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 newSpace
= std::min(req
.idealSpace
, maxSize
- len_
);
143 reserveCapacity(std::min(len_
+ newSpace
, req
.maxCapacity
));
144 debugs(24, 7, id
<< " now: " << off_
<< '+' << len_
<< '+' << spaceSize() <<
145 '=' << store_
->capacity
);
146 return spaceSize(); // reallocated and probably reserved enough space
150 SBuf::rawSpace(size_type minSpace
)
152 Must(length() <= maxSize
- minSpace
);
153 debugs(24, 7, "reserving " << minSpace
<< " for " << id
);
155 // we're not concerned about RefCounts here,
156 // the store knows the last-used portion. If
157 // it's available, we're effectively claiming ownership
158 // of it. If it's not, we need to go away (realloc)
159 if (store_
->canAppend(off_
+len_
, minSpace
)) {
160 debugs(24, 7, id
<< " not growing");
163 // TODO: we may try to memmove before realloc'ing in order to avoid
164 // one allocation operation, if we're the sole owners of a MemBlob.
165 // Maybe some heuristic on off_ and length()?
166 cow(minSpace
+length());
174 //enabling this code path, the store will be freed and reinitialized
175 store_
= GetStorePrototype(); //uncomment to actually free storage upon clear()
177 //enabling this code path, we try to release the store without deallocating it.
178 // will be lazily reallocated if needed.
179 if (store_
->LockCount() == 1)
188 SBuf::append(const SBuf
&S
)
190 const Locker
blobKeeper(this, S
.buf());
191 return lowAppend(S
.buf(), S
.length());
195 SBuf::append(const char * S
, size_type Ssize
)
197 const Locker
blobKeeper(this, S
);
200 if (Ssize
== SBuf::npos
)
202 debugs(24, 7, "from c-string to id " << id
);
203 // coverity[access_dbuff_in_call]
204 return lowAppend(S
, Ssize
);
208 SBuf::append(const char c
)
210 return lowAppend(&c
, 1);
214 SBuf::Printf(const char *fmt
, ...)
216 // with printf() the fmt or an arg might be a dangerous char*
217 // NP: cant rely on vappendf() Locker because of clear()
218 const Locker
blobKeeper(this, buf());
229 SBuf::appendf(const char *fmt
, ...)
239 SBuf::vappendf(const char *fmt
, va_list vargs
)
241 // with (v)appendf() the fmt or an arg might be a dangerous char*
242 const Locker
blobKeeper(this, buf());
246 //reserve twice the format-string size, it's a likely heuristic
247 size_type requiredSpaceEstimate
= strlen(fmt
)*2;
249 char *space
= rawSpace(requiredSpaceEstimate
);
253 sz
= vsnprintf(space
, spaceSize(), fmt
, ap
);
256 sz
= vsnprintf(space
, spaceSize(), fmt
, vargs
);
259 /* check for possible overflow */
260 /* snprintf on Linux returns -1 on output errors, or the size
261 * that would have been written if enough space had been available */
262 /* vsnprintf is standard in C99 */
264 if (sz
>= static_cast<int>(spaceSize())) {
265 // not enough space on the first go, we now know how much we need
266 requiredSpaceEstimate
= sz
*2; // TODO: tune heuristics
267 space
= rawSpace(requiredSpaceEstimate
);
268 sz
= vsnprintf(space
, spaceSize(), fmt
, vargs
);
269 if (sz
< 0) // output error in vsnprintf
270 throw TextException("output error in second-go vsnprintf",__FILE__
,
274 if (sz
< 0) // output error in either vsnprintf
275 throw TextException("output error in vsnprintf",__FILE__
, __LINE__
);
277 // data was appended, update internal state
280 /* C99 specifies that the final '\0' is not counted in vsnprintf's
281 * return value. Older compilers/libraries might instead count it */
282 /* check whether '\0' was appended and counted */
283 static bool snPrintfTerminatorChecked
= false;
284 static bool snPrintfTerminatorCounted
= false;
285 if (!snPrintfTerminatorChecked
) {
287 snPrintfTerminatorCounted
= snprintf(testbuf
, sizeof(testbuf
),
289 snPrintfTerminatorChecked
= true;
291 if (snPrintfTerminatorCounted
) {
303 SBuf::print(std::ostream
&os
) const
305 os
.write(buf(), length());
311 SBuf::dump(std::ostream
&os
) const
316 os
<< ", offset:" << off_
320 os
<< '\'' << std::endl
;
323 // alternate implementation, based on Raw() API.
324 os
<< Raw("SBuf", buf(), length()) <<
326 ", offset:" << off_
<<
336 SBuf::setAt(size_type pos
, char toset
)
338 checkAccessBounds(pos
);
340 store_
->mem
[off_
+pos
] = toset
;
345 memcasecmp(const char *b1
, const char *b2
, SBuf::size_type len
)
349 rv
= tolower(*b1
)-tolower(*b2
);
360 SBuf::compare(const SBuf
&S
, const SBufCaseSensitive isCaseSensitive
, const size_type n
) const
363 debugs(24, 8, "length specified. substr and recurse");
364 return substr(0,n
).compare(S
.substr(0,n
),isCaseSensitive
);
367 const size_type byteCompareLen
= min(S
.length(), length());
370 debugs(24, 8, "comparing length " << byteCompareLen
);
371 if (isCaseSensitive
== caseSensitive
) {
372 rv
= memcmp(buf(), S
.buf(), byteCompareLen
);
374 rv
= memcasecmp(buf(), S
.buf(), byteCompareLen
);
377 debugs(24, 8, "result: " << rv
);
380 if (n
<= length() || n
<= S
.length()) {
381 debugs(24, 8, "same contents and bounded length. Equal");
384 if (length() == S
.length()) {
385 debugs(24, 8, "same contents and same length. Equal");
388 if (length() > S
.length()) {
389 debugs(24, 8, "lhs is longer than rhs. Result is 1");
392 debugs(24, 8, "rhs is longer than lhs. Result is -1");
397 SBuf::compare(const char *s
, const SBufCaseSensitive isCaseSensitive
, const size_type n
) const
399 // 0-length comparison is always true regardless of buffer states
405 // N-length compare MUST provide a non-NULL C-string pointer
408 // when this is a 0-length string, no need for any complexity.
414 // brute-force scan in order to avoid ever needing strlen() on a c-string.
416 const char *left
= buf();
417 const char *right
= s
;
419 // what area to scan.
420 // n may be npos, but we treat that as a huge positive value
421 size_type byteCount
= min(length(), n
);
423 // loop until we find a difference, a '\0', or reach the end of area to scan
424 if (isCaseSensitive
== caseSensitive
) {
425 while ((rv
= *left
- *right
++) == 0) {
426 if (*left
++ == '\0' || --byteCount
== 0)
430 while ((rv
= tolower(*left
) - tolower(*right
++)) == 0) {
431 if (*left
++ == '\0' || --byteCount
== 0)
436 // If we stopped scanning because we reached the end
437 // of buf() before we reached the end of s,
438 // pretend we have a 0-terminator there to compare.
439 // NP: the loop already incremented "right" ready for this comparison
440 if (!byteCount
&& length() < n
)
441 return '\0' - *right
;
443 // If we found a difference within the scan area,
444 // or we found a '\0',
445 // or all n characters were identical (and none was \0).
450 SBuf::startsWith(const SBuf
&S
, const SBufCaseSensitive isCaseSensitive
) const
452 debugs(24, 8, id
<< " startsWith " << S
.id
<< ", caseSensitive: " <<
454 if (length() < S
.length()) {
455 debugs(24, 8, "no, too short");
459 return (compare(S
, isCaseSensitive
, S
.length()) == 0);
463 SBuf::operator ==(const SBuf
& S
) const
465 debugs(24, 8, id
<< " == " << S
.id
);
466 if (length() != S
.length()) {
467 debugs(24, 8, "no, different lengths");
469 return false; //shortcut: must be equal length
471 if (store_
== S
.store_
&& off_
== S
.off_
) {
472 debugs(24, 8, "yes, same length and backing store");
474 return true; //shortcut: same store, offset and length
477 const bool rv
= (0 == memcmp(buf(), S
.buf(), length()));
478 debugs(24, 8, "returning " << rv
);
483 SBuf::operator !=(const SBuf
& S
) const
485 return !(*this == S
);
489 SBuf::consume(size_type n
)
494 n
= min(n
, length());
495 debugs(24, 8, id
<< " consume " << n
);
496 SBuf
rv(substr(0, n
));
502 SBufStats
& SBuf::GetStats()
508 SBuf::copy(char *dest
, size_type n
) const
510 size_type toexport
= min(n
,length());
511 memcpy(dest
, buf(), toexport
);
517 SBuf::rawContent() const
524 SBuf::forceSize(size_type newSize
)
526 debugs(24, 8, id
<< " force " << (newSize
> length() ? "grow" : "shrink") << " to length=" << newSize
);
528 Must(store_
->LockCount() == 1);
529 if (newSize
> min(maxSize
,store_
->capacity
-off_
))
530 throw SBufTooBigException(__FILE__
,__LINE__
);
532 store_
->size
= newSize
;
539 /* null-terminate the current buffer, by hand-appending a \0 at its tail but
540 * without increasing its length. May COW, the side-effect is to guarantee that
541 * the MemBlob's tail is availabe for us to use */
545 ++stats
.nulTerminate
;
550 SBuf::chop(size_type pos
, size_type n
)
552 if (pos
== npos
|| pos
> length())
555 if (n
== npos
|| (pos
+n
) > length())
558 // if there will be nothing left, reset the buffer while we can
559 if (pos
== length() || n
== 0) {
571 SBuf::trim(const SBuf
&toRemove
, bool atBeginning
, bool atEnd
)
575 const char *p
= bufEnd()-1;
576 while (!isEmpty() && memchr(toRemove
.buf(), *p
, toRemove
.length()) != NULL
) {
577 //current end-of-buf is in the searched set
583 const char *p
= buf();
584 while (!isEmpty() && memchr(toRemove
.buf(), *p
, toRemove
.length()) != NULL
) {
596 SBuf::substr(size_type pos
, size_type n
) const
599 rv
.chop(pos
, n
); //stats handled by callee
604 SBuf::find(char c
, size_type startPos
) const
608 if (startPos
== npos
) // can't find anything if we look past end of SBuf
611 // std::string returns npos if needle is outside hay
612 if (startPos
> length())
615 const void *i
= memchr(buf()+startPos
, (int)c
, (size_type
)length()-startPos
);
620 return (static_cast<const char *>(i
)-buf());
624 SBuf::find(const SBuf
&needle
, size_type startPos
) const
626 if (startPos
== npos
) { // can't find anything if we look past end of SBuf
631 // std::string allows needle to overhang hay but not start outside
632 if (startPos
> length()) {
637 // for empty needle std::string returns startPos
638 if (needle
.length() == 0) {
643 // if needle length is 1 use the char search
644 if (needle
.length() == 1)
645 return find(needle
[0], startPos
);
649 char *start
= buf()+startPos
;
650 char *lastPossible
= buf()+length()-needle
.length()+1;
651 char needleBegin
= needle
[0];
653 debugs(24, 7, "looking for " << needle
<< "starting at " << startPos
<<
655 while (start
< lastPossible
) {
657 debugs(24, 8, " begin=" << (void *) start
<<
658 ", lastPossible=" << (void*) lastPossible
);
659 tmp
= static_cast<char *>(memchr(start
, needleBegin
, lastPossible
-start
));
661 debugs(24, 8 , "First byte not found");
664 // lastPossible guarrantees no out-of-bounds with memcmp()
665 if (0 == memcmp(needle
.buf(), tmp
, needle
.length())) {
666 debugs(24, 8, "Found at " << (tmp
-buf()));
671 debugs(24, 8, "not found");
676 SBuf::rfind(const SBuf
&needle
, SBuf::size_type endPos
) const
678 // when the needle is 1 char, use the 1-char rfind()
679 if (needle
.length() == 1)
680 return rfind(needle
[0], endPos
);
684 // needle is bigger than haystack, impossible find
685 if (length() < needle
.length())
688 // if startPos is npos, std::string scans from the end of hay
689 if (endPos
== npos
|| endPos
> length()-needle
.length())
690 endPos
= length()-needle
.length();
692 // an empty needle found at the end of the haystack
693 if (needle
.length() == 0)
696 char *bufBegin
= buf();
697 char *cur
= bufBegin
+endPos
;
698 const char needleBegin
= needle
[0];
699 while (cur
>= bufBegin
) {
700 if (*cur
== needleBegin
) {
701 if (0 == memcmp(needle
.buf(), cur
, needle
.length())) {
712 SBuf::rfind(char c
, SBuf::size_type endPos
) const
716 // shortcut: haystack is empty, can't find anything by definition
720 // on npos input std::string compares last octet of hay
721 if (endPos
== npos
|| endPos
>= length()) {
724 // NP: off-by-one weirdness:
725 // endPos is an offset ... 0-based
726 // length() is a count ... 1-based
727 // memrhr() requires a 1-based count of space to scan.
734 const void *i
= memrchr(buf(), (int)c
, (size_type
)endPos
);
739 return (static_cast<const char *>(i
)-buf());
743 SBuf::findFirstOf(const CharacterSet
&set
, size_type startPos
) const
747 if (startPos
== npos
)
750 if (startPos
>= length())
753 debugs(24, 7, "first of characterset " << set
.name
<< " in id " << id
);
754 char *cur
= buf()+startPos
;
755 const char *bufend
= bufEnd();
756 while (cur
< bufend
) {
761 debugs(24, 7, "not found");
766 SBuf::findFirstNotOf(const CharacterSet
&set
, size_type startPos
) const
770 if (startPos
== npos
)
773 if (startPos
>= length())
776 debugs(24, 7, "first not of characterset " << set
.name
<< " in id " << id
);
777 char *cur
= buf()+startPos
;
778 const char *bufend
= bufEnd();
779 while (cur
< bufend
) {
784 debugs(24, 7, "not found");
789 SBuf::findLastOf(const CharacterSet
&set
, size_type endPos
) const
796 if (endPos
== npos
|| endPos
>= length())
797 endPos
= length() - 1;
799 debugs(24, 7, "last of characterset " << set
.name
<< " in id " << id
);
800 const char *start
= buf();
801 for (const char *cur
= start
+ endPos
; cur
>= start
; --cur
) {
805 debugs(24, 7, "not found");
810 SBuf::findLastNotOf(const CharacterSet
&set
, size_type endPos
) const
817 if (endPos
== npos
|| endPos
>= length())
818 endPos
= length() - 1;
820 debugs(24, 7, "last not of characterset " << set
.name
<< " in id " << id
);
821 const char *start
= buf();
822 for (const char *cur
= start
+ endPos
; cur
>= start
; --cur
) {
826 debugs(24, 7, "not found");
833 debugs(24, 8, "\"" << *this << "\"");
834 for (size_type j
= 0; j
< length(); ++j
) {
835 const int c
= (*this)[j
];
837 setAt(j
, tolower(c
));
839 debugs(24, 8, "result: \"" << *this << "\"");
846 debugs(24, 8, "\"" << *this << "\"");
847 for (size_type j
= 0; j
< length(); ++j
) {
848 const int c
= (*this)[j
];
850 setAt(j
, toupper(c
));
852 debugs(24, 8, "result: \"" << *this << "\"");
857 * checks whether the requested 'pos' is within the bounds of the SBuf
858 * \throw OutOfBoundsException if access is out of bounds
861 SBuf::checkAccessBounds(size_type pos
) const
864 throw OutOfBoundsException(*this, pos
, __FILE__
, __LINE__
);
867 /** re-allocate the backing store of the SBuf.
869 * If there are contents in the SBuf, they will be copied over.
870 * NO verifications are made on the size parameters, it's up to the caller to
871 * make sure that the new size is big enough to hold the copied contents.
872 * The re-allocated storage MAY be bigger than the requested size due to size-chunking
873 * algorithms in MemBlock, it is guarranteed NOT to be smaller.
876 SBuf::reAlloc(size_type newsize
)
878 debugs(24, 8, id
<< " new size: " << newsize
);
879 if (newsize
> maxSize
)
880 throw SBufTooBigException(__FILE__
, __LINE__
);
881 MemBlob::Pointer newbuf
= new MemBlob(newsize
);
883 newbuf
->append(buf(), length());
887 debugs(24, 7, id
<< " new store capacity: " << store_
->capacity
);
891 SBuf::lowAppend(const char * memArea
, size_type areaSize
)
893 rawSpace(areaSize
); //called method also checks n <= maxSize()
894 store_
->append(memArea
, areaSize
);
901 * copy-on-write: make sure that we are the only holder of the backing store.
902 * If not, reallocate. If a new size is specified, and it is greater than the
903 * current length, the backing store will be extended as needed
906 SBuf::cow(SBuf::size_type newsize
)
908 debugs(24, 8, id
<< " new size:" << newsize
);
909 if (newsize
== npos
|| newsize
< length())
912 if (store_
->LockCount() == 1 && newsize
== length()) {
913 debugs(24, 8, id
<< " no cow needed");