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 "sbuf/DetailedStats.h"
16 #include "sbuf/Exceptions.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), 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 allocFromCString
+= ss
.allocFromCString
;
53 assignFast
+= ss
.assignFast
;
57 toStream
+= ss
.toStream
;
58 setChar
+= ss
.setChar
;
59 getChar
+= ss
.getChar
;
60 compareSlow
+= ss
.compareSlow
;
61 compareFast
+= ss
.compareFast
;
62 copyOut
+= ss
.copyOut
;
63 rawAccess
+= ss
.rawAccess
;
64 nulTerminate
+= ss
.nulTerminate
;
69 caseChange
+= ss
.caseChange
;
70 cowFast
+= ss
.cowFast
;
71 cowSlow
+= ss
.cowSlow
;
78 : store_(GetStorePrototype()), off_(0), len_(0)
80 debugs(24, 8, id
<< " created");
85 SBuf::SBuf(const SBuf
&S
)
86 : store_(S
.store_
), off_(S
.off_
), len_(S
.len_
)
88 debugs(24, 8, id
<< " created from id " << S
.id
);
94 SBuf::SBuf(const std::string
&s
)
95 : store_(GetStorePrototype()), off_(0), len_(0)
97 debugs(24, 8, id
<< " created from std::string");
98 lowAppend(s
.data(),s
.length());
103 SBuf::SBuf(const char *S
, size_type n
)
104 : store_(GetStorePrototype()), off_(0), len_(0)
108 ++stats
.allocFromCString
;
112 SBuf::SBuf(const char *S
)
113 : store_(GetStorePrototype()), off_(0), len_(0)
117 ++stats
.allocFromCString
;
123 debugs(24, 8, id
<< " destructed");
125 recordSBufSizeAtDestruct(len_
);
129 SBuf::GetStorePrototype()
131 static MemBlob::Pointer InitialStore
= new MemBlob(0);
136 SBuf::assign(const SBuf
&S
)
138 debugs(24, 7, "assigning " << id
<< " from " << S
.id
);
139 if (&S
== this) //assignment to self. Noop.
149 SBuf::assign(const char *S
, size_type n
)
151 const Locker
blobKeeper(this, S
);
152 debugs(24, 6, id
<< " from c-string, n=" << n
<< ")");
154 return append(S
, n
); //bounds checked in append()
158 SBuf::reserveCapacity(size_type minCapacity
)
160 Must(minCapacity
<= maxSize
);
165 SBuf::rawSpace(size_type minSpace
)
167 Must(length() <= maxSize
- minSpace
);
168 debugs(24, 7, "reserving " << minSpace
<< " for " << id
);
170 // we're not concerned about RefCounts here,
171 // the store knows the last-used portion. If
172 // it's available, we're effectively claiming ownership
173 // of it. If it's not, we need to go away (realloc)
174 if (store_
->canAppend(off_
+len_
, minSpace
)) {
175 debugs(24, 7, id
<< " not growing");
178 // TODO: we may try to memmove before realloc'ing in order to avoid
179 // one allocation operation, if we're the sole owners of a MemBlob.
180 // Maybe some heuristic on off_ and length()?
181 cow(minSpace
+length());
189 //enabling this code path, the store will be freed and reinitialized
190 store_
= GetStorePrototype(); //uncomment to actually free storage upon clear()
192 //enabling this code path, we try to release the store without deallocating it.
193 // will be lazily reallocated if needed.
194 if (store_
->LockCount() == 1)
203 SBuf::append(const SBuf
&S
)
205 const Locker
blobKeeper(this, S
.buf());
206 return lowAppend(S
.buf(), S
.length());
210 SBuf::append(const char * S
, size_type Ssize
)
212 const Locker
blobKeeper(this, S
);
215 if (Ssize
== SBuf::npos
)
217 debugs(24, 7, "from c-string to id " << id
);
218 // coverity[access_dbuff_in_call]
219 return lowAppend(S
, Ssize
);
223 SBuf::append(const char c
)
225 return lowAppend(&c
, 1);
229 SBuf::Printf(const char *fmt
, ...)
231 // with printf() the fmt or an arg might be a dangerous char*
232 // NP: cant rely on vappendf() Locker because of clear()
233 const Locker
blobKeeper(this, buf());
244 SBuf::appendf(const char *fmt
, ...)
254 SBuf::vappendf(const char *fmt
, va_list vargs
)
256 // with (v)appendf() the fmt or an arg might be a dangerous char*
257 const Locker
blobKeeper(this, buf());
261 //reserve twice the format-string size, it's a likely heuristic
262 size_type requiredSpaceEstimate
= strlen(fmt
)*2;
264 char *space
= rawSpace(requiredSpaceEstimate
);
268 sz
= vsnprintf(space
, spaceSize(), fmt
, ap
);
271 sz
= vsnprintf(space
, spaceSize(), fmt
, vargs
);
274 /* check for possible overflow */
275 /* snprintf on Linux returns -1 on output errors, or the size
276 * that would have been written if enough space had been available */
277 /* vsnprintf is standard in C99 */
279 if (sz
>= static_cast<int>(spaceSize())) {
280 // not enough space on the first go, we now know how much we need
281 requiredSpaceEstimate
= sz
*2; // TODO: tune heuristics
282 space
= rawSpace(requiredSpaceEstimate
);
283 sz
= vsnprintf(space
, spaceSize(), fmt
, vargs
);
284 if (sz
< 0) // output error in vsnprintf
285 throw TextException("output error in second-go vsnprintf",__FILE__
,
289 if (sz
< 0) // output error in either vsnprintf
290 throw TextException("output error in vsnprintf",__FILE__
, __LINE__
);
292 // data was appended, update internal state
295 /* C99 specifies that the final '\0' is not counted in vsnprintf's
296 * return value. Older compilers/libraries might instead count it */
297 /* check whether '\0' was appended and counted */
298 static bool snPrintfTerminatorChecked
= false;
299 static bool snPrintfTerminatorCounted
= false;
300 if (!snPrintfTerminatorChecked
) {
302 snPrintfTerminatorCounted
= snprintf(testbuf
, sizeof(testbuf
),
304 snPrintfTerminatorChecked
= true;
306 if (snPrintfTerminatorCounted
) {
318 SBuf::print(std::ostream
&os
) const
320 os
.write(buf(), length());
326 SBuf::dump(std::ostream
&os
) const
331 os
<< ", offset:" << off_
335 os
<< '\'' << std::endl
;
338 // alternate implementation, based on Raw() API.
339 os
<< Raw("SBuf", buf(), length()) <<
341 ", offset:" << off_
<<
351 SBuf::setAt(size_type pos
, char toset
)
353 checkAccessBounds(pos
);
355 store_
->mem
[off_
+pos
] = toset
;
360 memcasecmp(const char *b1
, const char *b2
, SBuf::size_type len
)
364 rv
= tolower(*b1
)-tolower(*b2
);
375 SBuf::compare(const SBuf
&S
, const SBufCaseSensitive isCaseSensitive
, const size_type n
) const
378 debugs(24, 8, "length specified. substr and recurse");
379 return substr(0,n
).compare(S
.substr(0,n
),isCaseSensitive
);
382 const size_type byteCompareLen
= min(S
.length(), length());
385 debugs(24, 8, "comparing length " << byteCompareLen
);
386 if (isCaseSensitive
== caseSensitive
) {
387 rv
= memcmp(buf(), S
.buf(), byteCompareLen
);
389 rv
= memcasecmp(buf(), S
.buf(), byteCompareLen
);
392 debugs(24, 8, "result: " << rv
);
395 if (n
<= length() || n
<= S
.length()) {
396 debugs(24, 8, "same contents and bounded length. Equal");
399 if (length() == S
.length()) {
400 debugs(24, 8, "same contents and same length. Equal");
403 if (length() > S
.length()) {
404 debugs(24, 8, "lhs is longer than rhs. Result is 1");
407 debugs(24, 8, "rhs is longer than lhs. Result is -1");
412 SBuf::compare(const char *s
, const SBufCaseSensitive isCaseSensitive
, const size_type n
) const
414 // 0-length comparison is always true regardless of buffer states
420 // N-length compare MUST provide a non-NULL C-string pointer
423 // when this is a 0-length string, no need for any complexity.
429 // brute-force scan in order to avoid ever needing strlen() on a c-string.
431 const char *left
= buf();
432 const char *right
= s
;
434 // what area to scan.
435 // n may be npos, but we treat that as a huge positive value
436 size_type byteCount
= min(length(), n
);
438 // loop until we find a difference, a '\0', or reach the end of area to scan
439 if (isCaseSensitive
== caseSensitive
) {
440 while ((rv
= *left
- *right
++) == 0) {
441 if (*left
++ == '\0' || --byteCount
== 0)
445 while ((rv
= tolower(*left
) - tolower(*right
++)) == 0) {
446 if (*left
++ == '\0' || --byteCount
== 0)
451 // If we stopped scanning because we reached the end
452 // of buf() before we reached the end of s,
453 // pretend we have a 0-terminator there to compare.
454 // NP: the loop already incremented "right" ready for this comparison
455 if (!byteCount
&& length() < n
)
456 return '\0' - *right
;
458 // If we found a difference within the scan area,
459 // or we found a '\0',
460 // or all n characters were identical (and none was \0).
465 SBuf::startsWith(const SBuf
&S
, const SBufCaseSensitive isCaseSensitive
) const
467 debugs(24, 8, id
<< " startsWith " << S
.id
<< ", caseSensitive: " <<
469 if (length() < S
.length()) {
470 debugs(24, 8, "no, too short");
474 return (compare(S
, isCaseSensitive
, S
.length()) == 0);
478 SBuf::operator ==(const SBuf
& S
) const
480 debugs(24, 8, id
<< " == " << S
.id
);
481 if (length() != S
.length()) {
482 debugs(24, 8, "no, different lengths");
484 return false; //shortcut: must be equal length
486 if (store_
== S
.store_
&& off_
== S
.off_
) {
487 debugs(24, 8, "yes, same length and backing store");
489 return true; //shortcut: same store, offset and length
492 const bool rv
= (0 == memcmp(buf(), S
.buf(), length()));
493 debugs(24, 8, "returning " << rv
);
498 SBuf::operator !=(const SBuf
& S
) const
500 return !(*this == S
);
504 SBuf::consume(size_type n
)
509 n
= min(n
, length());
510 debugs(24, 8, id
<< " consume " << n
);
511 SBuf
rv(substr(0, n
));
517 SBufStats
& SBuf::GetStats()
523 SBuf::copy(char *dest
, size_type n
) const
525 size_type toexport
= min(n
,length());
526 memcpy(dest
, buf(), toexport
);
532 SBuf::rawContent() const
539 SBuf::forceSize(size_type newSize
)
541 debugs(24, 8, id
<< " force " << (newSize
> length() ? "grow" : "shrink") << " to length=" << newSize
);
543 Must(store_
->LockCount() == 1);
544 if (newSize
> min(maxSize
,store_
->capacity
-off_
))
545 throw SBufTooBigException(__FILE__
,__LINE__
);
547 store_
->size
= newSize
;
554 /* null-terminate the current buffer, by hand-appending a \0 at its tail but
555 * without increasing its length. May COW, the side-effect is to guarantee that
556 * the MemBlob's tail is availabe for us to use */
560 ++stats
.nulTerminate
;
565 SBuf::chop(size_type pos
, size_type n
)
567 if (pos
== npos
|| pos
> length())
570 if (n
== npos
|| (pos
+n
) > length())
573 // if there will be nothing left, reset the buffer while we can
574 if (pos
== length() || n
== 0) {
586 SBuf::trim(const SBuf
&toRemove
, bool atBeginning
, bool atEnd
)
590 const char *p
= bufEnd()-1;
591 while (!isEmpty() && memchr(toRemove
.buf(), *p
, toRemove
.length()) != NULL
) {
592 //current end-of-buf is in the searched set
598 const char *p
= buf();
599 while (!isEmpty() && memchr(toRemove
.buf(), *p
, toRemove
.length()) != NULL
) {
611 SBuf::substr(size_type pos
, size_type n
) const
614 rv
.chop(pos
, n
); //stats handled by callee
619 SBuf::find(char c
, size_type startPos
) const
623 if (startPos
== npos
) // can't find anything if we look past end of SBuf
626 // std::string returns npos if needle is outside hay
627 if (startPos
> length())
630 const void *i
= memchr(buf()+startPos
, (int)c
, (size_type
)length()-startPos
);
635 return (static_cast<const char *>(i
)-buf());
639 SBuf::find(const SBuf
&needle
, size_type startPos
) const
641 if (startPos
== npos
) { // can't find anything if we look past end of SBuf
646 // std::string allows needle to overhang hay but not start outside
647 if (startPos
> length()) {
652 // for empty needle std::string returns startPos
653 if (needle
.length() == 0) {
658 // if needle length is 1 use the char search
659 if (needle
.length() == 1)
660 return find(needle
[0], startPos
);
664 char *start
= buf()+startPos
;
665 char *lastPossible
= buf()+length()-needle
.length()+1;
666 char needleBegin
= needle
[0];
668 debugs(24, 7, "looking for " << needle
<< "starting at " << startPos
<<
670 while (start
< lastPossible
) {
672 debugs(24, 8, " begin=" << (void *) start
<<
673 ", lastPossible=" << (void*) lastPossible
);
674 tmp
= static_cast<char *>(memchr(start
, needleBegin
, lastPossible
-start
));
676 debugs(24, 8 , "First byte not found");
679 // lastPossible guarrantees no out-of-bounds with memcmp()
680 if (0 == memcmp(needle
.buf(), tmp
, needle
.length())) {
681 debugs(24, 8, "Found at " << (tmp
-buf()));
686 debugs(24, 8, "not found");
691 SBuf::rfind(const SBuf
&needle
, SBuf::size_type endPos
) const
693 // when the needle is 1 char, use the 1-char rfind()
694 if (needle
.length() == 1)
695 return rfind(needle
[0], endPos
);
699 // needle is bigger than haystack, impossible find
700 if (length() < needle
.length())
703 // if startPos is npos, std::string scans from the end of hay
704 if (endPos
== npos
|| endPos
> length()-needle
.length())
705 endPos
= length()-needle
.length();
707 // an empty needle found at the end of the haystack
708 if (needle
.length() == 0)
711 char *bufBegin
= buf();
712 char *cur
= bufBegin
+endPos
;
713 const char needleBegin
= needle
[0];
714 while (cur
>= bufBegin
) {
715 if (*cur
== needleBegin
) {
716 if (0 == memcmp(needle
.buf(), cur
, needle
.length())) {
727 SBuf::rfind(char c
, SBuf::size_type endPos
) const
731 // shortcut: haystack is empty, can't find anything by definition
735 // on npos input std::string compares last octet of hay
736 if (endPos
== npos
|| endPos
>= length()) {
739 // NP: off-by-one weirdness:
740 // endPos is an offset ... 0-based
741 // length() is a count ... 1-based
742 // memrhr() requires a 1-based count of space to scan.
749 const void *i
= memrchr(buf(), (int)c
, (size_type
)endPos
);
754 return (static_cast<const char *>(i
)-buf());
758 SBuf::findFirstOf(const CharacterSet
&set
, size_type startPos
) const
762 if (startPos
== npos
)
765 if (startPos
>= length())
768 debugs(24, 7, "first of characterset " << set
.name
<< " in id " << id
);
769 char *cur
= buf()+startPos
;
770 const char *bufend
= bufEnd();
771 while (cur
< bufend
) {
776 debugs(24, 7, "not found");
781 SBuf::findFirstNotOf(const CharacterSet
&set
, size_type startPos
) const
785 if (startPos
== npos
)
788 if (startPos
>= length())
791 debugs(24, 7, "first not of characterset " << set
.name
<< " in id " << id
);
792 char *cur
= buf()+startPos
;
793 const char *bufend
= bufEnd();
794 while (cur
< bufend
) {
799 debugs(24, 7, "not found");
804 SBuf::findLastOf(const CharacterSet
&set
, size_type endPos
) const
811 if (endPos
== npos
|| endPos
>= length())
812 endPos
= length() - 1;
814 debugs(24, 7, "last of characterset " << set
.name
<< " in id " << id
);
815 const char *start
= buf();
816 for (const char *cur
= start
+ endPos
; cur
>= start
; --cur
) {
820 debugs(24, 7, "not found");
825 SBuf::findLastNotOf(const CharacterSet
&set
, size_type endPos
) const
832 if (endPos
== npos
|| endPos
>= length())
833 endPos
= length() - 1;
835 debugs(24, 7, "last not of characterset " << set
.name
<< " in id " << id
);
836 const char *start
= buf();
837 for (const char *cur
= start
+ endPos
; cur
>= start
; --cur
) {
841 debugs(24, 7, "not found");
846 * TODO: borrow a sscanf implementation from Linux or similar?
847 * we'd really need a vsnscanf(3)... ? As an alternative, a
848 * light-regexp-like domain-specific syntax might be an idea.
851 SBuf::scanf(const char *format
, ...)
853 // with the format or an arg might be a dangerous char*
854 // that gets invalidated by c_str()
855 const Locker
blobKeeper(this, buf());
860 va_start(arg
, format
);
861 rv
= vsscanf(c_str(), format
, arg
);
867 SBufStats::dump(std::ostream
& os
) const
869 MemBlobStats ststats
= MemBlob::GetStats();
871 "SBuf stats:\nnumber of allocations: " << alloc
<<
872 "\ncopy-allocations: " << allocCopy
<<
873 "\ncopy-allocations from C String: " << allocFromCString
<<
874 "\nlive references: " << live
<<
875 "\nno-copy assignments: " << assignFast
<<
876 "\nclearing operations: " << clear
<<
877 "\nappend operations: " << append
<<
878 "\nmove operations: " << moves
<<
879 "\ndump-to-ostream: " << toStream
<<
880 "\nset-char: " << setChar
<<
881 "\nget-char: " << getChar
<<
882 "\ncomparisons with data-scan: " << compareSlow
<<
883 "\ncomparisons not requiring data-scan: " << compareFast
<<
884 "\ncopy-out ops: " << copyOut
<<
885 "\nraw access to memory: " << rawAccess
<<
886 "\nNULL terminate C string: " << nulTerminate
<<
887 "\nchop operations: " << chop
<<
888 "\ntrim operations: " << trim
<<
889 "\nfind: " << find
<<
890 "\nscanf: " << scanf
<<
891 "\ncase-change ops: " << caseChange
<<
892 "\nCOW not actually requiring a copy: " << cowFast
<<
893 "\nCOW: " << cowSlow
<<
894 "\naverage store share factor: " <<
895 (ststats
.live
!= 0 ? static_cast<float>(live
)/ststats
.live
: 0) <<
903 debugs(24, 8, "\"" << *this << "\"");
904 for (size_type j
= 0; j
< length(); ++j
) {
905 const int c
= (*this)[j
];
907 setAt(j
, tolower(c
));
909 debugs(24, 8, "result: \"" << *this << "\"");
916 debugs(24, 8, "\"" << *this << "\"");
917 for (size_type j
= 0; j
< length(); ++j
) {
918 const int c
= (*this)[j
];
920 setAt(j
, toupper(c
));
922 debugs(24, 8, "result: \"" << *this << "\"");
927 * checks whether the requested 'pos' is within the bounds of the SBuf
928 * \throw OutOfBoundsException if access is out of bounds
931 SBuf::checkAccessBounds(size_type pos
) const
934 throw OutOfBoundsException(*this, pos
, __FILE__
, __LINE__
);
937 /** re-allocate the backing store of the SBuf.
939 * If there are contents in the SBuf, they will be copied over.
940 * NO verifications are made on the size parameters, it's up to the caller to
941 * make sure that the new size is big enough to hold the copied contents.
942 * The re-allocated storage MAY be bigger than the requested size due to size-chunking
943 * algorithms in MemBlock, it is guarranteed NOT to be smaller.
946 SBuf::reAlloc(size_type newsize
)
948 debugs(24, 8, id
<< " new size: " << newsize
);
949 if (newsize
> maxSize
)
950 throw SBufTooBigException(__FILE__
, __LINE__
);
951 MemBlob::Pointer newbuf
= new MemBlob(newsize
);
953 newbuf
->append(buf(), length());
957 debugs(24, 7, id
<< " new store capacity: " << store_
->capacity
);
961 SBuf::lowAppend(const char * memArea
, size_type areaSize
)
963 rawSpace(areaSize
); //called method also checks n <= maxSize()
964 store_
->append(memArea
, areaSize
);
971 * copy-on-write: make sure that we are the only holder of the backing store.
972 * If not, reallocate. If a new size is specified, and it is greater than the
973 * current length, the backing store will be extended as needed
976 SBuf::cow(SBuf::size_type newsize
)
978 debugs(24, 8, id
<< " new size:" << newsize
);
979 if (newsize
== npos
|| newsize
< length())
982 if (store_
->LockCount() == 1 && newsize
== length()) {
983 debugs(24, 8, id
<< " no cow needed");