2 * Copyright (C) 1996-2016 The Squid Software Foundation and contributors
4 * Squid software is distributed under GPLv2+ license and includes
5 * contributions from numerous individuals and organizations.
6 * Please see the COPYING and CONTRIBUTORS files for details.
10 #include "base/CharacterSet.h"
11 #include "base/RefCount.h"
13 #include "sbuf/DetailedStats.h"
14 #include "sbuf/Exceptions.h"
15 #include "sbuf/OutOfBoundsException.h"
16 #include "sbuf/SBuf.h"
27 #if defined HAVE_VA_COPY
28 #define VA_COPY va_copy
29 #elif defined HAVE___VA_COPY
30 #define VA_COPY __va_copy
33 InstanceIdDefinitions(SBuf
, "SBuf");
35 SBufStats
SBuf::stats
;
36 const SBuf::size_type
SBuf::npos
;
37 const SBuf::size_type
SBuf::maxSize
;
40 : store_(GetStorePrototype()), off_(0), len_(0)
42 debugs(24, 8, id
<< " created");
47 SBuf::SBuf(const SBuf
&S
)
48 : store_(S
.store_
), off_(S
.off_
), len_(S
.len_
)
50 debugs(24, 8, id
<< " created from id " << S
.id
);
56 SBuf::SBuf(const std::string
&s
)
57 : store_(GetStorePrototype()), off_(0), len_(0)
59 debugs(24, 8, id
<< " created from std::string");
60 lowAppend(s
.data(),s
.length());
65 SBuf::SBuf(const char *S
, size_type n
)
66 : store_(GetStorePrototype()), off_(0), len_(0)
70 ++stats
.allocFromCString
;
74 SBuf::SBuf(const char *S
)
75 : store_(GetStorePrototype()), off_(0), len_(0)
79 ++stats
.allocFromCString
;
85 debugs(24, 8, id
<< " destructed");
87 recordSBufSizeAtDestruct(len_
);
91 SBuf::GetStorePrototype()
93 static MemBlob::Pointer InitialStore
= new MemBlob(0);
98 SBuf::assign(const SBuf
&S
)
100 debugs(24, 7, "assigning " << id
<< " from " << S
.id
);
101 if (&S
== this) //assignment to self. Noop.
111 SBuf::assign(const char *S
, size_type n
)
113 const Locker
blobKeeper(this, S
);
114 debugs(24, 6, id
<< " from c-string, n=" << n
<< ")");
116 return append(S
, n
); //bounds checked in append()
120 SBuf::reserveCapacity(size_type minCapacity
)
122 Must(minCapacity
<= maxSize
);
127 SBuf::reserve(const SBufReservationRequirements
&req
)
129 debugs(24, 8, id
<< " was: " << off_
<< '+' << len_
<< '+' << spaceSize() <<
130 '=' << store_
->capacity
);
132 const bool mustRealloc
= !req
.allowShared
&& store_
->LockCount() > 1;
134 if (!mustRealloc
&& spaceSize() >= req
.minSpace
)
135 return spaceSize(); // the caller is content with what we have
137 /* only reallocation can make the caller happy */
139 if (!mustRealloc
&& len_
>= req
.maxCapacity
)
140 return spaceSize(); // but we cannot reallocate
142 const size_type desiredSpace
= std::max(req
.minSpace
, req
.idealSpace
);
143 const size_type newSpace
= std::min(desiredSpace
, maxSize
- len_
);
144 reserveCapacity(std::min(len_
+ newSpace
, req
.maxCapacity
));
145 debugs(24, 7, id
<< " now: " << off_
<< '+' << len_
<< '+' << spaceSize() <<
146 '=' << store_
->capacity
);
147 return spaceSize(); // reallocated and probably reserved enough space
151 SBuf::rawSpace(size_type minSpace
)
153 Must(length() <= maxSize
- minSpace
);
154 debugs(24, 7, "reserving " << minSpace
<< " for " << id
);
156 // we're not concerned about RefCounts here,
157 // the store knows the last-used portion. If
158 // it's available, we're effectively claiming ownership
159 // of it. If it's not, we need to go away (realloc)
160 if (store_
->canAppend(off_
+len_
, minSpace
)) {
161 debugs(24, 7, id
<< " not growing");
164 // TODO: we may try to memmove before realloc'ing in order to avoid
165 // one allocation operation, if we're the sole owners of a MemBlob.
166 // Maybe some heuristic on off_ and length()?
167 cow(minSpace
+length());
175 //enabling this code path, the store will be freed and reinitialized
176 store_
= GetStorePrototype(); //uncomment to actually free storage upon clear()
178 //enabling this code path, we try to release the store without deallocating it.
179 // will be lazily reallocated if needed.
180 if (store_
->LockCount() == 1)
189 SBuf::append(const SBuf
&S
)
191 if (isEmpty() && store_
== GetStorePrototype())
192 return (*this = S
); // optimization: avoid needless copying
194 const Locker
blobKeeper(this, S
.buf());
195 return lowAppend(S
.buf(), S
.length());
199 SBuf::append(const char * S
, size_type Ssize
)
201 const Locker
blobKeeper(this, S
);
204 if (Ssize
== SBuf::npos
)
206 debugs(24, 7, "from c-string to id " << id
);
207 // coverity[access_dbuff_in_call]
208 return lowAppend(S
, Ssize
);
212 SBuf::append(const char c
)
214 return lowAppend(&c
, 1);
218 SBuf::Printf(const char *fmt
, ...)
220 // with printf() the fmt or an arg might be a dangerous char*
221 // NP: cant rely on vappendf() Locker because of clear()
222 const Locker
blobKeeper(this, buf());
233 SBuf::appendf(const char *fmt
, ...)
243 SBuf::vappendf(const char *fmt
, va_list vargs
)
245 // with (v)appendf() the fmt or an arg might be a dangerous char*
246 const Locker
blobKeeper(this, buf());
250 //reserve twice the format-string size, it's a likely heuristic
251 size_type requiredSpaceEstimate
= strlen(fmt
)*2;
253 char *space
= rawSpace(requiredSpaceEstimate
);
257 sz
= vsnprintf(space
, spaceSize(), fmt
, ap
);
260 sz
= vsnprintf(space
, spaceSize(), fmt
, vargs
);
263 /* check for possible overflow */
264 /* snprintf on Linux returns -1 on output errors, or the size
265 * that would have been written if enough space had been available */
266 /* vsnprintf is standard in C99 */
268 if (sz
>= static_cast<int>(spaceSize())) {
269 // not enough space on the first go, we now know how much we need
270 requiredSpaceEstimate
= sz
*2; // TODO: tune heuristics
271 space
= rawSpace(requiredSpaceEstimate
);
272 sz
= vsnprintf(space
, spaceSize(), fmt
, vargs
);
273 if (sz
< 0) // output error in vsnprintf
274 throw TextException("output error in second-go vsnprintf",__FILE__
,
278 if (sz
< 0) // output error in either vsnprintf
279 throw TextException("output error in vsnprintf",__FILE__
, __LINE__
);
281 // data was appended, update internal state
284 /* C99 specifies that the final '\0' is not counted in vsnprintf's
285 * return value. Older compilers/libraries might instead count it */
286 /* check whether '\0' was appended and counted */
287 static bool snPrintfTerminatorChecked
= false;
288 static bool snPrintfTerminatorCounted
= false;
289 if (!snPrintfTerminatorChecked
) {
291 snPrintfTerminatorCounted
= snprintf(testbuf
, sizeof(testbuf
),
293 snPrintfTerminatorChecked
= true;
295 if (snPrintfTerminatorCounted
) {
307 SBuf::print(std::ostream
&os
) const
309 os
.write(buf(), length());
315 SBuf::dump(std::ostream
&os
) const
320 os
<< ", offset:" << off_
324 os
<< '\'' << std::endl
;
327 // alternate implementation, based on Raw() API.
328 os
<< Raw("SBuf", buf(), length()) <<
330 ", offset:" << off_
<<
340 SBuf::setAt(size_type pos
, char toset
)
342 checkAccessBounds(pos
);
344 store_
->mem
[off_
+pos
] = toset
;
349 memcasecmp(const char *b1
, const char *b2
, SBuf::size_type len
)
353 rv
= tolower(*b1
)-tolower(*b2
);
364 SBuf::compare(const SBuf
&S
, const SBufCaseSensitive isCaseSensitive
, const size_type n
) const
367 debugs(24, 8, "length specified. substr and recurse");
368 return substr(0,n
).compare(S
.substr(0,n
),isCaseSensitive
);
371 const size_type byteCompareLen
= min(S
.length(), length());
374 debugs(24, 8, "comparing length " << byteCompareLen
);
375 if (isCaseSensitive
== caseSensitive
) {
376 rv
= memcmp(buf(), S
.buf(), byteCompareLen
);
378 rv
= memcasecmp(buf(), S
.buf(), byteCompareLen
);
381 debugs(24, 8, "result: " << rv
);
384 if (n
<= length() || n
<= S
.length()) {
385 debugs(24, 8, "same contents and bounded length. Equal");
388 if (length() == S
.length()) {
389 debugs(24, 8, "same contents and same length. Equal");
392 if (length() > S
.length()) {
393 debugs(24, 8, "lhs is longer than rhs. Result is 1");
396 debugs(24, 8, "rhs is longer than lhs. Result is -1");
401 SBuf::compare(const char *s
, const SBufCaseSensitive isCaseSensitive
, const size_type n
) const
403 // 0-length comparison is always true regardless of buffer states
409 // N-length compare MUST provide a non-NULL C-string pointer
412 // when this is a 0-length string, no need for any complexity.
418 // brute-force scan in order to avoid ever needing strlen() on a c-string.
420 const char *left
= buf();
421 const char *right
= s
;
423 // what area to scan.
424 // n may be npos, but we treat that as a huge positive value
425 size_type byteCount
= min(length(), n
);
427 // loop until we find a difference, a '\0', or reach the end of area to scan
428 if (isCaseSensitive
== caseSensitive
) {
429 while ((rv
= *left
- *right
++) == 0) {
430 if (*left
++ == '\0' || --byteCount
== 0)
434 while ((rv
= tolower(*left
) - tolower(*right
++)) == 0) {
435 if (*left
++ == '\0' || --byteCount
== 0)
440 // If we stopped scanning because we reached the end
441 // of buf() before we reached the end of s,
442 // pretend we have a 0-terminator there to compare.
443 // NP: the loop already incremented "right" ready for this comparison
444 if (!byteCount
&& length() < n
)
445 return '\0' - *right
;
447 // If we found a difference within the scan area,
448 // or we found a '\0',
449 // or all n characters were identical (and none was \0).
454 SBuf::startsWith(const SBuf
&S
, const SBufCaseSensitive isCaseSensitive
) const
456 debugs(24, 8, id
<< " startsWith " << S
.id
<< ", caseSensitive: " <<
458 if (length() < S
.length()) {
459 debugs(24, 8, "no, too short");
463 return (compare(S
, isCaseSensitive
, S
.length()) == 0);
467 SBuf::operator ==(const SBuf
& S
) const
469 debugs(24, 8, id
<< " == " << S
.id
);
470 if (length() != S
.length()) {
471 debugs(24, 8, "no, different lengths");
473 return false; //shortcut: must be equal length
475 if (store_
== S
.store_
&& off_
== S
.off_
) {
476 debugs(24, 8, "yes, same length and backing store");
478 return true; //shortcut: same store, offset and length
481 const bool rv
= (0 == memcmp(buf(), S
.buf(), length()));
482 debugs(24, 8, "returning " << rv
);
487 SBuf::operator !=(const SBuf
& S
) const
489 return !(*this == S
);
493 SBuf::consume(size_type n
)
498 n
= min(n
, length());
499 debugs(24, 8, id
<< " consume " << n
);
500 SBuf
rv(substr(0, n
));
506 SBufStats
& SBuf::GetStats()
512 SBuf::copy(char *dest
, size_type n
) const
514 size_type toexport
= min(n
,length());
515 memcpy(dest
, buf(), toexport
);
521 SBuf::rawContent() const
528 SBuf::forceSize(size_type newSize
)
530 debugs(24, 8, id
<< " force " << (newSize
> length() ? "grow" : "shrink") << " to length=" << newSize
);
532 Must(store_
->LockCount() == 1);
533 if (newSize
> min(maxSize
,store_
->capacity
-off_
))
534 throw SBufTooBigException(__FILE__
,__LINE__
);
536 store_
->size
= newSize
;
543 /* null-terminate the current buffer, by hand-appending a \0 at its tail but
544 * without increasing its length. May COW, the side-effect is to guarantee that
545 * the MemBlob's tail is availabe for us to use */
549 ++stats
.nulTerminate
;
554 SBuf::chop(size_type pos
, size_type n
)
556 if (pos
== npos
|| pos
> length())
559 if (n
== npos
|| (pos
+n
) > length())
562 // if there will be nothing left, reset the buffer while we can
563 if (pos
== length() || n
== 0) {
575 SBuf::trim(const SBuf
&toRemove
, bool atBeginning
, bool atEnd
)
579 const char *p
= bufEnd()-1;
580 while (!isEmpty() && memchr(toRemove
.buf(), *p
, toRemove
.length()) != NULL
) {
581 //current end-of-buf is in the searched set
587 const char *p
= buf();
588 while (!isEmpty() && memchr(toRemove
.buf(), *p
, toRemove
.length()) != NULL
) {
600 SBuf::substr(size_type pos
, size_type n
) const
603 rv
.chop(pos
, n
); //stats handled by callee
608 SBuf::find(char c
, size_type startPos
) const
612 if (startPos
== npos
) // can't find anything if we look past end of SBuf
615 // std::string returns npos if needle is outside hay
616 if (startPos
> length())
619 const void *i
= memchr(buf()+startPos
, (int)c
, (size_type
)length()-startPos
);
624 return (static_cast<const char *>(i
)-buf());
628 SBuf::find(const SBuf
&needle
, size_type startPos
) const
630 if (startPos
== npos
) { // can't find anything if we look past end of SBuf
635 // std::string allows needle to overhang hay but not start outside
636 if (startPos
> length()) {
641 // for empty needle std::string returns startPos
642 if (needle
.length() == 0) {
647 // if needle length is 1 use the char search
648 if (needle
.length() == 1)
649 return find(needle
[0], startPos
);
653 char *start
= buf()+startPos
;
654 char *lastPossible
= buf()+length()-needle
.length()+1;
655 char needleBegin
= needle
[0];
657 debugs(24, 7, "looking for " << needle
<< "starting at " << startPos
<<
659 while (start
< lastPossible
) {
661 debugs(24, 8, " begin=" << (void *) start
<<
662 ", lastPossible=" << (void*) lastPossible
);
663 tmp
= static_cast<char *>(memchr(start
, needleBegin
, lastPossible
-start
));
665 debugs(24, 8 , "First byte not found");
668 // lastPossible guarrantees no out-of-bounds with memcmp()
669 if (0 == memcmp(needle
.buf(), tmp
, needle
.length())) {
670 debugs(24, 8, "Found at " << (tmp
-buf()));
675 debugs(24, 8, "not found");
680 SBuf::rfind(const SBuf
&needle
, SBuf::size_type endPos
) const
682 // when the needle is 1 char, use the 1-char rfind()
683 if (needle
.length() == 1)
684 return rfind(needle
[0], endPos
);
688 // needle is bigger than haystack, impossible find
689 if (length() < needle
.length())
692 // if startPos is npos, std::string scans from the end of hay
693 if (endPos
== npos
|| endPos
> length()-needle
.length())
694 endPos
= length()-needle
.length();
696 // an empty needle found at the end of the haystack
697 if (needle
.length() == 0)
700 char *bufBegin
= buf();
701 char *cur
= bufBegin
+endPos
;
702 const char needleBegin
= needle
[0];
703 while (cur
>= bufBegin
) {
704 if (*cur
== needleBegin
) {
705 if (0 == memcmp(needle
.buf(), cur
, needle
.length())) {
716 SBuf::rfind(char c
, SBuf::size_type endPos
) const
720 // shortcut: haystack is empty, can't find anything by definition
724 // on npos input std::string compares last octet of hay
725 if (endPos
== npos
|| endPos
>= length()) {
728 // NP: off-by-one weirdness:
729 // endPos is an offset ... 0-based
730 // length() is a count ... 1-based
731 // memrhr() requires a 1-based count of space to scan.
738 const void *i
= memrchr(buf(), (int)c
, (size_type
)endPos
);
743 return (static_cast<const char *>(i
)-buf());
747 SBuf::findFirstOf(const CharacterSet
&set
, size_type startPos
) const
751 if (startPos
== npos
)
754 if (startPos
>= length())
757 debugs(24, 7, "first of characterset " << set
.name
<< " in id " << id
);
758 char *cur
= buf()+startPos
;
759 const char *bufend
= bufEnd();
760 while (cur
< bufend
) {
765 debugs(24, 7, "not found");
770 SBuf::findFirstNotOf(const CharacterSet
&set
, size_type startPos
) const
774 if (startPos
== npos
)
777 if (startPos
>= length())
780 debugs(24, 7, "first not of characterset " << set
.name
<< " in id " << id
);
781 char *cur
= buf()+startPos
;
782 const char *bufend
= bufEnd();
783 while (cur
< bufend
) {
788 debugs(24, 7, "not found");
793 SBuf::findLastOf(const CharacterSet
&set
, size_type endPos
) const
800 if (endPos
== npos
|| endPos
>= length())
801 endPos
= length() - 1;
803 debugs(24, 7, "last of characterset " << set
.name
<< " in id " << id
);
804 const char *start
= buf();
805 for (const char *cur
= start
+ endPos
; cur
>= start
; --cur
) {
809 debugs(24, 7, "not found");
814 SBuf::findLastNotOf(const CharacterSet
&set
, size_type endPos
) const
821 if (endPos
== npos
|| endPos
>= length())
822 endPos
= length() - 1;
824 debugs(24, 7, "last not of characterset " << set
.name
<< " in id " << id
);
825 const char *start
= buf();
826 for (const char *cur
= start
+ endPos
; cur
>= start
; --cur
) {
830 debugs(24, 7, "not found");
837 debugs(24, 8, "\"" << *this << "\"");
838 for (size_type j
= 0; j
< length(); ++j
) {
839 const int c
= (*this)[j
];
841 setAt(j
, tolower(c
));
843 debugs(24, 8, "result: \"" << *this << "\"");
850 debugs(24, 8, "\"" << *this << "\"");
851 for (size_type j
= 0; j
< length(); ++j
) {
852 const int c
= (*this)[j
];
854 setAt(j
, toupper(c
));
856 debugs(24, 8, "result: \"" << *this << "\"");
861 * checks whether the requested 'pos' is within the bounds of the SBuf
862 * \throw OutOfBoundsException if access is out of bounds
865 SBuf::checkAccessBounds(size_type pos
) const
868 throw OutOfBoundsException(*this, pos
, __FILE__
, __LINE__
);
871 /** re-allocate the backing store of the SBuf.
873 * If there are contents in the SBuf, they will be copied over.
874 * NO verifications are made on the size parameters, it's up to the caller to
875 * make sure that the new size is big enough to hold the copied contents.
876 * The re-allocated storage MAY be bigger than the requested size due to size-chunking
877 * algorithms in MemBlock, it is guarranteed NOT to be smaller.
880 SBuf::reAlloc(size_type newsize
)
882 debugs(24, 8, id
<< " new size: " << newsize
);
883 if (newsize
> maxSize
)
884 throw SBufTooBigException(__FILE__
, __LINE__
);
885 MemBlob::Pointer newbuf
= new MemBlob(newsize
);
887 newbuf
->append(buf(), length());
891 debugs(24, 7, id
<< " new store capacity: " << store_
->capacity
);
895 SBuf::lowAppend(const char * memArea
, size_type areaSize
)
897 rawSpace(areaSize
); //called method also checks n <= maxSize()
898 store_
->append(memArea
, areaSize
);
905 * copy-on-write: make sure that we are the only holder of the backing store.
906 * If not, reallocate. If a new size is specified, and it is greater than the
907 * current length, the backing store will be extended as needed
910 SBuf::cow(SBuf::size_type newsize
)
912 debugs(24, 8, id
<< " new size:" << newsize
);
913 if (newsize
== npos
|| newsize
< length())
916 if (store_
->LockCount() == 1 && newsize
== length()) {
917 debugs(24, 8, id
<< " no cow needed");