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 "OutOfBoundsException.h"
15 #include "SBufDetailedStats.h"
16 #include "SBufExceptions.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
;
39 SBufStats::SBufStats()
40 : alloc(0), allocCopy(0), allocFromString(0), allocFromCString(0),
41 assignFast(0), clear(0), append(0), moves(0), toStream(0), setChar(0),
42 getChar(0), compareSlow(0), compareFast(0), copyOut(0),
43 rawAccess(0), nulTerminate(0), chop(0), trim(0), find(0), scanf(0),
44 caseChange(0), cowFast(0), cowSlow(0), live(0)
48 SBufStats::operator +=(const SBufStats
& ss
)
51 allocCopy
+= ss
.allocCopy
;
52 allocFromString
+= ss
.allocFromString
;
53 allocFromCString
+= ss
.allocFromCString
;
54 assignFast
+= ss
.assignFast
;
58 toStream
+= ss
.toStream
;
59 setChar
+= ss
.setChar
;
60 getChar
+= ss
.getChar
;
61 compareSlow
+= ss
.compareSlow
;
62 compareFast
+= ss
.compareFast
;
63 copyOut
+= ss
.copyOut
;
64 rawAccess
+= ss
.rawAccess
;
65 nulTerminate
+= ss
.nulTerminate
;
70 caseChange
+= ss
.caseChange
;
71 cowFast
+= ss
.cowFast
;
72 cowSlow
+= ss
.cowSlow
;
79 : store_(GetStorePrototype()), off_(0), len_(0)
81 debugs(24, 8, id
<< " created");
86 SBuf::SBuf(const SBuf
&S
)
87 : store_(S
.store_
), off_(S
.off_
), len_(S
.len_
)
89 debugs(24, 8, id
<< " created from id " << S
.id
);
95 SBuf::SBuf(const String
&S
)
96 : store_(GetStorePrototype()), off_(0), len_(0)
98 debugs(24, 8, id
<< " created from string");
99 assign(S
.rawBuf(), S
.size());
101 ++stats
.allocFromString
;
105 SBuf::SBuf(const std::string
&s
)
106 : store_(GetStorePrototype()), off_(0), len_(0)
108 debugs(24, 8, id
<< " created from std::string");
109 lowAppend(s
.data(),s
.length());
111 ++stats
.allocFromString
;
115 SBuf::SBuf(const char *S
, size_type n
)
116 : store_(GetStorePrototype()), off_(0), len_(0)
120 ++stats
.allocFromCString
;
124 SBuf::SBuf(const char *S
)
125 : store_(GetStorePrototype()), off_(0), len_(0)
129 ++stats
.allocFromCString
;
135 debugs(24, 8, id
<< " destructed");
137 recordSBufSizeAtDestruct(len_
);
141 SBuf::GetStorePrototype()
143 static MemBlob::Pointer InitialStore
= new MemBlob(0);
148 SBuf::assign(const SBuf
&S
)
150 debugs(24, 7, "assigning " << id
<< " from " << S
.id
);
151 if (&S
== this) //assignment to self. Noop.
161 SBuf::assign(const char *S
, size_type n
)
163 const Locker
blobKeeper(this, S
);
164 debugs(24, 6, id
<< " from c-string, n=" << n
<< ")");
166 return append(S
, n
); //bounds checked in append()
170 SBuf::reserveCapacity(size_type minCapacity
)
172 Must(minCapacity
<= maxSize
);
177 SBuf::rawSpace(size_type minSpace
)
179 Must(length() <= maxSize
- minSpace
);
180 debugs(24, 7, "reserving " << minSpace
<< " for " << id
);
182 // we're not concerned about RefCounts here,
183 // the store knows the last-used portion. If
184 // it's available, we're effectively claiming ownership
185 // of it. If it's not, we need to go away (realloc)
186 if (store_
->canAppend(off_
+len_
, minSpace
)) {
187 debugs(24, 7, id
<< " not growing");
190 // TODO: we may try to memmove before realloc'ing in order to avoid
191 // one allocation operation, if we're the sole owners of a MemBlob.
192 // Maybe some heuristic on off_ and length()?
193 cow(minSpace
+length());
201 //enabling this code path, the store will be freed and reinitialized
202 store_
= GetStorePrototype(); //uncomment to actually free storage upon clear()
204 //enabling this code path, we try to release the store without deallocating it.
205 // will be lazily reallocated if needed.
206 if (store_
->LockCount() == 1)
215 SBuf::append(const SBuf
&S
)
217 const Locker
blobKeeper(this, S
.buf());
218 return lowAppend(S
.buf(), S
.length());
222 SBuf::append(const char * S
, size_type Ssize
)
224 const Locker
blobKeeper(this, S
);
227 if (Ssize
== SBuf::npos
)
229 debugs(24, 7, "from c-string to id " << id
);
230 // coverity[access_dbuff_in_call]
231 return lowAppend(S
, Ssize
);
235 SBuf::append(const char c
)
237 return lowAppend(&c
, 1);
241 SBuf::Printf(const char *fmt
, ...)
243 // with printf() the fmt or an arg might be a dangerous char*
244 // NP: cant rely on vappendf() Locker because of clear()
245 const Locker
blobKeeper(this, buf());
256 SBuf::appendf(const char *fmt
, ...)
266 SBuf::vappendf(const char *fmt
, va_list vargs
)
268 // with (v)appendf() the fmt or an arg might be a dangerous char*
269 const Locker
blobKeeper(this, buf());
273 //reserve twice the format-string size, it's a likely heuristic
274 size_type requiredSpaceEstimate
= strlen(fmt
)*2;
276 char *space
= rawSpace(requiredSpaceEstimate
);
280 sz
= vsnprintf(space
, spaceSize(), fmt
, ap
);
283 sz
= vsnprintf(space
, spaceSize(), fmt
, vargs
);
286 /* check for possible overflow */
287 /* snprintf on Linux returns -1 on output errors, or the size
288 * that would have been written if enough space had been available */
289 /* vsnprintf is standard in C99 */
291 if (sz
>= static_cast<int>(spaceSize())) {
292 // not enough space on the first go, we now know how much we need
293 requiredSpaceEstimate
= sz
*2; // TODO: tune heuristics
294 space
= rawSpace(requiredSpaceEstimate
);
295 sz
= vsnprintf(space
, spaceSize(), fmt
, vargs
);
296 if (sz
< 0) // output error in vsnprintf
297 throw TextException("output error in second-go vsnprintf",__FILE__
,
301 if (sz
< 0) // output error in either vsnprintf
302 throw TextException("output error in vsnprintf",__FILE__
, __LINE__
);
304 // data was appended, update internal state
307 /* C99 specifies that the final '\0' is not counted in vsnprintf's
308 * return value. Older compilers/libraries might instead count it */
309 /* check whether '\0' was appended and counted */
310 static bool snPrintfTerminatorChecked
= false;
311 static bool snPrintfTerminatorCounted
= false;
312 if (!snPrintfTerminatorChecked
) {
314 snPrintfTerminatorCounted
= snprintf(testbuf
, sizeof(testbuf
),
316 snPrintfTerminatorChecked
= true;
318 if (snPrintfTerminatorCounted
) {
330 SBuf::print(std::ostream
&os
) const
332 os
.write(buf(), length());
338 SBuf::dump(std::ostream
&os
) const
343 os
<< ", offset:" << off_
347 os
<< '\'' << std::endl
;
350 // alternate implementation, based on Raw() API.
351 os
<< Raw("SBuf", buf(), length()) <<
353 ", offset:" << off_
<<
363 SBuf::setAt(size_type pos
, char toset
)
365 checkAccessBounds(pos
);
367 store_
->mem
[off_
+pos
] = toset
;
372 memcasecmp(const char *b1
, const char *b2
, SBuf::size_type len
)
376 rv
= tolower(*b1
)-tolower(*b2
);
387 SBuf::compare(const SBuf
&S
, const SBufCaseSensitive isCaseSensitive
, const size_type n
) const
390 debugs(24, 8, "length specified. substr and recurse");
391 return substr(0,n
).compare(S
.substr(0,n
),isCaseSensitive
);
394 const size_type byteCompareLen
= min(S
.length(), length());
397 debugs(24, 8, "comparing length " << byteCompareLen
);
398 if (isCaseSensitive
== caseSensitive
) {
399 rv
= memcmp(buf(), S
.buf(), byteCompareLen
);
401 rv
= memcasecmp(buf(), S
.buf(), byteCompareLen
);
404 debugs(24, 8, "result: " << rv
);
407 if (n
<= length() || n
<= S
.length()) {
408 debugs(24, 8, "same contents and bounded length. Equal");
411 if (length() == S
.length()) {
412 debugs(24, 8, "same contents and same length. Equal");
415 if (length() > S
.length()) {
416 debugs(24, 8, "lhs is longer than rhs. Result is 1");
419 debugs(24, 8, "rhs is longer than lhs. Result is -1");
424 SBuf::compare(const char *s
, const SBufCaseSensitive isCaseSensitive
, const size_type n
) const
426 // 0-length comparison is always true regardless of buffer states
432 // N-length compare MUST provide a non-NULL C-string pointer
435 // when this is a 0-length string, no need for any complexity.
441 // brute-force scan in order to avoid ever needing strlen() on a c-string.
443 const char *left
= buf();
444 const char *right
= s
;
446 // what area to scan.
447 // n may be npos, but we treat that as a huge positive value
448 size_type byteCount
= min(length(), n
);
450 // loop until we find a difference, a '\0', or reach the end of area to scan
451 if (isCaseSensitive
== caseSensitive
) {
452 while ((rv
= *left
- *right
++) == 0) {
453 if (*left
++ == '\0' || --byteCount
== 0)
457 while ((rv
= tolower(*left
) - tolower(*right
++)) == 0) {
458 if (*left
++ == '\0' || --byteCount
== 0)
463 // If we stopped scanning because we reached the end
464 // of buf() before we reached the end of s,
465 // pretend we have a 0-terminator there to compare.
466 // NP: the loop already incremented "right" ready for this comparison
467 if (!byteCount
&& length() < n
)
468 return '\0' - *right
;
470 // If we found a difference within the scan area,
471 // or we found a '\0',
472 // or all n characters were identical (and none was \0).
477 SBuf::startsWith(const SBuf
&S
, const SBufCaseSensitive isCaseSensitive
) const
479 debugs(24, 8, id
<< " startsWith " << S
.id
<< ", caseSensitive: " <<
481 if (length() < S
.length()) {
482 debugs(24, 8, "no, too short");
486 return (compare(S
, isCaseSensitive
, S
.length()) == 0);
490 SBuf::operator ==(const SBuf
& S
) const
492 debugs(24, 8, id
<< " == " << S
.id
);
493 if (length() != S
.length()) {
494 debugs(24, 8, "no, different lengths");
496 return false; //shortcut: must be equal length
498 if (store_
== S
.store_
&& off_
== S
.off_
) {
499 debugs(24, 8, "yes, same length and backing store");
501 return true; //shortcut: same store, offset and length
504 const bool rv
= (0 == memcmp(buf(), S
.buf(), length()));
505 debugs(24, 8, "returning " << rv
);
510 SBuf::operator !=(const SBuf
& S
) const
512 return !(*this == S
);
516 SBuf::consume(size_type n
)
521 n
= min(n
, length());
522 debugs(24, 8, id
<< " consume " << n
);
523 SBuf
rv(substr(0, n
));
529 SBufStats
& SBuf::GetStats()
535 SBuf::copy(char *dest
, size_type n
) const
537 size_type toexport
= min(n
,length());
538 memcpy(dest
, buf(), toexport
);
544 SBuf::rawContent() const
551 SBuf::forceSize(size_type newSize
)
553 debugs(24, 8, id
<< " force " << (newSize
> length() ? "grow" : "shrink") << " to length=" << newSize
);
555 Must(store_
->LockCount() == 1);
556 if (newSize
> min(maxSize
,store_
->capacity
-off_
))
557 throw SBufTooBigException(__FILE__
,__LINE__
);
559 store_
->size
= newSize
;
566 /* null-terminate the current buffer, by hand-appending a \0 at its tail but
567 * without increasing its length. May COW, the side-effect is to guarantee that
568 * the MemBlob's tail is availabe for us to use */
572 ++stats
.nulTerminate
;
577 SBuf::chop(size_type pos
, size_type n
)
579 if (pos
== npos
|| pos
> length())
582 if (n
== npos
|| (pos
+n
) > length())
585 // if there will be nothing left, reset the buffer while we can
586 if (pos
== length() || n
== 0) {
598 SBuf::trim(const SBuf
&toRemove
, bool atBeginning
, bool atEnd
)
602 const char *p
= bufEnd()-1;
603 while (!isEmpty() && memchr(toRemove
.buf(), *p
, toRemove
.length()) != NULL
) {
604 //current end-of-buf is in the searched set
610 const char *p
= buf();
611 while (!isEmpty() && memchr(toRemove
.buf(), *p
, toRemove
.length()) != NULL
) {
623 SBuf::substr(size_type pos
, size_type n
) const
626 rv
.chop(pos
, n
); //stats handled by callee
631 SBuf::find(char c
, size_type startPos
) const
635 if (startPos
== npos
) // can't find anything if we look past end of SBuf
638 // std::string returns npos if needle is outside hay
639 if (startPos
> length())
642 const void *i
= memchr(buf()+startPos
, (int)c
, (size_type
)length()-startPos
);
647 return (static_cast<const char *>(i
)-buf());
651 SBuf::find(const SBuf
&needle
, size_type startPos
) const
653 if (startPos
== npos
) { // can't find anything if we look past end of SBuf
658 // std::string allows needle to overhang hay but not start outside
659 if (startPos
> length()) {
664 // for empty needle std::string returns startPos
665 if (needle
.length() == 0) {
670 // if needle length is 1 use the char search
671 if (needle
.length() == 1)
672 return find(needle
[0], startPos
);
676 char *start
= buf()+startPos
;
677 char *lastPossible
= buf()+length()-needle
.length()+1;
678 char needleBegin
= needle
[0];
680 debugs(24, 7, "looking for " << needle
<< "starting at " << startPos
<<
682 while (start
< lastPossible
) {
684 debugs(24, 8, " begin=" << (void *) start
<<
685 ", lastPossible=" << (void*) lastPossible
);
686 tmp
= static_cast<char *>(memchr(start
, needleBegin
, lastPossible
-start
));
688 debugs(24, 8 , "First byte not found");
691 // lastPossible guarrantees no out-of-bounds with memcmp()
692 if (0 == memcmp(needle
.buf(), tmp
, needle
.length())) {
693 debugs(24, 8, "Found at " << (tmp
-buf()));
698 debugs(24, 8, "not found");
703 SBuf::rfind(const SBuf
&needle
, SBuf::size_type endPos
) const
705 // when the needle is 1 char, use the 1-char rfind()
706 if (needle
.length() == 1)
707 return rfind(needle
[0], endPos
);
711 // needle is bigger than haystack, impossible find
712 if (length() < needle
.length())
715 // if startPos is npos, std::string scans from the end of hay
716 if (endPos
== npos
|| endPos
> length()-needle
.length())
717 endPos
= length()-needle
.length();
719 // an empty needle found at the end of the haystack
720 if (needle
.length() == 0)
723 char *bufBegin
= buf();
724 char *cur
= bufBegin
+endPos
;
725 const char needleBegin
= needle
[0];
726 while (cur
>= bufBegin
) {
727 if (*cur
== needleBegin
) {
728 if (0 == memcmp(needle
.buf(), cur
, needle
.length())) {
739 SBuf::rfind(char c
, SBuf::size_type endPos
) const
743 // shortcut: haystack is empty, can't find anything by definition
747 // on npos input std::string compares last octet of hay
748 if (endPos
== npos
|| endPos
>= length()) {
751 // NP: off-by-one weirdness:
752 // endPos is an offset ... 0-based
753 // length() is a count ... 1-based
754 // memrhr() requires a 1-based count of space to scan.
761 const void *i
= memrchr(buf(), (int)c
, (size_type
)endPos
);
766 return (static_cast<const char *>(i
)-buf());
770 SBuf::findFirstOf(const CharacterSet
&set
, size_type startPos
) const
774 if (startPos
== npos
)
777 if (startPos
>= length())
780 debugs(24, 7, "first 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::findFirstNotOf(const CharacterSet
&set
, size_type startPos
) const
797 if (startPos
== npos
)
800 if (startPos
>= length())
803 debugs(24, 7, "first not of characterset " << set
.name
<< " in id " << id
);
804 char *cur
= buf()+startPos
;
805 const char *bufend
= bufEnd();
806 while (cur
< bufend
) {
811 debugs(24, 7, "not found");
816 SBuf::findLastOf(const CharacterSet
&set
, size_type endPos
) const
823 if (endPos
== npos
|| endPos
>= length())
824 endPos
= length() - 1;
826 debugs(24, 7, "last of characterset " << set
.name
<< " in id " << id
);
827 const char *start
= buf();
828 for (const char *cur
= start
+ endPos
; cur
>= start
; --cur
) {
832 debugs(24, 7, "not found");
837 SBuf::findLastNotOf(const CharacterSet
&set
, size_type endPos
) const
844 if (endPos
== npos
|| endPos
>= length())
845 endPos
= length() - 1;
847 debugs(24, 7, "last not of characterset " << set
.name
<< " in id " << id
);
848 const char *start
= buf();
849 for (const char *cur
= start
+ endPos
; cur
>= start
; --cur
) {
853 debugs(24, 7, "not found");
858 * TODO: borrow a sscanf implementation from Linux or similar?
859 * we'd really need a vsnscanf(3)... ? As an alternative, a
860 * light-regexp-like domain-specific syntax might be an idea.
863 SBuf::scanf(const char *format
, ...)
865 // with the format or an arg might be a dangerous char*
866 // that gets invalidated by c_str()
867 const Locker
blobKeeper(this, buf());
872 va_start(arg
, format
);
873 rv
= vsscanf(c_str(), format
, arg
);
879 SBufStats::dump(std::ostream
& os
) const
881 MemBlobStats ststats
= MemBlob::GetStats();
883 "SBuf stats:\nnumber of allocations: " << alloc
<<
884 "\ncopy-allocations: " << allocCopy
<<
885 "\ncopy-allocations from SquidString: " << allocFromString
<<
886 "\ncopy-allocations from C String: " << allocFromCString
<<
887 "\nlive references: " << live
<<
888 "\nno-copy assignments: " << assignFast
<<
889 "\nclearing operations: " << clear
<<
890 "\nappend operations: " << append
<<
891 "\nmove operations: " << moves
<<
892 "\ndump-to-ostream: " << toStream
<<
893 "\nset-char: " << setChar
<<
894 "\nget-char: " << getChar
<<
895 "\ncomparisons with data-scan: " << compareSlow
<<
896 "\ncomparisons not requiring data-scan: " << compareFast
<<
897 "\ncopy-out ops: " << copyOut
<<
898 "\nraw access to memory: " << rawAccess
<<
899 "\nNULL terminate C string: " << nulTerminate
<<
900 "\nchop operations: " << chop
<<
901 "\ntrim operations: " << trim
<<
902 "\nfind: " << find
<<
903 "\nscanf: " << scanf
<<
904 "\ncase-change ops: " << caseChange
<<
905 "\nCOW not actually requiring a copy: " << cowFast
<<
906 "\nCOW: " << cowSlow
<<
907 "\naverage store share factor: " <<
908 (ststats
.live
!= 0 ? static_cast<float>(live
)/ststats
.live
: 0) <<
916 debugs(24, 8, "\"" << *this << "\"");
917 for (size_type j
= 0; j
< length(); ++j
) {
918 const int c
= (*this)[j
];
920 setAt(j
, tolower(c
));
922 debugs(24, 8, "result: \"" << *this << "\"");
929 debugs(24, 8, "\"" << *this << "\"");
930 for (size_type j
= 0; j
< length(); ++j
) {
931 const int c
= (*this)[j
];
933 setAt(j
, toupper(c
));
935 debugs(24, 8, "result: \"" << *this << "\"");
940 * checks whether the requested 'pos' is within the bounds of the SBuf
941 * \throw OutOfBoundsException if access is out of bounds
944 SBuf::checkAccessBounds(size_type pos
) const
947 throw OutOfBoundsException(*this, pos
, __FILE__
, __LINE__
);
951 SBuf::toString() const
954 rv
.limitInit(buf(), length());
959 /** re-allocate the backing store of the SBuf.
961 * If there are contents in the SBuf, they will be copied over.
962 * NO verifications are made on the size parameters, it's up to the caller to
963 * make sure that the new size is big enough to hold the copied contents.
964 * The re-allocated storage MAY be bigger than the requested size due to size-chunking
965 * algorithms in MemBlock, it is guarranteed NOT to be smaller.
968 SBuf::reAlloc(size_type newsize
)
970 debugs(24, 8, id
<< " new size: " << newsize
);
971 if (newsize
> maxSize
)
972 throw SBufTooBigException(__FILE__
, __LINE__
);
973 MemBlob::Pointer newbuf
= new MemBlob(newsize
);
975 newbuf
->append(buf(), length());
979 debugs(24, 7, id
<< " new store capacity: " << store_
->capacity
);
983 SBuf::lowAppend(const char * memArea
, size_type areaSize
)
985 rawSpace(areaSize
); //called method also checks n <= maxSize()
986 store_
->append(memArea
, areaSize
);
993 * copy-on-write: make sure that we are the only holder of the backing store.
994 * If not, reallocate. If a new size is specified, and it is greater than the
995 * current length, the backing store will be extended as needed
998 SBuf::cow(SBuf::size_type newsize
)
1000 debugs(24, 8, id
<< " new size:" << newsize
);
1001 if (newsize
== npos
|| newsize
< length())
1004 if (store_
->LockCount() == 1 && newsize
== length()) {
1005 debugs(24, 8, id
<< " no cow needed");