diff options
author | Tor Brede Vekterli <vekterli@oath.com> | 2018-07-25 14:24:21 +0000 |
---|---|---|
committer | Tor Brede Vekterli <vekterli@oath.com> | 2018-07-25 14:24:21 +0000 |
commit | 12c8f3005e202b31a8e0ff3816ce9d714a269046 (patch) | |
tree | a5d9ba0eedc49df2cea2dbdfea677c4c37ed3775 | |
parent | e3af3d215feb1e416b27b92bbf421dde281f3a09 (diff) |
Remove stringref::c_str()
The expected semantics of c_str() (a null-terminated string) cannot
be satisfied with a string reference, so remove the function entirely
to prevent people from using it in buggy ways.
Replaces c_str() with data() in places where it is presumed safe,
otherwise constructs temporary string instances. Certain callsites
have been de-stringref'd in favor of regular strings, in particular
where C APIs have been transitively called. The vast majority of
these were called with string parameters anyway, so should not
cause much extra allocation.
128 files changed, 385 insertions, 365 deletions
diff --git a/config/src/vespa/config/common/configparser.cpp b/config/src/vespa/config/common/configparser.cpp index 6784f0793e9..4d9eac41af6 100644 --- a/config/src/vespa/config/common/configparser.cpp +++ b/config/src/vespa/config/common/configparser.cpp @@ -14,7 +14,7 @@ void ConfigParser::throwNoDefaultValue(const vespalib::stringref & key) { } vespalib::string -ConfigParser::deQuote(const vespalib::stringref & source) +ConfigParser::deQuote(const vespalib::string & source) { const char *src = source.c_str(); const char *s = src; diff --git a/config/src/vespa/config/common/configparser.h b/config/src/vespa/config/common/configparser.h index 2f6cdd9cf39..77b5bf7ddaa 100644 --- a/config/src/vespa/config/common/configparser.h +++ b/config/src/vespa/config/common/configparser.h @@ -23,7 +23,7 @@ private: static std::vector<vsvector> splitArray( const vsvector & config); static std::map<vespalib::string, vsvector> splitMap( const vsvector & config); - static vespalib::string deQuote(const vespalib::stringref & source); + static vespalib::string deQuote(const vespalib::string & source); static void throwNoDefaultValue(const vespalib::stringref & key); template<typename T> diff --git a/document/src/tests/primitivefieldvaluetest.cpp b/document/src/tests/primitivefieldvaluetest.cpp index c4cdc16c3ba..3ccb5aa714b 100644 --- a/document/src/tests/primitivefieldvaluetest.cpp +++ b/document/src/tests/primitivefieldvaluetest.cpp @@ -195,7 +195,7 @@ void deserialize(const ByteBuffer &buffer, T &value) { CPPUNIT_ASSERT_EQUAL(size_t(3), value2.getValueRef().size()); // Zero termination - CPPUNIT_ASSERT(*(value2.getValueRef().c_str() + value2.getValueRef().size()) == '\0'); + CPPUNIT_ASSERT(*(value2.getValueRef().data() + value2.getValueRef().size()) == '\0'); } } @@ -226,7 +226,7 @@ PrimitiveFieldValueTest::testRaw() value.toXml(" ")); value.setValue("grmpf", 4); - CPPUNIT_ASSERT(strncmp("grmpf", value.getValueRef().c_str(), + CPPUNIT_ASSERT(strncmp("grmpf", value.getValueRef().data(), value.getValueRef().size()) == 0); } diff --git a/document/src/vespa/document/base/documentid.cpp b/document/src/vespa/document/base/documentid.cpp index d2eae01922d..c3ba8fea29d 100644 --- a/document/src/vespa/document/base/documentid.cpp +++ b/document/src/vespa/document/base/documentid.cpp @@ -18,7 +18,7 @@ DocumentId::DocumentId() DocumentId::DocumentId(vespalib::stringref id) : Printable(), _globalId(), - _id(IdString::createIdString(id.c_str(), id.size()).release()) + _id(IdString::createIdString(id.data(), id.size()).release()) { } diff --git a/document/src/vespa/document/base/documentid.h b/document/src/vespa/document/base/documentid.h index 4611de73741..a4b01cdad82 100644 --- a/document/src/vespa/document/base/documentid.h +++ b/document/src/vespa/document/base/documentid.h @@ -41,10 +41,15 @@ public: * Parse the given document identifier given as string, and create an * identifier object from it. * + * Precondition: `id` MUST be null-terminated. + * * @throws IdParseException If the identifier given is invalid. */ explicit DocumentId(vespalib::stringref id); + /** + * Precondition: `id` MUST be null-terminated. + */ void set(vespalib::stringref id); /** diff --git a/document/src/vespa/document/base/field.cpp b/document/src/vespa/document/base/field.cpp index 5a3fe6c1935..7ce766c47c6 100644 --- a/document/src/vespa/document/base/field.cpp +++ b/document/src/vespa/document/base/field.cpp @@ -78,7 +78,7 @@ Field::calculateIdV7() ost << getName(); ost << _dataType->getId(); - int newId = vespalib::BobHash::hash(ost.str().c_str(), ost.str().length(), 0); + int newId = vespalib::BobHash::hash(ost.str().data(), ost.str().length(), 0); // Highest bit is reserved to tell 7-bit id's from 31-bit ones if (newId < 0) newId = -newId; validateId(newId); @@ -91,7 +91,7 @@ Field::validateId(int newId) { throw vespalib::IllegalArgumentException(vespalib::make_string( "Attempt to set the id of %s to %d failed, values from " "100 to 127 are reserved for internal use", - getName().c_str(), newId)); + vespalib::string(getName()).c_str(), newId)); } if ((newId & 0x80000000) != 0) // Highest bit must not be set @@ -99,7 +99,7 @@ Field::validateId(int newId) { throw vespalib::IllegalArgumentException(vespalib::make_string( "Attempt to set the id of %s to %d" " failed, negative id values are illegal", - getName().c_str(), newId)); + vespalib::string(getName()).c_str(), newId)); } } diff --git a/document/src/vespa/document/base/fieldpath.cpp b/document/src/vespa/document/base/fieldpath.cpp index 6625f9ae2a5..d1603ca5c09 100644 --- a/document/src/vespa/document/base/fieldpath.cpp +++ b/document/src/vespa/document/base/fieldpath.cpp @@ -139,7 +139,7 @@ FieldPathEntry::visitMembers(vespalib::ObjectVisitor &visitor) const vespalib::string FieldPathEntry::parseKey(vespalib::stringref & key) { vespalib::string v; - const char *c = key.c_str(); + const char *c = key.data(); const char *e = c + key.size(); for(;(c < e) && isspace(c[0]); c++); if ((c < e) && (c[0] == '{')) { @@ -156,7 +156,8 @@ vespalib::string FieldPathEntry::parseKey(vespalib::stringref & key) if ((c < e) && (c[0] == '"')) { c++; } else { - throw IllegalArgumentException(make_string("Escaped key '%s' is incomplete. No matching '\"'", key.c_str()), VESPA_STRLOC); + throw IllegalArgumentException(make_string("Escaped key '%s' is incomplete. No matching '\"'", + vespalib::string(key).c_str()), VESPA_STRLOC); } } else { const char * start = c; @@ -169,10 +170,12 @@ vespalib::string FieldPathEntry::parseKey(vespalib::stringref & key) if ((c < e) && (c[0] == '}')) { key = c+1; } else { - throw IllegalArgumentException(make_string("Key '%s' is incomplete. No matching '}'", key.c_str()), VESPA_STRLOC); + throw IllegalArgumentException(make_string("Key '%s' is incomplete. No matching '}'", + vespalib::string(key).c_str()), VESPA_STRLOC); } } else { - throw IllegalArgumentException(make_string("key '%s' does not start with '{'", key.c_str()), VESPA_STRLOC); + throw IllegalArgumentException(make_string("key '%s' does not start with '{'", + vespalib::string(key).c_str()), VESPA_STRLOC); } return v; } diff --git a/document/src/vespa/document/base/idstring.cpp b/document/src/vespa/document/base/idstring.cpp index 9c64ac6a648..175fb653542 100644 --- a/document/src/vespa/document/base/idstring.cpp +++ b/document/src/vespa/document/base/idstring.cpp @@ -84,9 +84,9 @@ void reportTooShortDocId(const char * id, size_t sz) uint64_t getAsNumber(const stringref & s, const char* part) { char* errPos = NULL; - uint64_t value = strtoull(s.c_str(), &errPos, 10); + uint64_t value = strtoull(s.data(), &errPos, 10); - if (s.c_str() + s.size() != errPos) { + if (s.data() + s.size() != errPos) { reportError(s, part); } return value; @@ -96,9 +96,9 @@ void getOrderDocBits(const stringref& scheme, uint16_t & widthBits, uint16_t & divisionBits) { const char* parenPos = reinterpret_cast<const char*>( - memchr(scheme.c_str(), '(', scheme.size())); + memchr(scheme.data(), '(', scheme.size())); const char* endParenPos = reinterpret_cast<const char*>( - memchr(scheme.c_str(), ')', scheme.size())); + memchr(scheme.data(), ')', scheme.size())); if (parenPos == NULL || endParenPos == NULL || endParenPos < parenPos) { reportError(scheme); @@ -198,13 +198,13 @@ IdString::Offsets::Offsets(uint32_t maxComponents, uint32_t namespaceOffset, con { _offsets[0] = namespaceOffset; size_t index(1); - const char * s(id.c_str() + namespaceOffset); - const char * e(id.c_str() + id.size()); + const char * s(id.data() + namespaceOffset); + const char * e(id.data() + id.size()); for(s=fmemchr(s, e); (s != NULL) && (index < maxComponents); s = fmemchr(s+1, e)) { - _offsets[index++] = s - id.c_str() + 1; + _offsets[index++] = s - id.data() + 1; } _numComponents = index; for (;index < VESPA_NELEMS(_offsets); index++) { @@ -276,14 +276,14 @@ union LocationUnion { IdString::LocationType makeLocation(const stringref &s) { LocationUnion location; - fastc_md5sum(reinterpret_cast<const unsigned char*>(s.c_str()), s.size(), location._key); + fastc_md5sum(reinterpret_cast<const unsigned char*>(s.data()), s.size(), location._key); return location._location[0]; } uint64_t parseNumber(const stringref &number) { char* errPos = NULL; errno = 0; - uint64_t n = strtoul(number.c_str(), &errPos, 10); + uint64_t n = strtoul(number.data(), &errPos, 10); if (*errPos) { throw IdParseException( "'n'-value must be a 64-bit number. It was " + @@ -396,7 +396,7 @@ GroupDocIdString::locationFromGroupName(vespalib::stringref name) } OrderDocIdString::OrderDocIdString(const stringref & rawId) : - IdString(4, static_cast<const char *>(memchr(rawId.c_str(), ':', rawId.size())) - rawId.c_str() + 1, rawId), + IdString(4, static_cast<const char *>(memchr(rawId.data(), ':', rawId.size())) - rawId.data() + 1, rawId), _widthBits(0), _divisionBits(0), _ordering(getAsNumber(rawId.substr(offset(2), offset(3) - offset(2) - 1), "ordering")) diff --git a/document/src/vespa/document/base/idstring.h b/document/src/vespa/document/base/idstring.h index 05554a68ba3..b1a14cfec94 100644 --- a/document/src/vespa/document/base/idstring.h +++ b/document/src/vespa/document/base/idstring.h @@ -24,7 +24,7 @@ public: static const vespalib::string & getTypeName(Type t); /** @throws document::IdParseException If parsing of id scheme failed. */ - static IdString::UP createIdString(const vespalib::stringref & id) { return createIdString(id.c_str(), id.size()); } + static IdString::UP createIdString(const vespalib::stringref & id) { return createIdString(id.data(), id.size()); } static IdString::UP createIdString(const char *id, size_t sz); ~IdString() {} diff --git a/document/src/vespa/document/datatype/arraydatatype.cpp b/document/src/vespa/document/datatype/arraydatatype.cpp index 5ced6053b05..b49599ac620 100644 --- a/document/src/vespa/document/datatype/arraydatatype.cpp +++ b/document/src/vespa/document/datatype/arraydatatype.cpp @@ -60,7 +60,8 @@ ArrayDataType::onBuildFieldPath(FieldPath & path, const vespalib::stringref & re if (remainFieldName[1] == '$') { path.insert(path.begin(), std::make_unique<FieldPathEntry>(getNestedType(), remainFieldName.substr(2, endPos - 2))); } else { - path.insert(path.begin(), std::make_unique<FieldPathEntry>(getNestedType(), atoi(remainFieldName.substr(1, endPos - 1).c_str()))); + // FIXME C++17 range-safe from_chars() instead of atoi() + path.insert(path.begin(), std::make_unique<FieldPathEntry>(getNestedType(), atoi(remainFieldName.substr(1, endPos - 1).data()))); } } } else { diff --git a/document/src/vespa/document/datatype/datatype.h b/document/src/vespa/document/datatype/datatype.h index 247d72db665..5857157c218 100644 --- a/document/src/vespa/document/datatype/datatype.h +++ b/document/src/vespa/document/datatype/datatype.h @@ -125,6 +125,7 @@ public: * This takes a . separated fieldname and gives you back the path of * fields you have to apply to get to your leaf. * @param remainFieldName. The remaining part of the fieldname that you want the path of. + * MUST be null-terminated. * @return pointer to field path or null if an error occured */ void buildFieldPath(FieldPath & fieldPath, const vespalib::stringref & remainFieldName) const; diff --git a/document/src/vespa/document/datatype/documenttype.cpp b/document/src/vespa/document/datatype/documenttype.cpp index c7eaf42b50b..31485aa42b6 100644 --- a/document/src/vespa/document/datatype/documenttype.cpp +++ b/document/src/vespa/document/datatype/documenttype.cpp @@ -96,7 +96,7 @@ DocumentType::addField(const Field& field) } else if (!_ownedFields.get()) { throw vespalib::IllegalStateException(make_string( "Cannot add field %s to a DocumentType that does not " - "own its fields.", field.getName().c_str()), VESPA_STRLOC); + "own its fields.", vespalib::string(field.getName()).c_str()), VESPA_STRLOC); } _ownedFields->addField(field); } diff --git a/document/src/vespa/document/datatype/mapdatatype.cpp b/document/src/vespa/document/datatype/mapdatatype.cpp index 5c940b1af6e..4598b96d970 100644 --- a/document/src/vespa/document/datatype/mapdatatype.cpp +++ b/document/src/vespa/document/datatype/mapdatatype.cpp @@ -73,7 +73,7 @@ MapDataType::buildFieldPathImpl(FieldPath & path, const DataType &dataType, *fv = keyValue; path.insert(path.begin(), std::make_unique<FieldPathEntry>(valueType, dataType, std::move(fv))); } - } else if (memcmp(remainFieldName.c_str(), "key", 3) == 0) { + } else if (memcmp(remainFieldName.data(), "key", 3) == 0) { size_t endPos = 3; if (remainFieldName[endPos] == '.') { endPos++; @@ -82,7 +82,7 @@ MapDataType::buildFieldPathImpl(FieldPath & path, const DataType &dataType, keyType.buildFieldPath(path, remainFieldName.substr(endPos)); path.insert(path.begin(), std::make_unique<FieldPathEntry>(dataType, keyType, valueType, true, false)); - } else if (memcmp(remainFieldName.c_str(), "value", 5) == 0) { + } else if (memcmp(remainFieldName.data(), "value", 5) == 0) { size_t endPos = 5; if (remainFieldName[endPos] == '.') { endPos++; diff --git a/document/src/vespa/document/datatype/referencedatatype.cpp b/document/src/vespa/document/datatype/referencedatatype.cpp index d02793edd3a..8f0c6a0a4c3 100644 --- a/document/src/vespa/document/datatype/referencedatatype.cpp +++ b/document/src/vespa/document/datatype/referencedatatype.cpp @@ -36,7 +36,7 @@ ReferenceDataType* ReferenceDataType::clone() const { void ReferenceDataType::onBuildFieldPath(FieldPath &, const vespalib::stringref& remainingFieldName) const { if ( ! remainingFieldName.empty() ) { throw IllegalArgumentException(make_string("Reference data type does not support further field recursion: '%s'", - remainingFieldName.c_str()), VESPA_STRLOC); + vespalib::string(remainingFieldName).c_str()), VESPA_STRLOC); } } diff --git a/document/src/vespa/document/datatype/structdatatype.cpp b/document/src/vespa/document/datatype/structdatatype.cpp index 0abde69c2a1..1303f16c43b 100644 --- a/document/src/vespa/document/datatype/structdatatype.cpp +++ b/document/src/vespa/document/datatype/structdatatype.cpp @@ -83,7 +83,7 @@ StructDataType::addField(const Field& field) vespalib::string error = containsConflictingField(field); if (error != "") { throw IllegalArgumentException(make_string("Failed to add field '%s' to struct '%s': %s", - field.getName().c_str(), getName().c_str(), + vespalib::string(field.getName()).c_str(), getName().c_str(), error.c_str()), VESPA_STRLOC); } if (hasField(field.getName())) { diff --git a/document/src/vespa/document/datatype/structureddatatype.cpp b/document/src/vespa/document/datatype/structureddatatype.cpp index 41c0cd6f4e7..604b4cad045 100644 --- a/document/src/vespa/document/datatype/structureddatatype.cpp +++ b/document/src/vespa/document/datatype/structureddatatype.cpp @@ -80,7 +80,8 @@ StructuredDataType::onBuildFieldPath(FieldPath & path, const vespalib::stringref path.insert(path.begin(), std::make_unique<FieldPathEntry>(fp)); } else { throw FieldNotFoundException(currFieldName, make_string("Invalid field path '%s', no field named '%s'", - remainFieldName.c_str(), currFieldName.c_str())); + vespalib::string(remainFieldName).c_str(), + vespalib::string(currFieldName).c_str())); } } diff --git a/document/src/vespa/document/fieldvalue/arrayfieldvalue.cpp b/document/src/vespa/document/fieldvalue/arrayfieldvalue.cpp index f3239553fa9..a09d5a25dd2 100644 --- a/document/src/vespa/document/fieldvalue/arrayfieldvalue.cpp +++ b/document/src/vespa/document/fieldvalue/arrayfieldvalue.cpp @@ -186,9 +186,6 @@ ArrayFieldValue::iterateSubset(int startPos, int endPos, { fieldvalue::ModificationStatus retVal = ModificationStatus::NOT_MODIFIED; - LOG(spam, "iterateSubset(start=%d, end=%d, variable='%s')", - startPos, endPos, variable.c_str()); - std::vector<int> indicesToRemove; for (int i = startPos; i <= endPos && i < static_cast<int>(_array->size()); ++i) { diff --git a/document/src/vespa/document/fieldvalue/document.cpp b/document/src/vespa/document/fieldvalue/document.cpp index 47366b388a9..51ba135b826 100644 --- a/document/src/vespa/document/fieldvalue/document.cpp +++ b/document/src/vespa/document/fieldvalue/document.cpp @@ -32,12 +32,13 @@ void documentTypeError(const vespalib::stringref & name) __attribute__((noinline void throwTypeMismatch(vespalib::stringref type, vespalib::stringref docidType) __attribute__((noinline)); void documentTypeError(const vespalib::stringref & name) { - throw IllegalArgumentException(make_string("Cannot generate a document with non-document type %s.", name.c_str()), VESPA_STRLOC); + throw IllegalArgumentException(make_string("Cannot generate a document with non-document type %s.", + vespalib::string(name).c_str()), VESPA_STRLOC); } void throwTypeMismatch(vespalib::stringref type, vespalib::stringref docidType) { throw IllegalArgumentException(make_string("Trying to create a document with type %s that don't match the id (type %s).", - type.c_str(), docidType.c_str()), + vespalib::string(type).c_str(), vespalib::string(docidType).c_str()), VESPA_STRLOC); } diff --git a/document/src/vespa/document/fieldvalue/literalfieldvalue.cpp b/document/src/vespa/document/fieldvalue/literalfieldvalue.cpp index 747c789c6cd..5614330a495 100644 --- a/document/src/vespa/document/fieldvalue/literalfieldvalue.cpp +++ b/document/src/vespa/document/fieldvalue/literalfieldvalue.cpp @@ -79,7 +79,7 @@ LiteralFieldValueB::fastCompare(const FieldValue& other) const void LiteralFieldValueB::printXml(XmlOutputStream& out) const { - out << XmlContentWrapper(_value.c_str(), _value.size()); + out << XmlContentWrapper(_value.data(), _value.size()); } void @@ -106,7 +106,7 @@ LiteralFieldValueB::getAsString() const std::pair<const char*, size_t> LiteralFieldValueB::getAsRaw() const { - return std::make_pair(_value.c_str(), _value.size()); + return std::make_pair(_value.data(), _value.size()); } void diff --git a/document/src/vespa/document/fieldvalue/literalfieldvalue.h b/document/src/vespa/document/fieldvalue/literalfieldvalue.h index d72e734b6a6..2f9050eb13c 100644 --- a/document/src/vespa/document/fieldvalue/literalfieldvalue.h +++ b/document/src/vespa/document/fieldvalue/literalfieldvalue.h @@ -54,7 +54,7 @@ public: _value = _backing; _altered = true; } - size_t hash() const override final { return vespalib::hashValue(_value.c_str()); } + size_t hash() const override final { return vespalib::hashValue(_value.data(), _value.size()); } void setValue(const char* val, size_t size) { setValue(stringref(val, size)); } int compare(const FieldValue& other) const override; @@ -76,7 +76,7 @@ public: protected: void syncBacking() const __attribute__((noinline)); void sync() const { - if (__builtin_expect(_backing.c_str() != _value.c_str(), false)) { + if (__builtin_expect(_backing.data() != _value.data(), false)) { syncBacking(); } } diff --git a/document/src/vespa/document/fieldvalue/numericfieldvalue.hpp b/document/src/vespa/document/fieldvalue/numericfieldvalue.hpp index 881cdb4a7e3..c3ef6781706 100644 --- a/document/src/vespa/document/fieldvalue/numericfieldvalue.hpp +++ b/document/src/vespa/document/fieldvalue/numericfieldvalue.hpp @@ -84,9 +84,10 @@ NumericFieldValue<Number>::operator=(const vespalib::stringref & value) // so detect these in front. if ((value.size() > 2) && (value[0] == '0') && ((value[1] | 0x20) == 'x')) { char* endp; - // It is safe to assume that all hex numbers can be contained within - // 64 bit unsigned value. - unsigned long long val = strtoull(value.c_str(), &endp, 16); + // It is safe to assume that all hex numbers can be contained within + // 64 bit unsigned value. + // FIXME C++17 range-safe from_chars() instead of strtoull() + unsigned long long val = strtoull(value.data(), &endp, 16); if (*endp == '\0') { // Allow numbers to be specified in range max signed to max // unsigned. These become negative numbers. diff --git a/document/src/vespa/document/fieldvalue/rawfieldvalue.cpp b/document/src/vespa/document/fieldvalue/rawfieldvalue.cpp index 6e415471cd0..5d4abe658c1 100644 --- a/document/src/vespa/document/fieldvalue/rawfieldvalue.cpp +++ b/document/src/vespa/document/fieldvalue/rawfieldvalue.cpp @@ -15,13 +15,13 @@ void RawFieldValue::printXml(XmlOutputStream& out) const { out << XmlBase64Content() - << XmlContentWrapper(_value.c_str(), _value.size()); + << XmlContentWrapper(_value.data(), _value.size()); } void RawFieldValue::print(std::ostream& out, bool, const std::string&) const { - StringUtil::printAsHex(out, _value.c_str(), _value.size()); + StringUtil::printAsHex(out, _value.data(), _value.size()); } } // document diff --git a/document/src/vespa/document/fieldvalue/structuredfieldvalue.cpp b/document/src/vespa/document/fieldvalue/structuredfieldvalue.cpp index 92d4e4788fb..c193b0919ea 100644 --- a/document/src/vespa/document/fieldvalue/structuredfieldvalue.cpp +++ b/document/src/vespa/document/fieldvalue/structuredfieldvalue.cpp @@ -71,7 +71,7 @@ void StructuredFieldValue::setFieldValue(const Field & field, const FieldValue & throw IllegalArgumentException( "Cannot assign value of type " + value.getDataType()->toString() + "with value : '" + value.toString() - + "' to field " + field.getName().c_str() + " of type " + + "' to field " + field.getName() + " of type " + field.getDataType().toString() + ".", VESPA_STRLOC); } setFieldValue(field, FieldValue::UP(value.clone())); diff --git a/document/src/vespa/document/select/simpleparser.cpp b/document/src/vespa/document/select/simpleparser.cpp index 462243f342c..349c1c17362 100644 --- a/document/src/vespa/document/select/simpleparser.cpp +++ b/document/src/vespa/document/select/simpleparser.cpp @@ -24,7 +24,7 @@ bool icmp(char c, char l) bool IdSpecParser::parse(const vespalib::stringref & s) { bool retval(false); - size_t pos(eatWhite(s.c_str(), s.size())); + size_t pos(eatWhite(s.data(), s.size())); if (pos+1 < s.size()) { if (icmp(s[pos], 'i') && icmp(s[pos+1],'d')) { pos += 2; @@ -77,7 +77,7 @@ bool IdSpecParser::parse(const vespalib::stringref & s) bool OperatorParser::parse(const vespalib::stringref & s) { bool retval(false); - size_t pos(eatWhite(s.c_str(), s.size())); + size_t pos(eatWhite(s.data(), s.size())); if (pos+1 < s.size()) { retval = true; if (s[pos] == '=') { @@ -122,7 +122,7 @@ bool StringParser::parse(const vespalib::stringref & s) { bool retval(false); setRemaining(s); - size_t pos(eatWhite(s.c_str(), s.size())); + size_t pos(eatWhite(s.data(), s.size())); if (pos + 1 < s.size()) { if (s[pos++] == '"') { vespalib::string str; @@ -146,7 +146,7 @@ bool StringParser::parse(const vespalib::stringref & s) bool IntegerParser::parse(const vespalib::stringref & s) { bool retval(false); - size_t pos(eatWhite(s.c_str(), s.size())); + size_t pos(eatWhite(s.data(), s.size())); if (pos < s.size()) { char * err(NULL); errno = 0; diff --git a/document/src/vespa/document/serialization/vespadocumentserializer.cpp b/document/src/vespa/document/serialization/vespadocumentserializer.cpp index 08fddbaad41..a309fdd3500 100644 --- a/document/src/vespa/document/serialization/vespadocumentserializer.cpp +++ b/document/src/vespa/document/serialization/vespadocumentserializer.cpp @@ -513,7 +513,10 @@ void VespaDocumentSerializer::write(const MapValueUpdate &value) namespace { -void writeStringWithZeroTermination(nbostream & os, stringref s) +// We must ensure that string passed is always zero-terminated, so take in +// string instead of stringref. No extra allocs; function only ever called with +// string arguments. +void writeStringWithZeroTermination(nbostream & os, const vespalib::string& s) { uint32_t sz(s.size() + 1); os << sz; diff --git a/document/src/vespa/document/update/addvalueupdate.cpp b/document/src/vespa/document/update/addvalueupdate.cpp index 051ffcf8b2a..e5a99b49a9e 100644 --- a/document/src/vespa/document/update/addvalueupdate.cpp +++ b/document/src/vespa/document/update/addvalueupdate.cpp @@ -43,7 +43,7 @@ AddValueUpdate::checkCompatibility(const Field& field) const const CollectionDataType& type(static_cast<const CollectionDataType&>(field.getDataType())); if (!type.getNestedType().isValueType(*_value)) { throw IllegalArgumentException("Cannot add value of type " + _value->getDataType()->toString() + - " to field " + field.getName().c_str() + " of container type " + + " to field " + field.getName() + " of container type " + field.getDataType().toString(), VESPA_STRLOC); } } else { diff --git a/document/src/vespa/document/update/arithmeticvalueupdate.cpp b/document/src/vespa/document/update/arithmeticvalueupdate.cpp index 9ae7dd17a52..7363899d5cf 100644 --- a/document/src/vespa/document/update/arithmeticvalueupdate.cpp +++ b/document/src/vespa/document/update/arithmeticvalueupdate.cpp @@ -35,7 +35,7 @@ ArithmeticValueUpdate::checkCompatibility(const Field& field) const if ( ! field.getDataType().inherits(NumericDataType::classId)) { throw IllegalArgumentException(vespalib::make_string( "Can not perform arithmetic update on non-numeric field '%s'.", - field.getName().c_str()), VESPA_STRLOC); + vespalib::string(field.getName()).c_str()), VESPA_STRLOC); } } diff --git a/document/src/vespa/document/update/mapvalueupdate.cpp b/document/src/vespa/document/update/mapvalueupdate.cpp index 3fc9c8cbea5..cc0aec3618a 100644 --- a/document/src/vespa/document/update/mapvalueupdate.cpp +++ b/document/src/vespa/document/update/mapvalueupdate.cpp @@ -46,7 +46,7 @@ MapValueUpdate::checkCompatibility(const Field& field) const if (_key->getClass().id() != IntFieldValue::classId) { throw IllegalArgumentException(vespalib::make_string( "Key for field '%s' is of wrong type (expected '%s', was '%s').", - field.getName().c_str(), DataType::INT->toString().c_str(), + vespalib::string(field.getName()).c_str(), DataType::INT->toString().c_str(), _key->getDataType()->toString().c_str()), VESPA_STRLOC); } } else if (field.getDataType().getClass().id() == WeightedSetDataType::classId) { @@ -54,7 +54,7 @@ MapValueUpdate::checkCompatibility(const Field& field) const if (!type.getNestedType().isValueType(*_key)) { throw IllegalArgumentException(vespalib::make_string( "Key for field '%s' is of wrong type (expected '%s', was '%s').", - field.getName().c_str(), DataType::INT->toString().c_str(), + vespalib::string(field.getName()).c_str(), DataType::INT->toString().c_str(), _key->getDataType()->toString().c_str()), VESPA_STRLOC); } } else { diff --git a/document/src/vespa/document/update/removevalueupdate.cpp b/document/src/vespa/document/update/removevalueupdate.cpp index 28c69652a0e..fdbee3cb394 100644 --- a/document/src/vespa/document/update/removevalueupdate.cpp +++ b/document/src/vespa/document/update/removevalueupdate.cpp @@ -44,7 +44,7 @@ RemoveValueUpdate::checkCompatibility(const Field& field) const throw IllegalArgumentException( "Cannot remove value of type " + _key->getDataType()->toString() + " from field " - + field.getName().c_str() + " of container type " + + field.getName() + " of container type " + field.getDataType().toString(), VESPA_STRLOC); } } else { diff --git a/eval/src/vespa/eval/tensor/dense/dense_tensor_view.cpp b/eval/src/vespa/eval/tensor/dense/dense_tensor_view.cpp index 80548d33e72..f2ddcb38698 100644 --- a/eval/src/vespa/eval/tensor/dense/dense_tensor_view.cpp +++ b/eval/src/vespa/eval/tensor/dense/dense_tensor_view.cpp @@ -67,7 +67,7 @@ checkDimensions(const DenseTensorView &lhs, const DenseTensorView &rhs, "dense tensor %s, " "lhs dimensions = '%s', " "rhs dimensions = '%s'", - operation.c_str(), + operation.data(), dimensionsAsString(lhs.fast_type()).c_str(), dimensionsAsString(rhs.fast_type()).c_str())); } diff --git a/eval/src/vespa/eval/tensor/sparse/sparse_tensor_unsorted_address_builder.h b/eval/src/vespa/eval/tensor/sparse/sparse_tensor_unsorted_address_builder.h index 681bdabc5eb..7e69adb5804 100644 --- a/eval/src/vespa/eval/tensor/sparse/sparse_tensor_unsorted_address_builder.h +++ b/eval/src/vespa/eval/tensor/sparse/sparse_tensor_unsorted_address_builder.h @@ -53,7 +53,7 @@ class SparseTensorUnsortedAddressBuilder ElementStringRef append(vespalib::stringref str) { - const char *cstr = str.c_str(); + const char *cstr = str.data(); uint32_t start = _elementStrings.size(); _elementStrings.insert(_elementStrings.end(), cstr, cstr + str.size() + 1); diff --git a/messagebus/src/vespa/messagebus/network/rpcsend.cpp b/messagebus/src/vespa/messagebus/network/rpcsend.cpp index 04cccd59903..87c87173ec7 100644 --- a/messagebus/src/vespa/messagebus/network/rpcsend.cpp +++ b/messagebus/src/vespa/messagebus/network/rpcsend.cpp @@ -207,12 +207,12 @@ RPCSend::decode(vespalib::stringref protocolName, const vespalib::Version & vers } } else { error = Error(ErrorCode::DECODE_ERROR, - make_string("Protocol '%s' failed to decode routable.", protocolName.c_str())); + make_string("Protocol '%s' failed to decode routable.", vespalib::string(protocolName).c_str())); } } else { error = Error(ErrorCode::UNKNOWN_PROTOCOL, - make_string("Protocol '%s' is not known by %s.", protocolName.c_str(), _serverIdent.c_str())); + make_string("Protocol '%s' is not known by %s.", vespalib::string(protocolName).c_str(), _serverIdent.c_str())); } return reply; } @@ -263,7 +263,7 @@ RPCSend::invoke(FRT_RPCRequest *req) if (protocol == nullptr) { replyError(req, params->getVersion(), params->getTraceLevel(), Error(ErrorCode::UNKNOWN_PROTOCOL, make_string("Protocol '%s' is not known by %s.", - params->getProtocol().c_str(), _serverIdent.c_str()))); + vespalib::string(params->getProtocol()).c_str(), _serverIdent.c_str()))); return; } if (protocol->requireSequencing() || !_net->allowDispatchForDecode()) { @@ -284,7 +284,7 @@ RPCSend::doRequest(FRT_RPCRequest *req, const IProtocol * protocol, std::unique_ if ( ! routable ) { replyError(req, params->getVersion(), params->getTraceLevel(), Error(ErrorCode::DECODE_ERROR, - make_string("Protocol '%s' failed to decode routable.", params->getProtocol().c_str()))); + make_string("Protocol '%s' failed to decode routable.", vespalib::string(params->getProtocol()).c_str()))); return; } if (routable->isReply()) { diff --git a/messagebus/src/vespa/messagebus/routing/routeparser.cpp b/messagebus/src/vespa/messagebus/routing/routeparser.cpp index 3bc9b57d1e7..0fb90f0d585 100644 --- a/messagebus/src/vespa/messagebus/routing/routeparser.cpp +++ b/messagebus/src/vespa/messagebus/routing/routeparser.cpp @@ -34,8 +34,9 @@ RouteParser::createTcpDirective(const stringref &str) if (posS == string::npos || posS == posP + 1) { return IHopDirective::SP(); // no port } + // FIXME C++17 range-safe from_chars() instead of atoi() return IHopDirective::SP(new TcpDirective(str.substr(0, posP), - atoi(str.substr(posP + 1, posS - 1).c_str()), + atoi(str.substr(posP + 1, posS - 1).data()), str.substr(posS + 1))); } @@ -104,7 +105,7 @@ RouteParser::createHop(stringref str) return Hop().addDirective(createErrorDirective( vespalib::make_string( "Failed to completely parse '%s'.", - str.c_str()))); + vespalib::string(str).c_str()))); } else if (str[at] == '[') { ++depth; } else if (str[at] == ']') { diff --git a/metrics/src/vespa/metrics/countmetric.cpp b/metrics/src/vespa/metrics/countmetric.cpp index a19b14f9545..0c2504b2077 100644 --- a/metrics/src/vespa/metrics/countmetric.cpp +++ b/metrics/src/vespa/metrics/countmetric.cpp @@ -14,7 +14,7 @@ AbstractCountMetric::logWarning(const char* msg, const char * op) const { vespalib::asciistream ost; ost << msg << " in count metric " << getPath() << " op " << op << ". Resetting it."; - LOG(warning, "%s", ost.str().c_str()); + LOG(warning, "%s", ost.str().data()); } void diff --git a/metrics/src/vespa/metrics/valuemetric.cpp b/metrics/src/vespa/metrics/valuemetric.cpp index 04b442829ed..48baa59c7a0 100644 --- a/metrics/src/vespa/metrics/valuemetric.cpp +++ b/metrics/src/vespa/metrics/valuemetric.cpp @@ -19,7 +19,7 @@ AbstractValueMetric::logWarning(const char* msg, const char * op) const { vespalib::asciistream ost; ost << msg << " in value metric " << getPath() << " op " << op << ". Resetting it."; - LOG(warning, "%s", ost.str().c_str()); + LOG(warning, "%s", ost.str().data()); } void diff --git a/searchcommon/src/vespa/searchcommon/common/schema.cpp b/searchcommon/src/vespa/searchcommon/common/schema.cpp index eafe9c28c1b..6cd9d87fa77 100644 --- a/searchcommon/src/vespa/searchcommon/common/schema.cpp +++ b/searchcommon/src/vespa/searchcommon/common/schema.cpp @@ -22,7 +22,7 @@ writeFields(vespalib::asciistream & os, { os << prefix << "[" << fields.size() << "]\n"; for (size_t i = 0; i < fields.size(); ++i) { - fields[i].write(os, vespalib::make_string("%s[%zu].", prefix.c_str(), i)); + fields[i].write(os, vespalib::make_string("%s[%zu].", prefix.data(), i)); } } @@ -245,7 +245,7 @@ Schema & Schema::operator=(Schema && rhs) = default; Schema::~Schema() { } bool -Schema::loadFromFile(const vespalib::stringref & fileName) +Schema::loadFromFile(const vespalib::string & fileName) { std::ifstream file(fileName.c_str()); if (!file) { @@ -284,7 +284,7 @@ Schema::loadFromFile(const vespalib::stringref & fileName) } bool -Schema::saveToFile(const vespalib::stringref & fileName) const +Schema::saveToFile(const vespalib::string & fileName) const { vespalib::asciistream os; writeToStream(os, true); diff --git a/searchcommon/src/vespa/searchcommon/common/schema.h b/searchcommon/src/vespa/searchcommon/common/schema.h index 374ea840f5c..1c3ab3ccd56 100644 --- a/searchcommon/src/vespa/searchcommon/common/schema.h +++ b/searchcommon/src/vespa/searchcommon/common/schema.h @@ -179,7 +179,7 @@ public: * @return true if the schema could be loaded. **/ bool - loadFromFile(const vespalib::stringref & fileName); + loadFromFile(const vespalib::string & fileName); /** * Save this schema to the file with the given name. @@ -188,7 +188,7 @@ public: * @return true if the schema could be saved. **/ bool - saveToFile(const vespalib::stringref & fileName) const; + saveToFile(const vespalib::string & fileName) const; vespalib::string toString() const; diff --git a/searchcore/src/tests/proton/index/indexmanager_test.cpp b/searchcore/src/tests/proton/index/indexmanager_test.cpp index 6a098667be8..d88199e6ae8 100644 --- a/searchcore/src/tests/proton/index/indexmanager_test.cpp +++ b/searchcore/src/tests/proton/index/indexmanager_test.cpp @@ -662,7 +662,7 @@ TEST_F("requireThatSerialNumberIsReadOnLoad", Fixture) { void crippleFusion(uint32_t fusionId) { vespalib::asciistream ost; ost << index_dir << "/index.flush." << fusionId << "/serial.dat"; - FastOS_File(ost.str().c_str()).Delete(); + FastOS_File(ost.str().data()).Delete(); } TEST_F("requireThatFailedFusionIsRetried", Fixture) { diff --git a/searchcore/src/tests/proton/summaryengine/summaryengine.cpp b/searchcore/src/tests/proton/summaryengine/summaryengine.cpp index 8206eba6350..0a520044985 100644 --- a/searchcore/src/tests/proton/summaryengine/summaryengine.cpp +++ b/searchcore/src/tests/proton/summaryengine/summaryengine.cpp @@ -68,7 +68,7 @@ public: DocsumReply::Docsum docsum; docsum.docid = 10 + i; docsum.gid = h.gid; - docsum.setData(_reply.c_str(), _reply.size()); + docsum.setData(_reply.data(), _reply.size()); retval->docsums.push_back(docsum); } return retval; diff --git a/searchcore/src/vespa/searchcore/fdispatch/search/query.h b/searchcore/src/vespa/searchcore/fdispatch/search/query.h index 171a68de9ab..4d336d9843e 100644 --- a/searchcore/src/vespa/searchcore/fdispatch/search/query.h +++ b/searchcore/src/vespa/searchcore/fdispatch/search/query.h @@ -70,6 +70,6 @@ private: const vespalib::stringref &b) { return (a.size() == b.size() && - memcmp(a.c_str(), b.c_str(), a.size()) == 0); + memcmp(a.data(), b.data(), a.size()) == 0); } }; diff --git a/searchcore/src/vespa/searchcore/fdispatch/search/search_path.cpp b/searchcore/src/vespa/searchcore/fdispatch/search/search_path.cpp index d1731b91e6c..90c6fa2155c 100644 --- a/searchcore/src/vespa/searchcore/fdispatch/search/search_path.cpp +++ b/searchcore/src/vespa/searchcore/fdispatch/search/search_path.cpp @@ -46,7 +46,7 @@ SearchPath::parsePartList(const vespalib::stringref &partSpec, size_t numNodes) } } catch (const std::exception & e) { LOG(warning, "Failed parsing part of searchpath='%s' with error '%s'. Result might be mumbo jumbo.", - partSpec.c_str(), e.what()); + vespalib::string(partSpec).c_str(), e.what()); } } @@ -97,7 +97,8 @@ void SearchPath::parseRow(const vespalib::stringref &rowSpec) { if (!rowSpec.empty()) { - _elements.back().setRow(strtoul(rowSpec.c_str(), NULL, 0)); + // FIXME C++17 range-safe from_chars() instead of strtoul() + _elements.back().setRow(strtoul(rowSpec.data(), nullptr, 0)); } } diff --git a/searchcore/src/vespa/searchcore/proton/attribute/attribute_writer.cpp b/searchcore/src/vespa/searchcore/proton/attribute/attribute_writer.cpp index eb6020b8d5f..3fecf661dcd 100644 --- a/searchcore/src/vespa/searchcore/proton/attribute/attribute_writer.cpp +++ b/searchcore/src/vespa/searchcore/proton/attribute/attribute_writer.cpp @@ -555,12 +555,12 @@ AttributeWriter::update(SerialNum serialNum, const DocumentUpdate &upd, Document } for (const auto &fupd : upd.getUpdates()) { - LOG(debug, "Retrieving guard for attribute vector '%s'.", fupd.getField().getName().c_str()); + LOG(debug, "Retrieving guard for attribute vector '%s'.", vespalib::string(fupd.getField().getName()).c_str()); auto found = _attrMap.find(fupd.getField().getName()); AttributeVector * attrp = (found != _attrMap.end()) ? found->second.first : nullptr; onUpdate.onUpdateField(fupd.getField().getName(), attrp); if (attrp == nullptr) { - LOG(spam, "Failed to find attribute vector %s", fupd.getField().getName().c_str()); + LOG(spam, "Failed to find attribute vector %s", vespalib::string(fupd.getField().getName()).c_str()); continue; } // TODO: Check if we must use > due to multiple entries for same diff --git a/searchcore/src/vespa/searchcore/proton/common/eventlogger.cpp b/searchcore/src/vespa/searchcore/proton/common/eventlogger.cpp index f3afab96cf5..78f73742fed 100644 --- a/searchcore/src/vespa/searchcore/proton/common/eventlogger.cpp +++ b/searchcore/src/vespa/searchcore/proton/common/eventlogger.cpp @@ -28,7 +28,7 @@ doTransactionLogReplayStart(const string &domainName, SerialNum first, SerialNum .appendKey("last").appendInt64(last) .endObject(); jstr.endObject(); - EV_STATE(eventName.c_str(), jstr.toString().c_str()); + EV_STATE(eventName.c_str(), jstr.toString().data()); } void @@ -39,7 +39,7 @@ doTransactionLogReplayComplete(const string &domainName, int64_t elapsedTimeMs, jstr.appendKey("domain").appendString(domainName); jstr.appendKey("time.elapsed.ms").appendInt64(elapsedTimeMs); jstr.endObject(); - EV_STATE(eventName.c_str(), jstr.toString().c_str()); + EV_STATE(eventName.c_str(), jstr.toString().data()); } } @@ -67,7 +67,7 @@ EventLogger::transactionLogReplayProgress(const string &domainName, float progre .appendKey("current").appendInt64(current) .endObject(); jstr.endObject(); - EV_STATE("transactionlog.replay.progress", jstr.toString().c_str()); + EV_STATE("transactionlog.replay.progress", jstr.toString().data()); } void @@ -83,7 +83,7 @@ EventLogger::flushInit(const string &name) jstr.beginObject(); jstr.appendKey("name").appendString(name); jstr.endObject(); - EV_STATE("flush.init", jstr.toString().c_str()); + EV_STATE("flush.init", jstr.toString().data()); } void @@ -105,7 +105,7 @@ EventLogger::flushStart(const string &name, int64_t beforeMemory, int64_t afterM .appendKey("current").appendInt64(current) .endObject(); jstr.endObject(); - EV_STATE("flush.start", jstr.toString().c_str()); + EV_STATE("flush.start", jstr.toString().data()); } void @@ -121,7 +121,7 @@ EventLogger::flushComplete(const string &name, int64_t elapsedTimeMs, LogUtil::logDir(jstr, outputPath, outputPathElems); } jstr.endObject(); - EV_STATE("flush.complete", jstr.toString().c_str()); + EV_STATE("flush.complete", jstr.toString().data()); } namespace { @@ -146,7 +146,7 @@ EventLogger::populateAttributeStart(const std::vector<string> &names) jstr.beginObject(); addNames(jstr, names); jstr.endObject(); - EV_STATE("populate.attribute.start", jstr.toString().c_str()); + EV_STATE("populate.attribute.start", jstr.toString().data()); } void @@ -157,7 +157,7 @@ EventLogger::populateAttributeComplete(const std::vector<string> &names, int64_t addNames(jstr, names); jstr.appendKey("documents.populated").appendInt64(documentsPopulated); jstr.endObject(); - EV_STATE("populate.attribute.complete", jstr.toString().c_str()); + EV_STATE("populate.attribute.complete", jstr.toString().data()); } void @@ -167,7 +167,7 @@ EventLogger::populateDocumentFieldStart(const string &fieldName) jstr.beginObject(); jstr.appendKey("name").appendString(fieldName); jstr.endObject(); - EV_STATE("populate.documentfield.start", jstr.toString().c_str()); + EV_STATE("populate.documentfield.start", jstr.toString().data()); } void @@ -178,7 +178,7 @@ EventLogger::populateDocumentFieldComplete(const string &fieldName, int64_t docu jstr.appendKey("name").appendString(fieldName); jstr.appendKey("documents.populated").appendInt64(documentsPopulated); jstr.endObject(); - EV_STATE("populate.documentfield.complete", jstr.toString().c_str()); + EV_STATE("populate.documentfield.complete", jstr.toString().data()); } void @@ -189,7 +189,7 @@ EventLogger::lidSpaceCompactionComplete(const string &subDbName, uint32_t lidLim jstr.appendKey("documentsubdb").appendString(subDbName); jstr.appendKey("lidlimit").appendInt64(lidLimit); jstr.endObject(); - EV_STATE("lidspace.compaction.complete", jstr.toString().c_str()); + EV_STATE("lidspace.compaction.complete", jstr.toString().data()); } @@ -201,7 +201,7 @@ EventLogger::reprocessDocumentsStart(const string &subDb, double visitCost) jstr.appendKey("documentsubdb").appendString(subDb); jstr.appendKey("visitcost").appendDouble(visitCost); jstr.endObject(); - EV_STATE("reprocess.documents.start", jstr.toString().c_str()); + EV_STATE("reprocess.documents.start", jstr.toString().data()); } @@ -214,7 +214,7 @@ EventLogger::reprocessDocumentsProgress(const string &subDb, double progress, do jstr.appendKey("progress").appendDouble(progress); jstr.appendKey("visitcost").appendDouble(visitCost); jstr.endObject(); - EV_STATE("reprocess.documents.progress", jstr.toString().c_str()); + EV_STATE("reprocess.documents.progress", jstr.toString().data()); } @@ -227,7 +227,7 @@ EventLogger::reprocessDocumentsComplete(const string &subDb, double visitCost, i jstr.appendKey("visitcost").appendDouble(visitCost); jstr.appendKey("time.elapsed.ms").appendInt64(elapsedTimeMs); jstr.endObject(); - EV_STATE("reprocess.documents.complete", jstr.toString().c_str()); + EV_STATE("reprocess.documents.complete", jstr.toString().data()); } void @@ -238,7 +238,7 @@ EventLogger::loadAttributeStart(const vespalib::string &subDbName, const vespali jstr.appendKey("documentsubdb").appendString(subDbName); jstr.appendKey("name").appendString(attrName); jstr.endObject(); - EV_STATE("load.attribute.start", jstr.toString().c_str()); + EV_STATE("load.attribute.start", jstr.toString().data()); } void @@ -251,7 +251,7 @@ EventLogger::loadAttributeComplete(const vespalib::string &subDbName, jstr.appendKey("name").appendString(attrName); jstr.appendKey("time.elapsed.ms").appendInt64(elapsedTimeMs); jstr.endObject(); - EV_STATE("load.attribute.complete", jstr.toString().c_str()); + EV_STATE("load.attribute.complete", jstr.toString().data()); } namespace { @@ -263,7 +263,7 @@ loadComponentStart(const vespalib::string &subDbName, const vespalib::string &co jstr.beginObject(); jstr.appendKey("documentsubdb").appendString(subDbName); jstr.endObject(); - EV_STATE(make_string("load.%s.start", componentName.c_str()).c_str(), jstr.toString().c_str()); + EV_STATE(make_string("load.%s.start", componentName.c_str()).c_str(), jstr.toString().data()); } void @@ -274,7 +274,7 @@ loadComponentComplete(const vespalib::string &subDbName, const vespalib::string jstr.appendKey("documentsubdb").appendString(subDbName); jstr.appendKey("time.elapsed.ms").appendInt64(elapsedTimeMs); jstr.endObject(); - EV_STATE(make_string("load.%s.complete", componentName.c_str()).c_str(), jstr.toString().c_str()); + EV_STATE(make_string("load.%s.complete", componentName.c_str()).c_str(), jstr.toString().data()); } } @@ -314,7 +314,7 @@ EventLogger::transactionLogPruneComplete(const string &domainName, SerialNum pru .appendKey("pruned").appendInt64(prunedSerial) .endObject(); jstr.endObject(); - EV_STATE("transactionlog.prune.complete", jstr.toString().c_str()); + EV_STATE("transactionlog.prune.complete", jstr.toString().data()); } } // namespace proton diff --git a/searchcore/src/vespa/searchcore/proton/docsummary/documentstoreadapter.cpp b/searchcore/src/vespa/searchcore/proton/docsummary/documentstoreadapter.cpp index 85ae621db48..ea6a16e1547 100644 --- a/searchcore/src/vespa/searchcore/proton/docsummary/documentstoreadapter.cpp +++ b/searchcore/src/vespa/searchcore/proton/docsummary/documentstoreadapter.cpp @@ -66,10 +66,10 @@ DocumentStoreAdapter::writeField(const FieldValue &value, ResType type) const LiteralFieldValueB & lfv = static_cast<const LiteralFieldValueB &>(value); vespalib::stringref s = lfv.getValueRef(); - return writeStringField(s.c_str(), s.size(), type); + return writeStringField(s.data(), s.size(), type); } else { vespalib::string s = value.getAsString(); - return writeStringField(s.c_str(), s.size(), type); + return writeStringField(s.data(), s.size(), type); } } case RES_DATA: diff --git a/searchcore/src/vespa/searchcore/proton/docsummary/fieldcache.cpp b/searchcore/src/vespa/searchcore/proton/docsummary/fieldcache.cpp index 92bb7da55e1..9579c99ff42 100644 --- a/searchcore/src/vespa/searchcore/proton/docsummary/fieldcache.cpp +++ b/searchcore/src/vespa/searchcore/proton/docsummary/fieldcache.cpp @@ -26,7 +26,7 @@ FieldCache::FieldCache(const ResultClass &resClass, if (docType.hasField(fieldName)) { const Field &field = docType.getField(fieldName); LOG(debug, "Caching Field instance for field '%s': %s.%u", - fieldName.c_str(), field.getName().c_str(), field.getId()); + fieldName.c_str(), vespalib::string(field.getName()).c_str(), field.getId()); _cache.push_back(Field::CSP(new Field(field))); } else { _cache.push_back(Field::CSP()); diff --git a/searchcore/src/vespa/searchcore/proton/server/documentretriever.cpp b/searchcore/src/vespa/searchcore/proton/server/documentretriever.cpp index a7bd61e75d4..5310d132092 100644 --- a/searchcore/src/vespa/searchcore/proton/server/documentretriever.cpp +++ b/searchcore/src/vespa/searchcore/proton/server/documentretriever.cpp @@ -48,7 +48,7 @@ DocumentRetriever LOG(debug, "checking document type '%s' for position fields", docTypeName.getName().c_str()); for (const document::Field * field : fields) { if (field->getDataType().getId() == positionDataTypeId) { - LOG(debug, "Field '%s' is a position field", field->getName().c_str()); + LOG(debug, "Field '%s' is a position field", vespalib::string(field->getName()).c_str()); const vespalib::string & zcurve_name = PositionDataType::getZCurveFieldName(field->getName()); AttributeGuard::UP attr = attr_manager.getAttribute(zcurve_name); if (attr && attr->valid()) { diff --git a/searchcore/src/vespa/searchcore/proton/server/memoryflush.cpp b/searchcore/src/vespa/searchcore/proton/server/memoryflush.cpp index 7d97cc4030a..d72ef274d99 100644 --- a/searchcore/src/vespa/searchcore/proton/server/memoryflush.cpp +++ b/searchcore/src/vespa/searchcore/proton/server/memoryflush.cpp @@ -213,7 +213,7 @@ MemoryFlush::getFlushTargets(const FlushContext::List &targetList, } oss << fv[i]->getName(); } - LOG(debug, "getFlushTargets(): %zu sorted targets: [%s]", fv.size(), oss.str().c_str()); + LOG(debug, "getFlushTargets(): %zu sorted targets: [%s]", fv.size(), oss.str().data()); } return fv; } diff --git a/searchcorespi/src/vespa/searchcorespi/index/eventlogger.cpp b/searchcorespi/src/vespa/searchcorespi/index/eventlogger.cpp index 9d824d69f93..cf1daf983b3 100644 --- a/searchcorespi/src/vespa/searchcorespi/index/eventlogger.cpp +++ b/searchcorespi/src/vespa/searchcorespi/index/eventlogger.cpp @@ -19,7 +19,7 @@ EventLogger::diskIndexLoadStart(const vespalib::string &indexDir) jstr.appendKey("input"); LogUtil::logDir(jstr, indexDir, 6); jstr.endObject(); - EV_STATE("diskindex.load.start", jstr.toString().c_str()); + EV_STATE("diskindex.load.start", jstr.toString().data()); } void @@ -32,7 +32,7 @@ EventLogger::diskIndexLoadComplete(const vespalib::string &indexDir, jstr.appendKey("input"); LogUtil::logDir(jstr, indexDir, 6); jstr.endObject(); - EV_STATE("diskindex.load.complete", jstr.toString().c_str()); + EV_STATE("diskindex.load.complete", jstr.toString().data()); } void @@ -50,7 +50,7 @@ EventLogger::diskFusionStart(const std::vector<vespalib::string> &sources, jstr.appendKey("output"); LogUtil::logDir(jstr, fusionDir, 6); jstr.endObject(); - EV_STATE("fusion.start", jstr.toString().c_str()); + EV_STATE("fusion.start", jstr.toString().data()); } void @@ -63,7 +63,7 @@ EventLogger::diskFusionComplete(const vespalib::string &fusionDir, jstr.appendKey("output"); LogUtil::logDir(jstr, fusionDir, 6); jstr.endObject(); - EV_STATE("fusion.complete", jstr.toString().c_str()); + EV_STATE("fusion.complete", jstr.toString().data()); } } diff --git a/searchcorespi/src/vespa/searchcorespi/plugin/factoryloader.cpp b/searchcorespi/src/vespa/searchcorespi/plugin/factoryloader.cpp index 1dac8c7aafd..3180f7ed29d 100644 --- a/searchcorespi/src/vespa/searchcorespi/plugin/factoryloader.cpp +++ b/searchcorespi/src/vespa/searchcorespi/plugin/factoryloader.cpp @@ -25,7 +25,8 @@ FactoryLoader::create(const stringref & factory) const FastOS_DynamicLibrary & lib = *_libraries.get(factory); FuncT registrationMethod = reinterpret_cast<FuncT>(lib.GetSymbol("createIndexManagerFactory")); if (registrationMethod == NULL) { - throw IllegalArgumentException(make_string("Failed locating symbol 'createIndexManagerFactory' in library '%s' for factory '%s'.", lib.GetLibName(), factory.c_str())); + throw IllegalArgumentException(make_string("Failed locating symbol 'createIndexManagerFactory' in library '%s' for factory '%s'.", + lib.GetLibName(), vespalib::string(factory).c_str())); } return IIndexManagerFactory::UP(registrationMethod()); } diff --git a/searchlib/src/tests/attribute/benchmark/attributesearcher.h b/searchlib/src/tests/attribute/benchmark/attributesearcher.h index f8cd614c48c..37f33803d27 100644 --- a/searchlib/src/tests/attribute/benchmark/attributesearcher.h +++ b/searchlib/src/tests/attribute/benchmark/attributesearcher.h @@ -126,7 +126,7 @@ AttributeFindSearcher<T>::doRun() // build simple term query vespalib::asciistream ss; ss << _values[i % _values.size()].getValue(); - this->buildTermQuery(_query, _attrPtr->getName(), ss.str().c_str()); + this->buildTermQuery(_query, _attrPtr->getName(), ss.str().data()); AttributeGuard guard(_attrPtr); std::unique_ptr<AttributeVector::SearchContext> searchContext = @@ -204,7 +204,7 @@ AttributeRangeSearcher::doRun() // build simple range term query vespalib::asciistream ss; ss << "[" << iter.a() << ";" << iter.b() << "]"; - buildTermQuery(_query, _attrPtr->getName(), ss.str().c_str()); + buildTermQuery(_query, _attrPtr->getName(), ss.str().data()); AttributeGuard guard(_attrPtr); std::unique_ptr<AttributeVector::SearchContext> searchContext = diff --git a/searchlib/src/tests/stackdumpiterator/stackdumpiteratortest.cpp b/searchlib/src/tests/stackdumpiterator/stackdumpiteratortest.cpp index 8ad4578b6c1..37a63828667 100644 --- a/searchlib/src/tests/stackdumpiterator/stackdumpiteratortest.cpp +++ b/searchlib/src/tests/stackdumpiterator/stackdumpiteratortest.cpp @@ -172,12 +172,12 @@ StackDumpIteratorTest::ShowResult(int testNo, delete item; break; } - if (strncmp(item->_indexName.c_str(), idx.c_str(), idx.size()) != 0) { + if (strncmp(item->_indexName.c_str(), idx.data(), idx.size()) != 0) { results |= ITERATOR_ERROR_WRONG_INDEX; delete item; break; } - if (strncmp(item->_term.c_str(), term.c_str(), term.size()) != 0) { + if (strncmp(item->_term.c_str(), term.data(), term.size()) != 0) { results |= ITERATOR_ERROR_WRONG_TERM; delete item; break; diff --git a/searchlib/src/vespa/searchlib/common/packets.cpp b/searchlib/src/vespa/searchlib/common/packets.cpp index b6b0baea92a..90157e318e9 100644 --- a/searchlib/src/vespa/searchlib/common/packets.cpp +++ b/searchlib/src/vespa/searchlib/common/packets.cpp @@ -243,7 +243,7 @@ void FS4Properties::set(StringRef & e, const vespalib::stringref & s) { e.first = _backing.size(); e.second = s.size(); - _backing.append(s.c_str(), s.size()); + _backing.append(s.data(), s.size()); } void diff --git a/searchlib/src/vespa/searchlib/diskindex/dictionarywordreader.cpp b/searchlib/src/vespa/searchlib/diskindex/dictionarywordreader.cpp index e3c5853d74e..b820a77724b 100644 --- a/searchlib/src/vespa/searchlib/diskindex/dictionarywordreader.cpp +++ b/searchlib/src/vespa/searchlib/diskindex/dictionarywordreader.cpp @@ -28,8 +28,8 @@ DictionaryWordReader::~DictionaryWordReader() bool -DictionaryWordReader::open(const vespalib::stringref &dictionaryName, - const vespalib::stringref & wordMapName, +DictionaryWordReader::open(const vespalib::string & dictionaryName, + const vespalib::string & wordMapName, const TuneFileSeqRead &tuneFileRead) { _old2newwordfile.reset(new Fast_BufferedFile(new FastOS_File)); diff --git a/searchlib/src/vespa/searchlib/diskindex/dictionarywordreader.h b/searchlib/src/vespa/searchlib/diskindex/dictionarywordreader.h index 7204ba14d25..9436c17cdbc 100644 --- a/searchlib/src/vespa/searchlib/diskindex/dictionarywordreader.h +++ b/searchlib/src/vespa/searchlib/diskindex/dictionarywordreader.h @@ -106,8 +106,8 @@ public: } bool - open(const vespalib::stringref & dictionaryName, - const vespalib::stringref & wordMapName, + open(const vespalib::string & dictionaryName, + const vespalib::string & wordMapName, const TuneFileSeqRead &tuneFileRead); void diff --git a/searchlib/src/vespa/searchlib/diskindex/indexbuilder.cpp b/searchlib/src/vespa/searchlib/diskindex/indexbuilder.cpp index 99eced5f97b..b879e1f65a6 100644 --- a/searchlib/src/vespa/searchlib/diskindex/indexbuilder.cpp +++ b/searchlib/src/vespa/searchlib/diskindex/indexbuilder.cpp @@ -296,7 +296,7 @@ FileHandle::open(const vespalib::stringref &dir, index.getSchema(), index.getIndex(), tuneFileWrite, fileHeaderContext)) { LOG(error, "Could not open term writer %s for write (%s)", - dir.c_str(), getLastErrorString().c_str()); + vespalib::string(dir).c_str(), getLastErrorString().c_str()); LOG_ABORT("should not be reached"); } } diff --git a/searchlib/src/vespa/searchlib/docstore/chunkformat.cpp b/searchlib/src/vespa/searchlib/docstore/chunkformat.cpp index 37381cfa3f6..93f1d9c0d51 100644 --- a/searchlib/src/vespa/searchlib/docstore/chunkformat.cpp +++ b/searchlib/src/vespa/searchlib/docstore/chunkformat.cpp @@ -13,7 +13,7 @@ using vespalib::compression::decompress; using vespalib::compression::computeMaxCompressedsize; using vespalib::compression::CompressionConfig; -ChunkException::ChunkException(const vespalib::stringref & msg, const vespalib::stringref & location) : +ChunkException::ChunkException(const vespalib::string & msg, const vespalib::stringref & location) : Exception(make_string("Illegal chunk: %s", msg.c_str()), location) { } diff --git a/searchlib/src/vespa/searchlib/docstore/chunkformat.h b/searchlib/src/vespa/searchlib/docstore/chunkformat.h index 9f9580f1f1d..81feaf2a27f 100644 --- a/searchlib/src/vespa/searchlib/docstore/chunkformat.h +++ b/searchlib/src/vespa/searchlib/docstore/chunkformat.h @@ -12,7 +12,7 @@ namespace search { class ChunkException : public vespalib::Exception { public: - ChunkException(const vespalib::stringref & msg, const vespalib::stringref & location); + ChunkException(const vespalib::string & msg, const vespalib::stringref & location); }; // This is an interface for implementing a chunk format diff --git a/searchlib/src/vespa/searchlib/docstore/logdatastore.cpp b/searchlib/src/vespa/searchlib/docstore/logdatastore.cpp index 1f5a904a514..148d77738f9 100644 --- a/searchlib/src/vespa/searchlib/docstore/logdatastore.cpp +++ b/searchlib/src/vespa/searchlib/docstore/logdatastore.cpp @@ -934,7 +934,7 @@ LogDataStore::scanDir(const vespalib::string &dir, const vespalib::string &suffi base.c_str(), err, getLastErrorString().c_str())); } } else { - LOG(debug, "Skipping '%s' since it does not end with '%s'", file.c_str(), suffix.c_str()); + LOG(debug, "Skipping '%s' since it does not end with '%s'", file.data(), suffix.c_str()); } } } diff --git a/searchlib/src/vespa/searchlib/docstore/summaryexceptions.cpp b/searchlib/src/vespa/searchlib/docstore/summaryexceptions.cpp index 30c825bca65..2cfa023e7ed 100644 --- a/searchlib/src/vespa/searchlib/docstore/summaryexceptions.cpp +++ b/searchlib/src/vespa/searchlib/docstore/summaryexceptions.cpp @@ -12,7 +12,7 @@ SummaryException::SummaryException(const vespalib::stringref &msg, FastOS_FileInterface &file, const vespalib::stringref &location) : IoException(make_string("%s : Failing file = '%s'. Reason given by OS = '%s'", - msg.c_str(), file.GetFileName(), file.getLastErrorString().c_str()), + vespalib::string(msg).c_str(), file.GetFileName(), file.getLastErrorString().c_str()), getErrorType(file.GetLastError()), location) { } diff --git a/searchlib/src/vespa/searchlib/engine/transportserver.cpp b/searchlib/src/vespa/searchlib/engine/transportserver.cpp index 005ef473817..c94e36202a1 100644 --- a/searchlib/src/vespa/searchlib/engine/transportserver.cpp +++ b/searchlib/src/vespa/searchlib/engine/transportserver.cpp @@ -322,7 +322,7 @@ TransportServer::logPacket(const vespalib::stringref &msg, FNET_Packet *p, FNET_ } else { str = vespalib::make_string("packet { pcode=%u }", p->GetPCODE()); } - LOG(debug, "%s (chid=%u, conn=%u):\n%s", msg.c_str(), chid, conntag, str.c_str()); + LOG(debug, "%s (chid=%u, conn=%u):\n%s", msg.data(), chid, conntag, str.c_str()); } void diff --git a/searchlib/src/vespa/searchlib/expression/catserializer.cpp b/searchlib/src/vespa/searchlib/expression/catserializer.cpp index a01f68de1a4..f613bd16a54 100644 --- a/searchlib/src/vespa/searchlib/expression/catserializer.cpp +++ b/searchlib/src/vespa/searchlib/expression/catserializer.cpp @@ -17,7 +17,7 @@ using vespalib::stringref; CatSerializer & CatSerializer::put(const IFieldBase & field, const stringref & value) { (void) field; - getStream().write(value.c_str(), value.size()); + getStream().write(value.data(), value.size()); return *this; } diff --git a/searchlib/src/vespa/searchlib/expression/documentfieldnode.cpp b/searchlib/src/vespa/searchlib/expression/documentfieldnode.cpp index 2055cf9c18c..c7ce9528520 100644 --- a/searchlib/src/vespa/searchlib/expression/documentfieldnode.cpp +++ b/searchlib/src/vespa/searchlib/expression/documentfieldnode.cpp @@ -77,7 +77,8 @@ deduceResultNode(const vespalib::stringref & fieldName, const FieldValue & fv, b } else if (cInfo.inherits(MapFieldValue::classId)) { value = deduceResultNode(fieldName, *static_cast<const MapFieldValue &>(fv).createValue(), preserveAccurateTypes, nestedMultiValue); } else { - throw std::runtime_error(make_string("Can not deduce correct resultclass for documentfield '%s' in based on class '%s'", fieldName.c_str(), cInfo.name())); + throw std::runtime_error(make_string("Can not deduce correct resultclass for documentfield '%s' in based on class '%s'", + vespalib::string(fieldName).c_str(), cInfo.name())); } const Identifiable::RuntimeClass & rInfo = value->getClass(); if (rInfo.inherits(ResultNodeVector::classId)) { @@ -97,10 +98,12 @@ deduceResultNode(const vespalib::stringref & fieldName, const FieldValue & fv, b } else if (rInfo.inherits(RawResultNode::classId)) { value.reset(new RawResultNodeVector()); } else { - throw std::runtime_error(make_string("Can not deduce correct resultclass for documentfield '%s' in based on class '%s'. It nests down to %s which is not expected", fieldName.c_str(), cInfo.name(), rInfo.name())); + throw std::runtime_error(make_string("Can not deduce correct resultclass for documentfield '%s' in based on class '%s'. It nests down to %s which is not expected", + vespalib::string(fieldName).c_str(), cInfo.name(), rInfo.name())); } } else { - throw std::runtime_error(make_string("Can not deduce correct resultclass for documentfield '%s' in based on class '%s'", fieldName.c_str(), cInfo.name())); + throw std::runtime_error(make_string("Can not deduce correct resultclass for documentfield '%s' in based on class '%s'", + vespalib::string(fieldName).c_str(), cInfo.name())); } return value; } diff --git a/searchlib/src/vespa/searchlib/features/array_parser.hpp b/searchlib/src/vespa/searchlib/features/array_parser.hpp index 613fa9ec13e..92abec3aab9 100644 --- a/searchlib/src/vespa/searchlib/features/array_parser.hpp +++ b/searchlib/src/vespa/searchlib/features/array_parser.hpp @@ -52,13 +52,13 @@ ArrayParser::parsePartial(const vespalib::string &input, OutputType &output) logWarning(vespalib::make_string( "Could not parse item '%s' in query vector '%s', skipping. " "Expected ':' between dimension and component.", - item.c_str(), input.c_str())); + vespalib::string(item).c_str(), input.c_str())); return; } } catch (vespalib::IllegalArgumentException & e) { logWarning(vespalib::make_string( "Could not parse item '%s' in query vector '%s', skipping. " - "Incorrect type of operands", item.c_str(), input.c_str())); + "Incorrect type of operands", vespalib::string(item).c_str(), input.c_str())); return; } if (commaPos != vespalib::string::npos) { @@ -77,7 +77,7 @@ ArrayParser::parsePartial(const vespalib::string &input, OutputType &output) } catch (vespalib::IllegalArgumentException & e) { logWarning(vespalib::make_string( "Could not parse item[%ld] = '%s' in query vector '%s', skipping. " - "Incorrect type of operands", output.size(), is.c_str(), s.c_str())); + "Incorrect type of operands", output.size(), is.c_str(), vespalib::string(s).c_str())); return; } } diff --git a/searchlib/src/vespa/searchlib/features/attributefeature.cpp b/searchlib/src/vespa/searchlib/features/attributefeature.cpp index b400233bd99..7e913f96b7f 100644 --- a/searchlib/src/vespa/searchlib/features/attributefeature.cpp +++ b/searchlib/src/vespa/searchlib/features/attributefeature.cpp @@ -43,7 +43,7 @@ bool equals(const X & lhs, const Y & rhs) { template <> bool equals<ConstCharPtr, vespalib::stringref>(const ConstCharPtr & lhs, const vespalib::stringref & rhs) { - return strcmp(lhs, rhs.c_str()) == 0; + return strcmp(lhs, rhs.data()) == 0; } template <typename T> diff --git a/searchlib/src/vespa/searchlib/features/dotproductfeature.h b/searchlib/src/vespa/searchlib/features/dotproductfeature.h index 27e96c26538..e3cd662cdd8 100644 --- a/searchlib/src/vespa/searchlib/features/dotproductfeature.h +++ b/searchlib/src/vespa/searchlib/features/dotproductfeature.h @@ -100,7 +100,7 @@ public: EnumVector(const search::attribute::IAttributeVector * attribute) : _attribute(attribute) {} void insert(const vespalib::stringref & label, const vespalib::stringref & value) { search::attribute::EnumHandle e; - if (_attribute->findEnum(label.c_str(), e)) { + if (_attribute->findEnum(label.data(), e)) { _vector.push_back(std::make_pair(e, util::strToNum<feature_t>(value))); } } diff --git a/searchlib/src/vespa/searchlib/features/weighted_set_parser.hpp b/searchlib/src/vespa/searchlib/features/weighted_set_parser.hpp index 3199d54bf03..d67b089f5fe 100644 --- a/searchlib/src/vespa/searchlib/features/weighted_set_parser.hpp +++ b/searchlib/src/vespa/searchlib/features/weighted_set_parser.hpp @@ -24,13 +24,13 @@ WeightedSetParser::parse(const vespalib::string &input, OutputType &output) if (colonPos != vespalib::string::npos) { vespalib::string tmpKey(item.substr(0, colonPos)); vespalib::string::size_type start(tmpKey.find_first_not_of(' ')); - vespalib::stringref key(tmpKey.c_str() + start, colonPos - start); + vespalib::stringref key(tmpKey.data() + start, colonPos - start); vespalib::stringref value(item.substr(colonPos+1)); output.insert(key, value); } else { logWarning(vespalib::make_string( "Could not parse item '%s' in input string '%s', skipping. " - "Expected ':' between key and weight.", item.c_str(), input.c_str())); + "Expected ':' between key and weight.", vespalib::string(item).c_str(), input.c_str())); } if (commaPos != vespalib::string::npos) { s = s.substr(commaPos+1); diff --git a/searchlib/src/vespa/searchlib/memoryindex/fieldinverter.cpp b/searchlib/src/vespa/searchlib/memoryindex/fieldinverter.cpp index 3238243ff0b..957573d0ad7 100644 --- a/searchlib/src/vespa/searchlib/memoryindex/fieldinverter.cpp +++ b/searchlib/src/vespa/searchlib/memoryindex/fieldinverter.cpp @@ -256,7 +256,7 @@ FieldInverter::saveWord(const vespalib::stringref word) char * buf = &_words[0] + wordsSize; memset(buf, 0, 4); - memcpy(buf + 4, word.c_str(), len); + memcpy(buf + 4, word.data(), len); uint32_t *lastWord = reinterpret_cast<uint32_t *>(buf + 4 + (len & ~0x3)); *lastWord &= (0xffffff >> ((3 - (len & 3)) << 3)); //only on little endian machiness !! diff --git a/searchlib/src/vespa/searchlib/memoryindex/memoryfieldindex.h b/searchlib/src/vespa/searchlib/memoryindex/memoryfieldindex.h index 92a69277b76..c4583d7f49f 100644 --- a/searchlib/src/vespa/searchlib/memoryindex/memoryfieldindex.h +++ b/searchlib/src/vespa/searchlib/memoryindex/memoryfieldindex.h @@ -52,7 +52,7 @@ public: if (wordRef.valid()) { return _wordStore.getWord(wordRef); } - return _word.c_str(); + return _word.data(); } public: diff --git a/searchlib/src/vespa/searchlib/memoryindex/urlfieldinverter.cpp b/searchlib/src/vespa/searchlib/memoryindex/urlfieldinverter.cpp index 527de32b956..0f8c05a44b9 100644 --- a/searchlib/src/vespa/searchlib/memoryindex/urlfieldinverter.cpp +++ b/searchlib/src/vespa/searchlib/memoryindex/urlfieldinverter.cpp @@ -130,7 +130,7 @@ UrlFieldInverter::processUrlSubField(FieldInverter *inverter, LOG(error, "Illegal field type %s for URL subfield %s, expected string", sfv->getDataType()->getName().c_str(), - subField.c_str()); + vespalib::string(subField).data()); return; } const StringFieldValue &value = static_cast<const StringFieldValue &>(*sfv); diff --git a/searchlib/src/vespa/searchlib/parsequery/parse.cpp b/searchlib/src/vespa/searchlib/parsequery/parse.cpp index cba69ea474a..60236275f76 100644 --- a/searchlib/src/vespa/searchlib/parsequery/parse.cpp +++ b/searchlib/src/vespa/searchlib/parsequery/parse.cpp @@ -63,7 +63,7 @@ ParseItem::ParseItem(ItemType type, const vespalib::stringref & idx, const char { assert_type(type); SetType(type); - SetIndex(idx.c_str()); + SetIndex(idx.data()); SetTerm(term); } diff --git a/searchlib/src/vespa/searchlib/query/queryterm.cpp b/searchlib/src/vespa/searchlib/query/queryterm.cpp index ee2e72b41a8..5eabaf35378 100644 --- a/searchlib/src/vespa/searchlib/query/queryterm.cpp +++ b/searchlib/src/vespa/searchlib/query/queryterm.cpp @@ -386,16 +386,16 @@ QueryTermSimple::QueryTermSimple(const string & term_, SearchTerm type) : } _valid = (numParts >= 2) && (numParts < NELEMS(parts)); if (_valid && numParts > 2) { - _rangeLimit = strtol(parts[2].c_str(), NULL, 0); + _rangeLimit = strtol(parts[2].data(), nullptr, 0); if (numParts > 3) { _valid = (numParts >= 5); if (_valid) { _diversityAttribute = parts[3]; - _maxPerGroup = strtoul(parts[4].c_str(), NULL, 0); + _maxPerGroup = strtoul(parts[4].data(), nullptr, 0); if ((_maxPerGroup > 0) && (numParts > 5)) { char *err = nullptr; - size_t cutoffGroups = strtoul(parts[5].c_str(), &err, 0); - if ((err == nullptr) || (size_t(err - parts[5].c_str()) == parts[5].size())) { + size_t cutoffGroups = strtoul(parts[5].data(), &err, 0); + if ((err == nullptr) || (size_t(err - parts[5].data()) == parts[5].size())) { _diversityCutoffGroups = cutoffGroups; } if (numParts > 6) { diff --git a/searchlib/src/vespa/searchlib/query/tree/stackdumpquerycreator.h b/searchlib/src/vespa/searchlib/query/tree/stackdumpquerycreator.h index fa42cdac1c0..a208ae357fa 100644 --- a/searchlib/src/vespa/searchlib/query/tree/stackdumpquerycreator.h +++ b/searchlib/src/vespa/searchlib/query/tree/stackdumpquerycreator.h @@ -41,7 +41,7 @@ public: vespalib::stringref stack = queryStack.getStack(); LOG(error, "Unable to create query tree from stack dump. Failed at position %ld out of %ld bytes %s", queryStack.getPosition(), stack.size(), builder.error().c_str()); - LOG(error, "Raw QueryStack = %s", vespalib::HexDump(stack.c_str(), stack.size()).toString().c_str()); + LOG(error, "Raw QueryStack = %s", vespalib::HexDump(stack.data(), stack.size()).toString().c_str()); if (LOG_WOULD_LOG(debug)) { vespalib::string query = SimpleQueryStack::StackbufToString(stack); LOG(error, "Error = %s, QueryStack = %s", builder.error().c_str(), query.c_str()); diff --git a/searchlib/src/vespa/searchlib/uca/ucaconverter.cpp b/searchlib/src/vespa/searchlib/uca/ucaconverter.cpp index fffcc782298..b36e9d13cdb 100644 --- a/searchlib/src/vespa/searchlib/uca/ucaconverter.cpp +++ b/searchlib/src/vespa/searchlib/uca/ucaconverter.cpp @@ -32,7 +32,7 @@ UcaConverter::UcaConverter(vespalib::stringref locale, vespalib::stringref stren Collator *coll(NULL); { std::lock_guard<std::mutex> guard(_GlobalDirtyICUThreadSafeLock); - coll = Collator::createInstance(icu::Locale(locale.c_str()), status); + coll = Collator::createInstance(icu::Locale(locale.data()), status); } if(U_SUCCESS(status)) { _collator.reset(coll); diff --git a/searchlib/src/vespa/searchlib/util/filekit.cpp b/searchlib/src/vespa/searchlib/util/filekit.cpp index 210a9c30134..7fc4ca8e7bb 100644 --- a/searchlib/src/vespa/searchlib/util/filekit.cpp +++ b/searchlib/src/vespa/searchlib/util/filekit.cpp @@ -12,7 +12,7 @@ namespace search { using vespalib::getLastErrorString; bool -FileKit::createStamp(const vespalib::stringref &name) +FileKit::createStamp(const vespalib::string &name) { FastOS_File stamp; FastOS_StatInfo statInfo; @@ -40,7 +40,7 @@ FileKit::createStamp(const vespalib::stringref &name) bool -FileKit::hasStamp(const vespalib::stringref &name) +FileKit::hasStamp(const vespalib::string &name) { FastOS_StatInfo statInfo; bool statres; @@ -57,7 +57,7 @@ FileKit::hasStamp(const vespalib::stringref &name) bool -FileKit::removeStamp(const vespalib::stringref &name) +FileKit::removeStamp(const vespalib::string &name) { FastOS_StatInfo statInfo; bool deleteres; @@ -91,7 +91,7 @@ FileKit::removeStamp(const vespalib::stringref &name) fastos::TimeStamp -FileKit::getModificationTime(const vespalib::stringref &name) +FileKit::getModificationTime(const vespalib::string &name) { FastOS_StatInfo statInfo; if (FastOS_File::Stat(name.c_str(), &statInfo)) { diff --git a/searchlib/src/vespa/searchlib/util/filekit.h b/searchlib/src/vespa/searchlib/util/filekit.h index 70acf19c70c..929412ee6d8 100644 --- a/searchlib/src/vespa/searchlib/util/filekit.h +++ b/searchlib/src/vespa/searchlib/util/filekit.h @@ -12,15 +12,15 @@ class FileKit private: static bool _syncFiles; public: - static bool createStamp(const vespalib::stringref &name); - static bool hasStamp(const vespalib::stringref &name); - static bool removeStamp(const vespalib::stringref &name); + static bool createStamp(const vespalib::string &name); + static bool hasStamp(const vespalib::string &name); + static bool removeStamp(const vespalib::string &name); /** * Returns the modification time of the given file/directory, * or time stamp 0 if stating of file/directory fails. **/ - static fastos::TimeStamp getModificationTime(const vespalib::stringref &name); + static fastos::TimeStamp getModificationTime(const vespalib::string &name); }; } diff --git a/searchsummary/src/vespa/searchsummary/docsummary/dynamicteaserdfw.cpp b/searchsummary/src/vespa/searchsummary/docsummary/dynamicteaserdfw.cpp index c7eb63a4480..73c62db864c 100644 --- a/searchsummary/src/vespa/searchsummary/docsummary/dynamicteaserdfw.cpp +++ b/searchsummary/src/vespa/searchsummary/docsummary/dynamicteaserdfw.cpp @@ -159,7 +159,7 @@ public: { if (item->_si != NULL) { *len = item->_si->getIndexName().size(); - return item->_si->getIndexName().c_str(); + return item->_si->getIndexName().data(); } else { *len = item->_data->_indexlen; return item->_data->_index; @@ -221,7 +221,7 @@ JuniperQueryAdapter::Traverse(juniper::IQueryVisitor *v) const case search::ParseItem::ITEM_PURE_WEIGHTED_STRING: { vespalib::stringref term = iterator.getTerm(); - v->VisitKeyword(&item, term.c_str(), term.size(), false, isSpecialToken); + v->VisitKeyword(&item, term.data(), term.size(), false, isSpecialToken); } break; case search::ParseItem::ITEM_NUMTERM: @@ -257,7 +257,7 @@ JuniperQueryAdapter::Traverse(juniper::IQueryVisitor *v) const case search::ParseItem::ITEM_SUBSTRINGTERM: { vespalib::stringref term = iterator.getTerm(); - v->VisitKeyword(&item, term.c_str(), term.size(), true, isSpecialToken); + v->VisitKeyword(&item, term.data(), term.size(), true, isSpecialToken); } break; case search::ParseItem::ITEM_ANY: diff --git a/searchsummary/src/vespa/searchsummary/docsummary/itokenizer.h b/searchsummary/src/vespa/searchsummary/docsummary/itokenizer.h index 62f2510c17b..15a367761ec 100644 --- a/searchsummary/src/vespa/searchsummary/docsummary/itokenizer.h +++ b/searchsummary/src/vespa/searchsummary/docsummary/itokenizer.h @@ -37,7 +37,7 @@ public: _text(textBegin, textEnd - textBegin), _stem(stemBegin, stemEnd - stemBegin), _type(type) {} const vespalib::stringref & getText() const { return _text; } const vespalib::stringref & getStem() const { return _stem; } - bool hasStem() const { return _stem.c_str() != NULL; } + bool hasStem() const { return _stem.data() != NULL; } Type getType() const { return _type; } }; diff --git a/searchsummary/src/vespa/searchsummary/docsummary/keywordextractor.cpp b/searchsummary/src/vespa/searchsummary/docsummary/keywordextractor.cpp index 3a60db52cf3..d75ca47dd33 100644 --- a/searchsummary/src/vespa/searchsummary/docsummary/keywordextractor.cpp +++ b/searchsummary/src/vespa/searchsummary/docsummary/keywordextractor.cpp @@ -195,7 +195,7 @@ KeywordExtractor::ExtractKeywords(vespalib::stringref buf) const phraseterms_was_added = true; } - keywords.append(term.c_str(), term.size()); + keywords.append(term.data(), term.size()); } } } @@ -218,7 +218,7 @@ KeywordExtractor::ExtractKeywords(vespalib::stringref buf) const vespalib::stringref term = si.getTerm(); if ( !term.empty() && useful(creator)) { // An actual string to add - keywords.append(term.c_str(), term.size()); + keywords.append(term.data(), term.size()); keywords.append("\0", 1); } } diff --git a/searchsummary/src/vespa/searchsummary/docsummary/rankfeaturesdfw.cpp b/searchsummary/src/vespa/searchsummary/docsummary/rankfeaturesdfw.cpp index 7097012c5ea..9748bdac3b3 100644 --- a/searchsummary/src/vespa/searchsummary/docsummary/rankfeaturesdfw.cpp +++ b/searchsummary/src/vespa/searchsummary/docsummary/rankfeaturesdfw.cpp @@ -47,7 +47,7 @@ RankFeaturesDFW::insertField(uint32_t docid, GeneralResult *, GetDocsumsState *s featureDump(json, names[i], values[i]); } json.endObject(); - vespalib::Memory value(json.toString().c_str(), + vespalib::Memory value(json.toString().data(), json.toString().size()); if (type == RES_STRING || type == RES_LONG_STRING) { target.insertString(value); diff --git a/searchsummary/src/vespa/searchsummary/docsummary/summaryfeaturesdfw.cpp b/searchsummary/src/vespa/searchsummary/docsummary/summaryfeaturesdfw.cpp index c21d6c40066..a5fb9bd8539 100644 --- a/searchsummary/src/vespa/searchsummary/docsummary/summaryfeaturesdfw.cpp +++ b/searchsummary/src/vespa/searchsummary/docsummary/summaryfeaturesdfw.cpp @@ -68,7 +68,7 @@ SummaryFeaturesDFW::insertField(uint32_t docid, GeneralResult *, GetDocsumsState json.appendDouble(0.0); } json.endObject(); - vespalib::Memory value(json.toString().c_str(), json.toString().size()); + vespalib::Memory value(json.toString().data(), json.toString().size()); if (type == RES_STRING || type == RES_LONG_STRING) { target.insertString(value); } diff --git a/staging_vespalib/src/tests/memorydatastore/memorydatastore.cpp b/staging_vespalib/src/tests/memorydatastore/memorydatastore.cpp index f6427f8acd2..7d047e36566 100644 --- a/staging_vespalib/src/tests/memorydatastore/memorydatastore.cpp +++ b/staging_vespalib/src/tests/memorydatastore/memorydatastore.cpp @@ -40,20 +40,20 @@ MemoryDataStoreTest::testVariableSizeVector() for (size_t i(0); i < 10000; i++) { asciistream os; os << i; - v.push_back(os.str().c_str(), os.str().size()); + v.push_back(os.str().data(), os.str().size()); } for (size_t i(0); i < v.size(); i++) { asciistream os; os << i; EXPECT_EQUAL(os.str().size(), v[i].size()); - EXPECT_EQUAL(0, memcmp(os.str().c_str(), v[i].data(), os.str().size())); + EXPECT_EQUAL(0, memcmp(os.str().data(), v[i].data(), os.str().size())); } size_t i(0); for (auto it(v.begin()), mt(v.end()); it != mt; it++, i++) { asciistream os; os << i; EXPECT_EQUAL(os.str().size(), it->size()); - EXPECT_EQUAL(0, memcmp(os.str().c_str(), (*it).data(), os.str().size())); + EXPECT_EQUAL(0, memcmp(os.str().data(), (*it).data(), os.str().size())); } } diff --git a/staging_vespalib/src/vespa/vespalib/util/growablebytebuffer.cpp b/staging_vespalib/src/vespa/vespalib/util/growablebytebuffer.cpp index 53875fe7241..22064864b22 100644 --- a/staging_vespalib/src/vespa/vespalib/util/growablebytebuffer.cpp +++ b/staging_vespalib/src/vespa/vespalib/util/growablebytebuffer.cpp @@ -72,7 +72,7 @@ void GrowableByteBuffer::putString(const vespalib::stringref& v) { putInt(v.size()); - putBytes(v.c_str(), v.size()); + putBytes(v.data(), v.size()); } void diff --git a/staging_vespalib/src/vespa/vespalib/util/jsonwriter.cpp b/staging_vespalib/src/vespa/vespalib/util/jsonwriter.cpp index ebeda4f1b8b..0ad52f9aac2 100644 --- a/staging_vespalib/src/vespa/vespalib/util/jsonwriter.cpp +++ b/staging_vespalib/src/vespa/vespalib/util/jsonwriter.cpp @@ -177,7 +177,7 @@ JSONWriter::appendKey(const vespalib::stringref & str) { considerComma(); indent(); - quote(str.c_str(), str.size()); + quote(str.data(), str.size()); (*_os) << ':'; _comma = false; return *this; @@ -246,7 +246,7 @@ JSONWriter & JSONWriter::appendString(const vespalib::stringref & str) { considerComma(); - quote(str.c_str(), str.size()); + quote(str.data(), str.size()); updateCommaState(); return *this; } diff --git a/storage/src/tests/bucketdb/bucketinfotest.cpp b/storage/src/tests/bucketdb/bucketinfotest.cpp index 3eb8d60befd..0298c50866c 100644 --- a/storage/src/tests/bucketdb/bucketinfotest.cpp +++ b/storage/src/tests/bucketdb/bucketinfotest.cpp @@ -51,14 +51,14 @@ getBucketInfo(std::string nodeList, std::string order) { { vespalib::StringTokenizer tokenizer(order, ","); for (uint32_t i = 0; i < tokenizer.size(); i++) { - ordering.push_back(atoi(tokenizer[i].c_str())); + ordering.push_back(atoi(tokenizer[i].data())); } } vespalib::StringTokenizer tokenizer(nodeList, ","); for (uint32_t i = 0; i < tokenizer.size(); i++) { info.addNode(BucketCopy(0, - atoi(tokenizer[i].c_str()), + atoi(tokenizer[i].data()), api::BucketInfo(1,1,1)), ordering); } diff --git a/storage/src/tests/distributor/bucketdbupdatertest.cpp b/storage/src/tests/distributor/bucketdbupdatertest.cpp index 559afffc795..56f88b7f98f 100644 --- a/storage/src/tests/distributor/bucketdbupdatertest.cpp +++ b/storage/src/tests/distributor/bucketdbupdatertest.cpp @@ -1800,7 +1800,7 @@ parseInputData(const std::string& data, for (uint32_t i = 0; i < tokenizer.size(); i++) { vespalib::StringTokenizer tok2(tokenizer[i], ":"); - uint16_t node = atoi(tok2[0].c_str()); + uint16_t node = atoi(tok2[0].data()); state.setNodeReplied(node); auto &pendingTransition = state.getPendingBucketSpaceDbTransition(makeBucketSpace()); @@ -1811,19 +1811,19 @@ parseInputData(const std::string& data, vespalib::StringTokenizer tok4(tok3[j], "/"); pendingTransition.addNodeInfo( - document::BucketId(16, atoi(tok4[0].c_str())), + document::BucketId(16, atoi(tok4[0].data())), BucketCopy( timestamp, node, api::BucketInfo( - atoi(tok4[1].c_str()), - atoi(tok4[2].c_str()), - atoi(tok4[3].c_str()), - atoi(tok4[2].c_str()), - atoi(tok4[3].c_str())))); + atoi(tok4[1].data()), + atoi(tok4[2].data()), + atoi(tok4[3].data()), + atoi(tok4[2].data()), + atoi(tok4[3].data())))); } else { pendingTransition.addNodeInfo( - document::BucketId(16, atoi(tok3[j].c_str())), + document::BucketId(16, atoi(tok3[j].data())), BucketCopy(timestamp, node, api::BucketInfo(3, 3, 3, 3, 3))); diff --git a/storage/src/tests/distributor/distributortest.cpp b/storage/src/tests/distributor/distributortest.cpp index ce20546dd44..46c756001d9 100644 --- a/storage/src/tests/distributor/distributortest.cpp +++ b/storage/src/tests/distributor/distributortest.cpp @@ -176,11 +176,11 @@ private: trusted = true; } - uint16_t node = atoi(tokenizer2[0].c_str()); + uint16_t node = atoi(tokenizer2[0].data()); if (tokenizer2[1] == "r") { removedNodes.push_back(node); } else { - uint32_t checksum = atoi(tokenizer2[1].c_str()); + uint32_t checksum = atoi(tokenizer2[1].data()); changedNodes.push_back( BucketCopy( i + 1, diff --git a/storage/src/tests/distributor/distributortestutil.cpp b/storage/src/tests/distributor/distributortestutil.cpp index e43161946fb..d3496d0c9f6 100644 --- a/storage/src/tests/distributor/distributortestutil.cpp +++ b/storage/src/tests/distributor/distributortestutil.cpp @@ -187,16 +187,16 @@ void DistributorTestUtil::addNodesToBucketDB(const document::Bucket& bucket, con vespalib::StringTokenizer tok2(tokenizer[i], "="); vespalib::StringTokenizer tok3(tok2[1], "/"); - api::BucketInfo info(atoi(tok3[0].c_str()), - atoi(tok3.size() > 1 ? tok3[1].c_str() : tok3[0].c_str()), - atoi(tok3.size() > 2 ? tok3[2].c_str() : tok3[0].c_str())); + api::BucketInfo info(atoi(tok3[0].data()), + atoi(tok3.size() > 1 ? tok3[1].data() : tok3[0].data()), + atoi(tok3.size() > 2 ? tok3[2].data() : tok3[0].data())); size_t flagsIdx = 3; // Meta info override? For simplicity, require both meta count and size if (tok3.size() > 4 && (!tok3[3].empty() && isdigit(tok3[3][0]))) { - info.setMetaCount(atoi(tok3[3].c_str())); - info.setUsedFileSize(atoi(tok3[4].c_str())); + info.setMetaCount(atoi(tok3[3].data())); + info.setUsedFileSize(atoi(tok3[4].data())); flagsIdx = 5; } @@ -211,7 +211,7 @@ void DistributorTestUtil::addNodesToBucketDB(const document::Bucket& bucket, con info.setReady(false); } - uint16_t idx = atoi(tok2[0].c_str()); + uint16_t idx = atoi(tok2[0].data()); BucketCopy node( 0, idx, diff --git a/storage/src/tests/distributor/putoperationtest.cpp b/storage/src/tests/distributor/putoperationtest.cpp index b43d3cf64ad..5551d0a5010 100644 --- a/storage/src/tests/distributor/putoperationtest.cpp +++ b/storage/src/tests/distributor/putoperationtest.cpp @@ -572,8 +572,8 @@ parseBucketInfoString(const std::string& nodeList) { BucketInfo entry; for (uint32_t i = 0; i < tokenizer.size(); i++) { vespalib::StringTokenizer tokenizer2(tokenizer[i], "-"); - int node = atoi(tokenizer2[0].c_str()); - int size = atoi(tokenizer2[1].c_str()); + int node = atoi(tokenizer2[0].data()); + int size = atoi(tokenizer2[1].data()); bool trusted = (tokenizer2[2] == "true"); entry.addNode(BucketCopy(0, diff --git a/storage/src/tests/storageserver/fnet_listener_test.cpp b/storage/src/tests/storageserver/fnet_listener_test.cpp index cc9c424ac28..84051041d25 100644 --- a/storage/src/tests/storageserver/fnet_listener_test.cpp +++ b/storage/src/tests/storageserver/fnet_listener_test.cpp @@ -135,7 +135,7 @@ vespalib::string make_compressable_state_string() { ss << " ." << i << ".s:d"; } return vespalib::make_string("version:123 distributor:100%s storage:100%s", - ss.str().c_str(), ss.str().c_str()); + ss.str().data(), ss.str().data()); } } diff --git a/storage/src/vespa/storage/common/hostreporter/kernelmetrictool.cpp b/storage/src/vespa/storage/common/hostreporter/kernelmetrictool.cpp index 0ff178c3f0f..c8d73737d7c 100644 --- a/storage/src/vespa/storage/common/hostreporter/kernelmetrictool.cpp +++ b/storage/src/vespa/storage/common/hostreporter/kernelmetrictool.cpp @@ -65,8 +65,9 @@ uint32_t getTokenCount(const vespalib::string& line) { uint64_t toLong(const vespalib::stringref& s, int base) { char* endptr; - uint64_t result(strtoull(s.c_str(), &endptr, base)); - if ((s.c_str() + s.size()) != endptr) { + // FIXME C++17 range-safe from_chars() instead of strtoull() + uint64_t result(strtoull(s.data(), &endptr, base)); + if ((s.data() + s.size()) != endptr) { throw vespalib::IllegalArgumentException("Parsing '" + s + "' as a long."); } return result; diff --git a/storage/src/vespa/storage/frameworkimpl/thread/deadlockdetector.cpp b/storage/src/vespa/storage/frameworkimpl/thread/deadlockdetector.cpp index 7c6a708fd8b..e1b7d9c52ea 100644 --- a/storage/src/vespa/storage/frameworkimpl/thread/deadlockdetector.cpp +++ b/storage/src/vespa/storage/frameworkimpl/thread/deadlockdetector.cpp @@ -169,7 +169,7 @@ namespace { } else if (state != DeadLockDetector::OK) { vespalib::asciistream ost; ost << "Thread " << id << " has registered tick again.\n"; - LOGBP(info, "%s", ost.str().c_str()); + LOGBP(info, "%s", ost.str().data()); state = DeadLockDetector::OK; } } @@ -200,7 +200,7 @@ DeadLockDetector::handleDeadlock(const framework::MilliSecTime& currentTime, if (warnOnly) { if (_enableWarning) { LOGBT(warning, "deadlockw-" + id, "%s", - error.str().c_str()); + error.str().data()); if (_reportedBucketDBLocksAtState != WARNED) { _reportedBucketDBLocksAtState = WARNED; LOG(info, "Locks in bucket database at deadlock time:" @@ -212,7 +212,7 @@ DeadLockDetector::handleDeadlock(const framework::MilliSecTime& currentTime, } else { if (_enableShutdown || _enableWarning) { LOGBT(error, "deadlock-" + id, "%s", - error.str().c_str()); + error.str().data()); } } if (!_enableShutdown) return; diff --git a/storage/src/vespa/storage/persistence/filestorage/filestormanager.cpp b/storage/src/vespa/storage/persistence/filestorage/filestormanager.cpp index 9d4d7223411..961af1532a1 100644 --- a/storage/src/vespa/storage/persistence/filestorage/filestormanager.cpp +++ b/storage/src/vespa/storage/persistence/filestorage/filestormanager.cpp @@ -432,7 +432,7 @@ FileStorManager::onDeleteBucket(const shared_ptr<api::DeleteBucketCommand>& cmd) << ", but storage bucket database contains " << entry->getBucketInfo().toString(); - LOG(debug, "Rejecting bucket delete: %s", ost.str().c_str()); + LOG(debug, "Rejecting bucket delete: %s", ost.str().data()); std::shared_ptr<api::StorageReply> reply = cmd->makeReply(); static_cast<api::DeleteBucketReply&>(*reply).setBucketInfo(entry->getBucketInfo()); reply->setResult(api::ReturnCode(api::ReturnCode::REJECTED, ost.str())); diff --git a/storage/src/vespa/storage/storageserver/mergethrottler.cpp b/storage/src/vespa/storage/storageserver/mergethrottler.cpp index 370f1c85241..22af1a73633 100644 --- a/storage/src/vespa/storage/storageserver/mergethrottler.cpp +++ b/storage/src/vespa/storage/storageserver/mergethrottler.cpp @@ -787,7 +787,7 @@ MergeThrottler::validateNewMerge( oss << mergeCmd.toString() << " sent to node " << _component.getIndex() << ", which is not in its forwarding chain"; - LOG(error, "%s", oss.str().c_str()); + LOG(error, "%s", oss.str().data()); } else if (mergeCmd.getChain().size() >= nodeSeq.getSortedNodes().size()) { // Chain is full but we haven't seen the merge! This means // the node has probably gone down with a merge it previously @@ -795,12 +795,12 @@ MergeThrottler::validateNewMerge( oss << mergeCmd.toString() << " is not in node's internal state, but has a " << "full chain, meaning it cannot be forwarded."; - LOG(debug, "%s", oss.str().c_str()); + LOG(debug, "%s", oss.str().data()); } else if (nodeSeq.chainContainsIndex(nodeSeq.getThisNodeIndex())) { oss << mergeCmd.toString() << " is not in node's internal state, but contains " << "this node in its non-full chain. This should not happen!"; - LOG(error, "%s", oss.str().c_str()); + LOG(error, "%s", oss.str().data()); } else { valid = true; } @@ -1117,7 +1117,7 @@ MergeThrottler::makeAbortReply(api::StorageCommand& cmd, vespalib::stringref reason) const { LOG(debug, "Aborting message %s with reason '%s'", - cmd.toString().c_str(), reason.c_str()); + cmd.toString().c_str(), reason.data()); std::unique_ptr<api::StorageReply> reply(cmd.makeReply()); reply->setResult(api::ReturnCode(api::ReturnCode::ABORTED, reason)); return std::shared_ptr<api::StorageMessage>(reply.release()); diff --git a/storage/src/vespa/storage/storageserver/service_layer_error_listener.cpp b/storage/src/vespa/storage/storageserver/service_layer_error_listener.cpp index 41177fe46b8..e26549a3b37 100644 --- a/storage/src/vespa/storage/storageserver/service_layer_error_listener.cpp +++ b/storage/src/vespa/storage/storageserver/service_layer_error_listener.cpp @@ -15,21 +15,21 @@ void ServiceLayerErrorListener::on_fatal_error(vespalib::stringref message) { LOG(info, "Received FATAL_ERROR from persistence provider, " "shutting down node: %s", - message.c_str()); + vespalib::string(message).c_str()); _component.requestShutdown(message); // Thread safe } else { LOG(debug, "Received FATAL_ERROR from persistence provider: %s. " "Node has already been instructed to shut down so " "not doing anything now.", - message.c_str()); + vespalib::string(message).c_str()); } } void ServiceLayerErrorListener::on_resource_exhaustion_error(vespalib::stringref message) { LOG(debug, "SPI reports resource exhaustion ('%s'). " "Applying back-pressure to merge throttler", - message.c_str()); + vespalib::string(message).c_str()); _merge_throttler.apply_timed_backpressure(); // Thread safe } diff --git a/storage/src/vespa/storage/storageserver/statemanager.cpp b/storage/src/vespa/storage/storageserver/statemanager.cpp index d6ca8c266d3..77d9299169f 100644 --- a/storage/src/vespa/storage/storageserver/statemanager.cpp +++ b/storage/src/vespa/storage/storageserver/statemanager.cpp @@ -375,7 +375,7 @@ considerInsertDerivedTransition(const lib::State ¤tBaseline, ((currentDerived != currentBaseline) || (newDerived != newBaseline))); if (considerDerivedTransition && (transitions.find(bucketSpace) == transitions.end())) { transitions[bucketSpace] = vespalib::make_string("%s space: '%s' to '%s'", - document::FixedBucketSpaces::to_string(bucketSpace).c_str(), + document::FixedBucketSpaces::to_string(bucketSpace).data(), currentDerived.getName().c_str(), newDerived.getName().c_str()); } diff --git a/storage/src/vespa/storage/visiting/visitorthread.cpp b/storage/src/vespa/storage/visiting/visitorthread.cpp index b12a1eb6e7f..6bf28b08540 100644 --- a/storage/src/vespa/storage/visiting/visitorthread.cpp +++ b/storage/src/vespa/storage/visiting/visitorthread.cpp @@ -253,7 +253,7 @@ VisitorThread::run(framework::ThreadHandle& thread) } catch (std::exception& e) { vespalib::asciistream ost; ost << "Failed to handle visitor message:" << e.what(); - LOG(warning, "Failed handling visitor message: %s", ost.str().c_str()); + LOG(warning, "Failed handling visitor message: %s", ost.str().data()); result = ReturnCode(ReturnCode::INTERNAL_FAILURE, ost.str()); if (entry._message.get() && entry._message->getType() == api::MessageType::VISITOR_CREATE) { _messageSender.closed(entry._visitorId); @@ -466,7 +466,7 @@ VisitorThread::onCreateVisitor( if (visitor.get() == 0) { result = ReturnCode(ReturnCode::ILLEGAL_PARAMETERS, errors.str()); LOG(warning, "CreateVisitor(%s): Failed to create visitor: %s", - cmd->getInstanceId().c_str(), errors.str().c_str()); + cmd->getInstanceId().c_str(), errors.str().data()); break; } // Set visitor parameters @@ -510,7 +510,7 @@ VisitorThread::onCreateVisitor( << cmd->getDocumentSelection() << "': " << e.getMessage(); result = ReturnCode(ReturnCode::ILLEGAL_PARAMETERS, ost.str()); LOG(warning, "CreateVisitor(%s): %s", - cmd->getInstanceId().c_str(), ost.str().c_str()); + cmd->getInstanceId().c_str(), ost.str().data()); break; } catch (document::select::ParsingFailedException& e) { vespalib::asciistream ost; @@ -518,7 +518,7 @@ VisitorThread::onCreateVisitor( << cmd->getDocumentSelection() << "': " << e.getMessage(); result = ReturnCode(ReturnCode::ILLEGAL_PARAMETERS, ost.str()); LOG(warning, "CreateVisitor(%s): %s", - cmd->getInstanceId().c_str(), ost.str().c_str()); + cmd->getInstanceId().c_str(), ost.str().data()); break; } LOG(debug, "CreateVisitor(%s): Successfully created visitor", diff --git a/storageframework/src/vespa/storageframework/defaultimplementation/component/componentregisterimpl.cpp b/storageframework/src/vespa/storageframework/defaultimplementation/component/componentregisterimpl.cpp index a5611451ee8..ae448664f14 100644 --- a/storageframework/src/vespa/storageframework/defaultimplementation/component/componentregisterimpl.cpp +++ b/storageframework/src/vespa/storageframework/defaultimplementation/component/componentregisterimpl.cpp @@ -132,7 +132,7 @@ namespace { MetricHookWrapper(vespalib::stringref name, MetricUpdateHook& hook) - : metrics::UpdateHook(name.c_str()), + : metrics::UpdateHook(name.data()), // Expected to point to static name _hook(hook) { } diff --git a/vdslib/src/tests/distribution/distributiontest.cpp b/vdslib/src/tests/distribution/distributiontest.cpp index 3090910d2bb..7af48c1904b 100644 --- a/vdslib/src/tests/distribution/distributiontest.cpp +++ b/vdslib/src/tests/distribution/distributiontest.cpp @@ -191,7 +191,7 @@ namespace { try{ std::vector<uint16_t> nvect; distribution.getIdealNodes(nodeType, state, results[i].bucket, - nvect, upStates.c_str(), redundancy); + nvect, upStates.data(), redundancy); IdealNodeList nodes; for (uint32_t j=0, m=nvect.size(); j<m; ++j) { nodes.push_back(Node(nodeType, nvect[j])); diff --git a/vdslib/src/tests/distribution/grouptest.cpp b/vdslib/src/tests/distribution/grouptest.cpp index c108a1e8a38..71d8b8bac0c 100644 --- a/vdslib/src/tests/distribution/grouptest.cpp +++ b/vdslib/src/tests/distribution/grouptest.cpp @@ -30,7 +30,7 @@ namespace { vespalib::StringTokenizer st(nodelist, ","); std::vector<uint16_t> nodes(st.size()); for (uint32_t i=0; i<st.size(); ++i) { - nodes[i] = atoi(st[i].c_str()); + nodes[i] = atoi(st[i].data()); } group->setNodes(nodes); return group; diff --git a/vdslib/src/vespa/vdslib/container/parameters.h b/vdslib/src/vespa/vdslib/container/parameters.h index 4572b2f6f1c..ab65932496a 100644 --- a/vdslib/src/vespa/vdslib/container/parameters.h +++ b/vdslib/src/vespa/vdslib/container/parameters.h @@ -68,7 +68,7 @@ public: ParametersMap::const_iterator begin() const { return _parameters.begin(); } ParametersMap::const_iterator end() const { return _parameters.end(); } /// Convenience from earlier use. - void set(const KeyT & id, const vespalib::stringref & value) { _parameters[id] = Value(value.c_str(), value.size()); } + void set(const KeyT & id, const vespalib::stringref & value) { _parameters[id] = Value(value.data(), value.size()); } vespalib::stringref get(const KeyT & id, const vespalib::stringref & def = "") const; /** * Set the value identified by the id given. This requires the type to be diff --git a/vdslib/src/vespa/vdslib/distribution/redundancygroupdistribution.cpp b/vdslib/src/vespa/vdslib/distribution/redundancygroupdistribution.cpp index f620dc15928..99974225e9e 100644 --- a/vdslib/src/vespa/vdslib/distribution/redundancygroupdistribution.cpp +++ b/vdslib/src/vespa/vdslib/distribution/redundancygroupdistribution.cpp @@ -30,7 +30,7 @@ namespace { firstAsterisk = i; continue; } - uint32_t number = atoi(st[i].c_str()); + uint32_t number = atoi(vespalib::string(st[i]).c_str()); if (number <= 0 || number >= 256) { throw vespalib::IllegalArgumentException( "Illegal distribution spec \"" + serialized + "\". " @@ -48,7 +48,7 @@ namespace { } } - std::vector<uint16_t> parse(vespalib::stringref& serialized) { + std::vector<uint16_t> parse(vespalib::stringref serialized) { std::vector<uint16_t> result; if (serialized == "") return result; vespalib::StringTokenizer st(serialized, "|"); diff --git a/vdslib/src/vespa/vdslib/state/clusterstate.cpp b/vdslib/src/vespa/vdslib/state/clusterstate.cpp index fbc9943e22d..e50b18a5a82 100644 --- a/vdslib/src/vespa/vdslib/state/clusterstate.cpp +++ b/vdslib/src/vespa/vdslib/state/clusterstate.cpp @@ -88,7 +88,7 @@ ClusterState::ClusterState(const vespalib::string& serialized) if (key.empty() || ! parse(key, value, nodeData) ) { LOG(debug, "Unknown key %s in systemstate. Ignoring it, assuming it's " "a new feature from a newer version than ourself: %s", - key.c_str(), serialized.c_str()); + vespalib::string(key).c_str(), serialized.c_str()); } } nodeData.addTo(_nodeStates, _nodeCount); @@ -106,13 +106,13 @@ ClusterState::parse(vespalib::stringref key, vespalib::stringref value, NodeData break; case 'b': if (key == "bits") { - _distributionBits = atoi(value.c_str()); + _distributionBits = atoi(value.data()); return true; } break; case 'v': if (key == "version") { - _version = atoi(value.c_str()); + _version = atoi(value.data()); return true; } break; @@ -145,7 +145,7 @@ ClusterState::parseSorD(vespalib::stringref key, vespalib::stringref value, Node if (nodeType == 0) return false; if (dot == vespalib::string::npos) { // Entry that set node counts uint16_t nodeCount = 0; - nodeCount = atoi(value.c_str()); + nodeCount = atoi(value.data()); if (nodeCount > _nodeCount[*nodeType] ) { _nodeCount[*nodeType] = nodeCount; @@ -155,9 +155,9 @@ ClusterState::parseSorD(vespalib::stringref key, vespalib::stringref value, Node vespalib::string::size_type dot2 = key.find('.', dot + 1); Node node; if (dot2 == vespalib::string::npos) { - node = Node(*nodeType, atoi(key.substr(dot + 1).c_str())); + node = Node(*nodeType, atoi(key.substr(dot + 1).data())); } else { - node = Node(*nodeType, atoi(key.substr(dot + 1, dot2 - dot - 1).c_str())); + node = Node(*nodeType, atoi(key.substr(dot + 1, dot2 - dot - 1).data())); } if (node.getIndex() >= _nodeCount[*nodeType]) { diff --git a/vdslib/src/vespa/vdslib/state/clusterstate.h b/vdslib/src/vespa/vdslib/state/clusterstate.h index 9e8dd0f292a..26c6f1b95ef 100644 --- a/vdslib/src/vespa/vdslib/state/clusterstate.h +++ b/vdslib/src/vespa/vdslib/state/clusterstate.h @@ -72,7 +72,9 @@ public: const std::string& indent = "") const; private: + // Preconditions: `key` and `value` MUST point into null-terminated strings. bool parse(vespalib::stringref key, vespalib::stringref value, NodeData & nodeData); + // Preconditions: `key` and `value` MUST point into null-terminated strings. bool parseSorD(vespalib::stringref key, vespalib::stringref value, NodeData & nodeData); void removeExtraElements(); void printStateGroupwise(std::ostream& out, const Group&, bool verbose, diff --git a/vdslib/src/vespa/vdslib/state/diskstate.cpp b/vdslib/src/vespa/vdslib/state/diskstate.cpp index bcc380e0d75..c963dacff82 100644 --- a/vdslib/src/vespa/vdslib/state/diskstate.cpp +++ b/vdslib/src/vespa/vdslib/state/diskstate.cpp @@ -73,7 +73,7 @@ DiskState::DiskState(const vespalib::stringref & serialized) } LOG(debug, "Unknown key %s in diskstate. Ignoring it, assuming it's a " "new feature from a newer version than ourself: %s", - key.c_str(), serialized.c_str()); + key.c_str(), vespalib::string(serialized).c_str()); } } diff --git a/vdslib/src/vespa/vdslib/state/nodestate.cpp b/vdslib/src/vespa/vdslib/state/nodestate.cpp index ff6c8f31c89..d59686dcb1c 100644 --- a/vdslib/src/vespa/vdslib/state/nodestate.cpp +++ b/vdslib/src/vespa/vdslib/state/nodestate.cpp @@ -229,7 +229,7 @@ NodeState::NodeState(const vespalib::stringref & serialized, const NodeType* typ } LOG(debug, "Unknown key %s in nodestate. Ignoring it, assuming it's a " "new feature from a newer version than ourself: %s", - key.c_str(), serialized.c_str()); + key.c_str(), vespalib::string(serialized).c_str()); } diskData.addTo(_diskStates); updateAnyDiskDownFlag(); diff --git a/vespalib/src/tests/stllike/string_test.cpp b/vespalib/src/tests/stllike/string_test.cpp index 2973ffd1ef1..96c095667ee 100644 --- a/vespalib/src/tests/stllike/string_test.cpp +++ b/vespalib/src/tests/stllike/string_test.cpp @@ -265,10 +265,10 @@ TEST("testString") { // Test std::string conversion of empty string stringref sref; std::string stdString(sref); - EXPECT_TRUE(strcmp("", sref.c_str()) == 0); + EXPECT_TRUE(strcmp("", sref.data()) == 0); stdString = "abc"; stringref sref2(stdString); - EXPECT_TRUE(stdString.c_str() == sref2.c_str()); + EXPECT_TRUE(stdString.c_str() == sref2.data()); EXPECT_TRUE(stdString == sref2); EXPECT_TRUE(sref2 == stdString); { diff --git a/vespalib/src/vespa/vespalib/component/version.cpp b/vespalib/src/vespa/vespalib/component/version.cpp index af38a675de8..3aa8e134e36 100644 --- a/vespalib/src/vespa/vespalib/component/version.cpp +++ b/vespalib/src/vespa/vespalib/component/version.cpp @@ -62,10 +62,11 @@ Version::verifySanity() } } +// Precondition: input.empty() == false static int parseInteger(const stringref & input) __attribute__((noinline)); static int parseInteger(const stringref & input) { - const char *s = input.c_str(); + const char *s = input.data(); unsigned char firstDigit = s[0]; if (!isdigit(firstDigit)) throw IllegalArgumentException("integer must start with a digit"); diff --git a/vespalib/src/vespa/vespalib/io/fileutil.cpp b/vespalib/src/vespa/vespalib/io/fileutil.cpp index 389218cea35..e360c84f569 100644 --- a/vespalib/src/vespa/vespalib/io/fileutil.cpp +++ b/vespalib/src/vespa/vespalib/io/fileutil.cpp @@ -19,7 +19,7 @@ namespace vespalib { namespace { FileInfo::UP - processStat(struct stat& filestats, bool result, const stringref & path) { + processStat(struct stat& filestats, bool result, stringref path) { FileInfo::UP resval; if (result) { resval.reset(new FileInfo); @@ -36,7 +36,7 @@ namespace { } LOG(debug, "stat(%s): Existed? %s, Plain file? %s, Directory? %s, " "Size: %" PRIu64, - path.c_str(), + string(path).c_str(), resval.get() ? "true" : "false", resval.get() && resval->_plainfile ? "true" : "false", resval.get() && resval->_directory ? "true" : "false", @@ -69,7 +69,7 @@ operator<<(std::ostream& out, const FileInfo& info) return out; } -File::File(const stringref & filename) +File::File(stringref filename) : _fd(-1), _flags(0), _filename(filename), @@ -79,7 +79,7 @@ File::File(const stringref & filename) { } -File::File(int fileDescriptor, const stringref & filename) +File::File(int fileDescriptor, stringref filename) : _fd(fileDescriptor), _flags(0), _filename(filename), @@ -128,7 +128,7 @@ File::operator=(File& f) } void -File::setFilename(const stringref & filename) +File::setFilename(stringref filename) { if (_filename == filename) return; if (_close && _fd != -1) close(); @@ -139,14 +139,14 @@ File::setFilename(const stringref & filename) } namespace { - int openAndCreateDirsIfMissing(const stringref & filename, int flags, + int openAndCreateDirsIfMissing(const string & filename, int flags, bool createDirsIfMissing) { int fd = ::open(filename.c_str(), flags, 0644); if (fd < 0 && errno == ENOENT && ((flags & O_CREAT) != 0) && createDirsIfMissing) { - string::size_type pos = filename.rfind('/'); + auto pos = filename.rfind('/'); if (pos != string::npos) { string path(filename.substr(0, pos)); mkdir(path); @@ -381,7 +381,7 @@ File::readAll() const } vespalib::string -File::readAll(const vespalib::stringref & path) +File::readAll(vespalib::stringref path) { File file(path); file.open(File::READONLY); @@ -452,14 +452,14 @@ getCurrentDirectory() } bool -mkdir(const stringref & directory, bool recursive) +mkdir(const string & directory, bool recursive) { if (::mkdir(directory.c_str(), 0777) == 0) { LOG(debug, "mkdir(%s): Created directory", directory.c_str()); return true; } if (recursive && errno == ENOENT) { - string::size_type slashpos = directory.rfind('/'); + auto slashpos = directory.rfind('/'); if (slashpos != string::npos) { /* Recursively make superdirs.*/ string superdir = directory.substr(0, slashpos); @@ -499,8 +499,8 @@ mkdir(const stringref & directory, bool recursive) } void -symlink(const stringref & oldPath, - const stringref & newPath) +symlink(const string & oldPath, + const string & newPath) { if (::symlink(oldPath.c_str(), newPath.c_str())) { asciistream ss; @@ -513,7 +513,7 @@ symlink(const stringref & oldPath, } string -readLink(const stringref & path) +readLink(const string & path) { char buf[256]; ssize_t bytes(::readlink(path.c_str(), buf, sizeof(buf))); @@ -528,7 +528,7 @@ readLink(const stringref & path) } void -chdir(const stringref & directory) +chdir(const string & directory) { if (::chdir(directory.c_str()) != 0) { asciistream ost; @@ -537,12 +537,11 @@ chdir(const stringref & directory) throw IoException(ost.str(), IoException::getErrorType(errno), VESPA_STRLOC); } - LOG(debug, "chdir(%s): Working directory changed.", - directory.c_str()); + LOG(debug, "chdir(%s): Working directory changed.", directory.c_str()); } bool -rmdir(const stringref & directory, bool recursive) +rmdir(const string & directory, bool recursive) { string dirname(directory); if (!dirname.empty() && *dirname.rbegin() == '/') { @@ -595,26 +594,26 @@ rmdir(const stringref & directory, bool recursive) } FileInfo::UP -stat(const stringref & path) +stat(const string & path) { struct ::stat filestats; return processStat(filestats, ::stat(path.c_str(), &filestats) == 0, path); } FileInfo::UP -lstat(const stringref & path) +lstat(const string & path) { struct ::stat filestats; return processStat(filestats, ::lstat(path.c_str(), &filestats) == 0, path); } bool -fileExists(const vespalib::stringref & path) { +fileExists(const string & path) { return (stat(path).get() != 0); } bool -unlink(const stringref & filename) +unlink(const string & filename) { if (::unlink(filename.c_str()) != 0) { if (errno == ENOENT) { @@ -631,7 +630,7 @@ unlink(const stringref & filename) } bool -rename(const stringref & frompath, const stringref & topath, +rename(const string & frompath, const string & topath, bool copyDeleteBetweenFilesystems, bool createTargetDirectoryIfMissing) { LOG(spam, "rename(%s, %s): Renaming file%s.", @@ -696,7 +695,7 @@ namespace { } void -copy(const stringref & frompath, const stringref & topath, +copy(const string & frompath, const string & topath, bool createTargetDirectoryIfMissing, bool useDirectIO) { // Get aligned buffer, so it works with direct IO @@ -730,7 +729,7 @@ copy(const stringref & frompath, const stringref & topath, } DirectoryList -listDirectory(const stringref & path) +listDirectory(const string & path) { DIR* dir = ::opendir(path.c_str()); struct dirent* entry; @@ -762,7 +761,7 @@ getAlignedBuffer(size_t size) return MallocAutoPtr(ptr); } -string dirname(const stringref name) +string dirname(stringref name) { size_t found = name.rfind('/'); if (found == string::npos) { @@ -776,7 +775,7 @@ string dirname(const stringref name) namespace { -void addStat(asciistream &os, const stringref name) +void addStat(asciistream &os, const string & name) { struct ::stat filestat; memset(&filestat, '\0', sizeof(filestat)); @@ -801,7 +800,7 @@ void addStat(asciistream &os, const stringref name) } string -getOpenErrorString(const int osError, const stringref filename) +getOpenErrorString(const int osError, stringref filename) { asciistream os; string dirName(dirname(filename)); @@ -809,12 +808,12 @@ getOpenErrorString(const int osError, const stringref filename) getErrorString(osError) << "\") fileStat"; addStat(os, filename); os << " dirStat"; - addStat(os, dirName.c_str()); + addStat(os, dirName); return os.str(); } bool -isDirectory(const vespalib::stringref & path) { +isDirectory(const string & path) { FileInfo::UP info(stat(path)); return (info.get() && info->_directory); } diff --git a/vespalib/src/vespa/vespalib/io/fileutil.h b/vespalib/src/vespa/vespalib/io/fileutil.h index ece37ab0108..187939ed412 100644 --- a/vespalib/src/vespa/vespalib/io/fileutil.h +++ b/vespalib/src/vespa/vespalib/io/fileutil.h @@ -83,10 +83,10 @@ public: enum Flag { READONLY = 1, CREATE = 2, DIRECTIO = 4, TRUNC = 8 }; /** Create a file instance, without opening the file. */ - File(const vespalib::stringref & filename); + File(vespalib::stringref filename); /** Create a file instance of an already open file. */ - File(int fileDescriptor, const vespalib::stringref & filename); + File(int fileDescriptor, vespalib::stringref filename); /** Copying a file instance, moves any open file descriptor. */ File(File& f); @@ -99,7 +99,7 @@ public: * Make this instance point at another file. * Closes the old file it it was open. */ - void setFilename(const vespalib::stringref & filename); + void setFilename(vespalib::stringref filename); const vespalib::string& getFilename() const { return _filename; } @@ -188,7 +188,7 @@ public: * @throw IoException If we failed to read from file. * @return The content of the file. */ - static vespalib::string readAll(const vespalib::stringref & path); + static vespalib::string readAll(vespalib::stringref path); virtual void sync(); virtual bool close(); @@ -273,7 +273,7 @@ extern vespalib::string getCurrentDirectory(); * * @return True if it did not exist, false if it did. */ -extern bool mkdir(const vespalib::stringref & directory, bool recursive = true); +extern bool mkdir(const vespalib::string & directory, bool recursive = true); /** * Change working directory. @@ -281,7 +281,7 @@ extern bool mkdir(const vespalib::stringref & directory, bool recursive = true); * @param directory The directory to change to. * @throw IoException If we failed to change to the new working directory. */ -extern void chdir(const vespalib::stringref & directory); +extern void chdir(const vespalib::string & directory); /** * Remove a directory. @@ -293,7 +293,7 @@ extern void chdir(const vespalib::stringref & directory); * * @return True if directory existed, false if not. */ -extern bool rmdir(const vespalib::stringref & directory, bool recursive = false); +extern bool rmdir(const vespalib::string & directory, bool recursive = false); /** * Stat a file. @@ -302,7 +302,7 @@ extern bool rmdir(const vespalib::stringref & directory, bool recursive = false) * @return A file info object if everything went well, a null pointer if the * file was not found. */ -extern FileInfo::UP stat(const vespalib::stringref & path); +extern FileInfo::UP stat(const vespalib::string & path); /** * Stat a file. Give info on symlink rather than on file pointed to. @@ -311,14 +311,14 @@ extern FileInfo::UP stat(const vespalib::stringref & path); * @return A file info object if everything went well, a null pointer if the * file was not found. */ -extern FileInfo::UP lstat(const vespalib::stringref & path); +extern FileInfo::UP lstat(const vespalib::string & path); /** * Check if a file exists or not. See also pathExists. * * @throw IoException If we failed to stat the file. */ -extern bool fileExists(const vespalib::stringref & path); +extern bool fileExists(const vespalib::string & path); /** * Check if a path exists, i.e. whether it's a symbolic link, regular file, @@ -328,7 +328,7 @@ extern bool fileExists(const vespalib::stringref & path); * This function returns true, while fileExists returns true only if the path * the symbolic link points to exists. */ -extern inline bool pathExists(const vespalib::stringref & path) { +extern inline bool pathExists(const vespalib::string & path) { return (lstat(path).get() != 0); } @@ -336,7 +336,7 @@ extern inline bool pathExists(const vespalib::stringref & path) { * Get the filesize of the given file. Ignoring if it exists or not. * (None-existing files will be reported to have size zero) */ -extern inline off_t getFileSize(const vespalib::stringref & path) { +extern inline off_t getFileSize(const vespalib::string & path) { FileInfo::UP info(stat(path)); return (info.get() == 0 ? 0 : info->_size); } @@ -347,7 +347,7 @@ extern inline off_t getFileSize(const vespalib::stringref & path) { * @return True if it is a plain file, false if it don't exist or isn't. * @throw IoException If we failed to stat the file. */ -extern inline bool isPlainFile(const vespalib::stringref & path) { +extern inline bool isPlainFile(const vespalib::string & path) { FileInfo::UP info(stat(path)); return (info.get() && info->_plainfile); } @@ -358,7 +358,7 @@ extern inline bool isPlainFile(const vespalib::stringref & path) { * @return True if it is a directory, false if it don't exist or isn't. * @throw IoException If we failed to stat the file. */ -extern bool isDirectory(const vespalib::stringref & path); +extern bool isDirectory(const vespalib::string & path); /** * Check whether a path is a symlink. @@ -366,7 +366,7 @@ extern bool isDirectory(const vespalib::stringref & path); * @return True if path exists and is a symbolic link. * @throw IoException If there's an unexpected stat failure. */ -extern inline bool isSymLink(const vespalib::stringref & path) { +extern inline bool isSymLink(const vespalib::string & path) { FileInfo::UP info(lstat(path)); return (info.get() && info->_symlink); } @@ -384,8 +384,8 @@ extern inline bool isSymLink(const vespalib::stringref & path) { * @param newPath Relative link to be created. See above note for semantics. * @throw IoException if we fail to create the symlink. */ -extern void symlink(const vespalib::stringref & oldPath, - const vespalib::stringref & newPath); +extern void symlink(const vespalib::string & oldPath, + const vespalib::string & newPath); /** * Read and return the contents of symbolic link at the given path. @@ -394,7 +394,7 @@ extern void symlink(const vespalib::stringref & oldPath, * @return Contents of symbolic link. * @throw IoException if we cannot read the link. */ -extern vespalib::string readLink(const vespalib::stringref & path); +extern vespalib::string readLink(const vespalib::string & path); /** * Remove the given file. @@ -403,7 +403,7 @@ extern vespalib::string readLink(const vespalib::stringref & path); * @return True if file was removed, false if it did not exist. * @throw IoException If we failed to unlink the file. */ -extern bool unlink(const vespalib::stringref & filename); +extern bool unlink(const vespalib::string & filename); /** * Rename the file at frompath to topath. @@ -421,16 +421,16 @@ extern bool unlink(const vespalib::stringref & filename); * @throw IoException If we failed to rename the file. * @return True if file was renamed, false if frompath did not exist. */ -extern bool rename(const vespalib::stringref & frompath, - const vespalib::stringref & topath, +extern bool rename(const vespalib::string & frompath, + const vespalib::string & topath, bool copyDeleteBetweenFilesystems = true, bool createTargetDirectoryIfMissing = false); /** * Copies a file to a destination using Direct IO. */ -extern void copy(const vespalib::stringref & frompath, - const vespalib::stringref & topath, +extern void copy(const vespalib::string & frompath, + const vespalib::string & topath, bool createTargetDirectoryIfMissing = false, bool useDirectIO = true); @@ -438,11 +438,11 @@ extern void copy(const vespalib::stringref & frompath, * List the contents of the given directory. */ typedef std::vector<vespalib::string> DirectoryList; -extern DirectoryList listDirectory(const vespalib::stringref & path); +extern DirectoryList listDirectory(const vespalib::string & path); extern MallocAutoPtr getAlignedBuffer(size_t size); -string dirname(const stringref name); -string getOpenErrorString(const int osError, const stringref name); +string dirname(stringref name); +string getOpenErrorString(const int osError, stringref name); } // vespalib diff --git a/vespalib/src/vespa/vespalib/objects/nbostream.h b/vespalib/src/vespa/vespalib/objects/nbostream.h index b51fff1b7cc..c3127e06133 100644 --- a/vespalib/src/vespa/vespalib/objects/nbostream.h +++ b/vespalib/src/vespa/vespalib/objects/nbostream.h @@ -71,7 +71,7 @@ public: return *this; } nbostream & operator << (const char * v) { uint32_t sz(strlen(v)); (*this) << sz; write(v, sz); return *this; } - nbostream & operator << (const vespalib::stringref & v) { uint32_t sz(v.size()); (*this) << sz; write(v.c_str(), sz); return *this; } + nbostream & operator << (const vespalib::stringref & v) { uint32_t sz(v.size()); (*this) << sz; write(v.data(), sz); return *this; } nbostream & operator << (const vespalib::string & v) { uint32_t sz(v.size()); (*this) << sz; write(v.c_str(), sz); return *this; } nbostream & operator >> (vespalib::string & v) { uint32_t sz; (*this) >> sz; diff --git a/vespalib/src/vespa/vespalib/stllike/asciistream.cpp b/vespalib/src/vespa/vespalib/stllike/asciistream.cpp index 1be24175ede..7e8570b3d61 100644 --- a/vespalib/src/vespa/vespalib/stllike/asciistream.cpp +++ b/vespalib/src/vespa/vespalib/stllike/asciistream.cpp @@ -520,7 +520,7 @@ void asciistream::write(const void * buf, size_t len) if (_rPos > 0 && _rPos == length()) { clear(); } - if (_rbuf.c_str() != _wbuf.c_str()) { + if (_rbuf.data() != _wbuf.data()) { if (_wbuf.empty()) { _wbuf = _rbuf; // Read only to RW } else { @@ -557,7 +557,7 @@ string asciistream::getline(char delim) asciistream asciistream::createFromFile(const stringref & fileName) { - FastOS_File file(fileName.c_str()); + FastOS_File file(vespalib::string(fileName).c_str()); asciistream is; if (file.OpenReadOnly()) { ssize_t sz = file.getSize(); @@ -578,7 +578,7 @@ asciistream asciistream::createFromFile(const stringref & fileName) asciistream asciistream::createFromDevice(const stringref & fileName) { - FastOS_File file(fileName.c_str()); + FastOS_File file(vespalib::string(fileName).c_str()); asciistream is; if (file.OpenReadOnly()) { char buf[8192]; diff --git a/vespalib/src/vespa/vespalib/stllike/asciistream.h b/vespalib/src/vespa/vespalib/stllike/asciistream.h index 1e2b4bc1823..9dd73706d0a 100644 --- a/vespalib/src/vespa/vespalib/stllike/asciistream.h +++ b/vespalib/src/vespa/vespalib/stllike/asciistream.h @@ -42,9 +42,9 @@ public: asciistream & operator << (char v) { doFill(1); write(&v, 1); return *this; } asciistream & operator << (unsigned char v) { doFill(1); write(&v, 1); return *this; } asciistream & operator << (const char * v) { if (v != nullptr) { size_t n(strlen(v)); doFill(n); write(v, n); } return *this; } - asciistream & operator << (const string & v) { doFill(v.size()); write(v.c_str(), v.size()); return *this; } - asciistream & operator << (const stringref & v) { doFill(v.size()); write(v.c_str(), v.size()); return *this; } - asciistream & operator << (const std::string & v) { doFill(v.size()); write(v.c_str(), v.size()); return *this; } + asciistream & operator << (const string & v) { doFill(v.size()); write(v.data(), v.size()); return *this; } + asciistream & operator << (const stringref & v) { doFill(v.size()); write(v.data(), v.size()); return *this; } + asciistream & operator << (const std::string & v) { doFill(v.size()); write(v.data(), v.size()); return *this; } asciistream & operator << (int16_t v) { return *this << static_cast<int64_t>(v); } asciistream & operator << (uint16_t v) { return *this << static_cast<uint64_t>(v); } asciistream & operator << (int32_t v) { return *this << static_cast<int64_t>(v); } @@ -74,7 +74,7 @@ public: asciistream & operator >> (float & v); asciistream & operator >> (double & v); stringref str() const { return stringref(c_str(), size()); } - const char * c_str() const { return _rbuf.c_str() + _rPos; } + const char * c_str() const { return _rbuf.data() + _rPos; } size_t size() const { return length() - _rPos; } bool empty() const { return size() == 0; } bool eof() const { return empty(); } diff --git a/vespalib/src/vespa/vespalib/stllike/hash_fun.h b/vespalib/src/vespa/vespalib/stllike/hash_fun.h index 8b14d5ce67c..7d7be666136 100644 --- a/vespalib/src/vespa/vespalib/stllike/hash_fun.h +++ b/vespalib/src/vespa/vespalib/stllike/hash_fun.h @@ -67,7 +67,7 @@ template<> struct hash<const char *> { }; template<> struct hash<vespalib::stringref> { - size_t operator() (const vespalib::stringref & arg) const { return hashValue(arg.c_str(), arg.size()); } + size_t operator() (const vespalib::stringref & arg) const { return hashValue(arg.data(), arg.size()); } }; template<> struct hash<vespalib::string> { diff --git a/vespalib/src/vespa/vespalib/stllike/string.cpp b/vespalib/src/vespa/vespalib/stllike/string.cpp index 081d45936c7..47d424e93aa 100644 --- a/vespalib/src/vespa/vespalib/stllike/string.cpp +++ b/vespalib/src/vespa/vespalib/stllike/string.cpp @@ -47,7 +47,7 @@ stringref::find(const stringref & s, size_type start) const { std::ostream & operator << (std::ostream & os, const stringref & v) { - return os.write(v.c_str(), v.size()); + return os.write(v.data(), v.size()); } template<uint32_t SS> diff --git a/vespalib/src/vespa/vespalib/stllike/string.h b/vespalib/src/vespa/vespalib/stllike/string.h index 3db36f5fd41..98ed0929a9b 100644 --- a/vespalib/src/vespa/vespalib/stllike/string.h +++ b/vespalib/src/vespa/vespalib/stllike/string.h @@ -31,24 +31,21 @@ public: * return a pointer to the data held, or NULL. * Note that the data may not be zero terminated, and a default * constructed stringref will give a NULL pointer back. If you - * need to make sure c_str() gives a valid zero-terminated string + * need to make sure data() gives a valid zero-terminated string * you should make a vespalib::string from the stringref. **/ - const char * c_str() const { return _s; } - - /** return a pointer to the data held, or NULL. See c_str(). */ const char * data() const { return _s; } size_type size() const { return _sz; } size_type length() const { return size(); } bool empty() const { return _sz == 0; } - const char * begin() const { return c_str(); } + const char * begin() const { return data(); } const char * end() const { return begin() + size(); } const char * rbegin() const { return end() - 1; } const char * rend() const { return begin() - 1; } stringref substr(size_type start, size_type sz=npos) const { if (start < size()) { - return stringref(c_str() + start, std::min(sz, size()-start)); + return stringref(data() + start, std::min(sz, size()-start)); } return stringref(); } @@ -119,7 +116,7 @@ public: * was found, or npos if the substring could not be located */ size_type rfind(const char * s, size_type e=npos) const; - int compare(const stringref & s) const { return compare(s.c_str(), s.size()); } + int compare(const stringref & s) const { return compare(s.data(), s.size()); } int compare(const char *s, size_type sz) const { int diff(memcmp(_s, s, std::min(sz, size()))); return (diff != 0) ? diff : (size() - sz); @@ -127,23 +124,23 @@ public: const char & operator [] (size_t i) const { return _s[i]; } operator std::string () const { return std::string(_s, _sz); } bool operator < (const char * s) const { return compare(s, strlen(s)) < 0; } - bool operator < (const std::string & s) const { return compare(s.c_str(), s.size()) < 0; } - bool operator < (const stringref & s) const { return compare(s.c_str(), s.size()) < 0; } + bool operator < (const std::string & s) const { return compare(s.data(), s.size()) < 0; } + bool operator < (const stringref & s) const { return compare(s.data(), s.size()) < 0; } bool operator <= (const char * s) const { return compare(s, strlen(s)) <= 0; } - bool operator <= (const std::string & s) const { return compare(s.c_str(), s.size()) <= 0; } - bool operator <= (const stringref & s) const { return compare(s.c_str(), s.size()) <= 0; } + bool operator <= (const std::string & s) const { return compare(s.data(), s.size()) <= 0; } + bool operator <= (const stringref & s) const { return compare(s.data(), s.size()) <= 0; } bool operator != (const char * s) const { return compare(s, strlen(s)) != 0; } - bool operator != (const std::string & s) const { return compare(s.c_str(), s.size()) != 0; } - bool operator != (const stringref & s) const { return compare(s.c_str(), s.size()) != 0; } + bool operator != (const std::string & s) const { return compare(s.data(), s.size()) != 0; } + bool operator != (const stringref & s) const { return compare(s.data(), s.size()) != 0; } bool operator == (const char * s) const { return compare(s, strlen(s)) == 0; } - bool operator == (const std::string & s) const { return compare(s.c_str(), s.size()) == 0; } - bool operator == (const stringref & s) const { return compare(s.c_str(), s.size()) == 0; } + bool operator == (const std::string & s) const { return compare(s.data(), s.size()) == 0; } + bool operator == (const stringref & s) const { return compare(s.data(), s.size()) == 0; } bool operator >= (const char * s) const { return compare(s, strlen(s)) >= 0; } - bool operator >= (const std::string & s) const { return compare(s.c_str(), s.size()) >= 0; } - bool operator >= (const stringref & s) const { return compare(s.c_str(), s.size()) >= 0; } + bool operator >= (const std::string & s) const { return compare(s.data(), s.size()) >= 0; } + bool operator >= (const stringref & s) const { return compare(s.data(), s.size()) >= 0; } bool operator > (const char * s) const { return compare(s, strlen(s)) > 0; } - bool operator > (const std::string & s) const { return compare(s.c_str(), s.size()) > 0; } - bool operator > (const stringref & s) const { return compare(s.c_str(), s.size()) > 0; } + bool operator > (const std::string & s) const { return compare(s.data(), s.size()) > 0; } + bool operator > (const stringref & s) const { return compare(s.data(), s.size()) > 0; } private: const char *_s; size_type _sz; @@ -178,13 +175,13 @@ public: small_string() : _buf(_stack), _sz(0), _bufferSize(StackSize) { _stack[0] = '\0'; } small_string(const char * s) : _buf(_stack), _sz(s ? strlen(s) : 0) { init(s); } small_string(const void * s, size_type sz) : _buf(_stack), _sz(sz) { init(s); } - small_string(const stringref & s) : _buf(_stack), _sz(s.size()) { init(s.c_str()); } - small_string(const std::string & s) : _buf(_stack), _sz(s.size()) { init(s.c_str()); } - small_string(const small_string & rhs) noexcept : _buf(_stack), _sz(rhs.size()) { init(rhs.c_str()); } + small_string(const stringref & s) : _buf(_stack), _sz(s.size()) { init(s.data()); } + small_string(const std::string & s) : _buf(_stack), _sz(s.size()) { init(s.data()); } + small_string(const small_string & rhs) noexcept : _buf(_stack), _sz(rhs.size()) { init(rhs.data()); } small_string(const small_string & rhs, size_type pos, size_type sz=npos) noexcept : _buf(_stack), _sz(std::min(sz, rhs.size()-pos)) { - init(rhs.c_str()+pos); + init(rhs.data()+pos); } small_string(size_type sz, char c) : _buf(_stack), _sz(0), _bufferSize(StackSize) @@ -204,10 +201,10 @@ public: } } small_string& operator= (const small_string &rhs) { - return assign(rhs.c_str(), rhs.size()); + return assign(rhs.data(), rhs.size()); } small_string & operator= (const stringref &rhs) { - return assign(rhs.c_str(), rhs.size()); + return assign(rhs.data(), rhs.size()); } small_string& operator= (const char *s) { return assign(s); @@ -321,18 +318,18 @@ public: small_string & assign(const char * s) { return assign(s, strlen(s)); } small_string & assign(const void * s, size_type sz); small_string & assign(const stringref &s, size_type pos, size_type sz) { - return assign(s.c_str() + pos, sz); + return assign(s.data() + pos, sz); } small_string & assign(const stringref &rhs) { - if (c_str() != rhs.c_str()) assign(rhs.c_str(), rhs.size()); + if (data() != rhs.data()) assign(rhs.data(), rhs.size()); return *this; } small_string & push_back(char c) { return append(&c, 1); } small_string & append(char c) { return append(&c, 1); } small_string & append(const char * s) { return append(s, strlen(s)); } - small_string & append(const stringref & s) { return append(s.c_str(), s.size()); } - small_string & append(const std::string & s) { return append(s.c_str(), s.size()); } - small_string & append(const small_string & s) { return append(s.c_str(), s.size()); } + small_string & append(const stringref & s) { return append(s.data(), s.size()); } + small_string & append(const std::string & s) { return append(s.data(), s.size()); } + small_string & append(const small_string & s) { return append(s.data(), s.size()); } small_string & append(const void * s, size_type sz); small_string & operator += (char c) { return append(c); } small_string & operator += (const char * s) { return append(s); } @@ -358,7 +355,7 @@ public: } small_string & insert(iterator p, const_iterator f, const_iterator l) { return insert(p-c_str(), f, l-f); } - small_string & insert(size_type start, const stringref & v) { return insert(start, v.c_str(), v.size()); } + small_string & insert(size_type start, const stringref & v) { return insert(start, v.data(), v.size()); } small_string & insert(size_type start, const void * v, size_type sz); /** @@ -447,29 +444,29 @@ public: */ bool operator < (const char * s) const { return compare(s, strlen(s)) < 0; } - bool operator < (const std::string & s) const { return compare(s.c_str(), s.size()) < 0; } - bool operator < (const small_string & s) const { return compare(s.c_str(), s.size()) < 0; } - bool operator < (const stringref & s) const { return compare(s.c_str(), s.size()) < 0; } + bool operator < (const std::string & s) const { return compare(s.data(), s.size()) < 0; } + bool operator < (const small_string & s) const { return compare(s.data(), s.size()) < 0; } + bool operator < (const stringref & s) const { return compare(s.data(), s.size()) < 0; } bool operator <= (const char * s) const { return compare(s, strlen(s)) <= 0; } - bool operator <= (const std::string & s) const { return compare(s.c_str(), s.size()) <= 0; } - bool operator <= (const small_string & s) const { return compare(s.c_str(), s.size()) <= 0; } - bool operator <= (const stringref & s) const { return compare(s.c_str(), s.size()) <= 0; } + bool operator <= (const std::string & s) const { return compare(s.data(), s.size()) <= 0; } + bool operator <= (const small_string & s) const { return compare(s.data(), s.size()) <= 0; } + bool operator <= (const stringref & s) const { return compare(s.data(), s.size()) <= 0; } bool operator == (const char * s) const { return compare(s, strlen(s)) == 0; } - bool operator == (const std::string & s) const { return compare(s.c_str(), s.size()) == 0; } - bool operator == (const small_string & s) const { return compare(s.c_str(), s.size()) == 0; } - bool operator == (const stringref & s) const { return compare(s.c_str(), s.size()) == 0; } + bool operator == (const std::string & s) const { return compare(s.data(), s.size()) == 0; } + bool operator == (const small_string & s) const { return compare(s.data(), s.size()) == 0; } + bool operator == (const stringref & s) const { return compare(s.data(), s.size()) == 0; } bool operator != (const char * s) const { return compare(s, strlen(s)) != 0; } - bool operator != (const std::string & s) const { return compare(s.c_str(), s.size()) != 0; } - bool operator != (const small_string & s) const { return compare(s.c_str(), s.size()) != 0; } - bool operator != (const stringref & s) const { return compare(s.c_str(), s.size()) != 0; } + bool operator != (const std::string & s) const { return compare(s.data(), s.size()) != 0; } + bool operator != (const small_string & s) const { return compare(s.data(), s.size()) != 0; } + bool operator != (const stringref & s) const { return compare(s.data(), s.size()) != 0; } bool operator >= (const char * s) const { return compare(s, strlen(s)) >= 0; } - bool operator >= (const std::string & s) const { return compare(s.c_str(), s.size()) >= 0; } - bool operator >= (const small_string & s) const { return compare(s.c_str(), s.size()) >= 0; } - bool operator >= (const stringref & s) const { return compare(s.c_str(), s.size()) >= 0; } + bool operator >= (const std::string & s) const { return compare(s.data(), s.size()) >= 0; } + bool operator >= (const small_string & s) const { return compare(s.data(), s.size()) >= 0; } + bool operator >= (const stringref & s) const { return compare(s.data(), s.size()) >= 0; } bool operator > (const char * s) const { return compare(s, strlen(s)) > 0; } - bool operator > (const std::string & s) const { return compare(s.c_str(), s.size()) > 0; } - bool operator > (const small_string & s) const { return compare(s.c_str(), s.size()) > 0; } - bool operator > (const stringref & s) const { return compare(s.c_str(), s.size()) > 0; } + bool operator > (const std::string & s) const { return compare(s.data(), s.size()) > 0; } + bool operator > (const small_string & s) const { return compare(s.data(), s.size()) > 0; } + bool operator > (const stringref & s) const { return compare(s.data(), s.size()) > 0; } template<typename T> bool operator != (const T& s) const { return ! operator == (s); } diff --git a/vespalib/src/vespa/vespalib/util/exceptions.cpp b/vespalib/src/vespa/vespalib/util/exceptions.cpp index 3db697e3b68..fc64aa79ca4 100644 --- a/vespalib/src/vespa/vespalib/util/exceptions.cpp +++ b/vespalib/src/vespa/vespalib/util/exceptions.cpp @@ -74,7 +74,8 @@ PortListenException::make_message(int port, const vespalib::stringref &protocol, const vespalib::stringref &msg) { return make_string("failed to listen on port %d with protocol %s%s%s", - port, protocol.c_str(), msg.empty() ? "" : ": ", msg.c_str()); + port, vespalib::string(protocol).c_str(), msg.empty() ? "" : ": ", + vespalib::string(msg).c_str()); } PortListenException::PortListenException(int port, const vespalib::stringref &protocol, diff --git a/vespalib/src/vespa/vespalib/util/regexp.cpp b/vespalib/src/vespa/vespalib/util/regexp.cpp index b376b451b6d..e1aa4e9b189 100644 --- a/vespalib/src/vespa/vespalib/util/regexp.cpp +++ b/vespalib/src/vespa/vespalib/util/regexp.cpp @@ -32,13 +32,13 @@ Regexp::compile(const vespalib::stringref & re, Flags flags) preg->fastmap = static_cast<char *>(malloc(256)); preg->buffer = NULL; preg->allocated = 0; - const char * error = re_compile_pattern(re.c_str(), re.size(), preg); + const char * error = re_compile_pattern(re.data(), re.size(), preg); if (error != 0) { - LOG(warning, "invalid regexp '%s': %s", re.c_str(), error); + LOG(warning, "invalid regexp '%s': %s", vespalib::string(re).c_str(), error); return false; } if (re_compile_fastmap(preg) != 0) { - LOG(warning, "re_compile_fastmap failed for regexp '%s'", re.c_str()); + LOG(warning, "re_compile_fastmap failed for regexp '%s'", vespalib::string(re).c_str()); return false; } return true; @@ -57,7 +57,7 @@ Regexp::match(const vespalib::stringref & s) const { if ( ! valid() ) { return false; } regex_t *preg = const_cast<regex_t *>(static_cast<const regex_t *>(_data)); - int pos(re_search(preg, s.c_str(), s.size(), 0, s.size(), NULL)); + int pos(re_search(preg, s.data(), s.size(), 0, s.size(), NULL)); if (pos < -1) { throw IllegalArgumentException(make_string("re_search failed with code(%d)", pos)); } @@ -70,13 +70,13 @@ vespalib::string Regexp::replace(const vespalib::stringref & s, const vespalib:: regex_t *preg = const_cast<regex_t *>(static_cast<const regex_t *>(_data)); vespalib::string modified; int prev(0); - for(int pos(re_search(preg, s.c_str(), s.size(), 0, s.size(), NULL)); + for(int pos(re_search(preg, s.data(), s.size(), 0, s.size(), NULL)); pos >=0; - pos = re_search(preg, s.c_str()+prev, s.size()-prev, 0, s.size()-prev, NULL)) + pos = re_search(preg, s.data()+prev, s.size()-prev, 0, s.size()-prev, NULL)) { modified += s.substr(prev, pos); modified += replacement; - int count = re_match(preg, s.c_str()+prev, s.size()-prev, pos, NULL); + int count = re_match(preg, s.data()+prev, s.size()-prev, pos, NULL); prev += pos + count; } modified += s.substr(prev); diff --git a/vsm/src/vespa/vsm/common/document.cpp b/vsm/src/vespa/vsm/common/document.cpp index dc820cd99b3..7e4713e672c 100644 --- a/vsm/src/vespa/vsm/common/document.cpp +++ b/vsm/src/vespa/vsm/common/document.cpp @@ -12,10 +12,10 @@ namespace vsm vespalib::asciistream & operator << (vespalib::asciistream & os, const FieldRef & f) { - const char *s = f.c_str(); + const char *s = f.data(); os << f.size(); if (s) { - os << s; + os << s; // Better hope it's null terminated! } os << " : "; return os; diff --git a/vsm/src/vespa/vsm/searcher/fieldsearcher.cpp b/vsm/src/vespa/vsm/searcher/fieldsearcher.cpp index 78531f41cf8..2ba5fea3153 100644 --- a/vsm/src/vespa/vsm/searcher/fieldsearcher.cpp +++ b/vsm/src/vespa/vsm/searcher/fieldsearcher.cpp @@ -115,7 +115,7 @@ void FieldSearcher::prepare(QueryTermList & qtl, const SharedSearcherBuf & UNUSE size_t FieldSearcher::countWords(const FieldRef & f) { size_t words = 0; - const char * n = f.c_str(); + const char * n = f.data(); const char * e = n + f.size(); for( ; n < e; ++n) { for (; isspace(*n) && (n<e); ++n); diff --git a/vsm/src/vespa/vsm/searcher/futf8strchrfieldsearcher.cpp b/vsm/src/vespa/vsm/searcher/futf8strchrfieldsearcher.cpp index b388507aed5..b26b4bd5133 100644 --- a/vsm/src/vespa/vsm/searcher/futf8strchrfieldsearcher.cpp +++ b/vsm/src/vespa/vsm/searcher/futf8strchrfieldsearcher.cpp @@ -222,7 +222,7 @@ size_t FUTF8StrChrFieldSearcher::matchTerm(const FieldRef & f, QueryTerm & qt) { _folded.reserve(f.size()+16*3); //Enable fulle xmm0 store size_t unalignedStart(0); - bool ascii7Bit = lfoldua(f.c_str(), f.size(), &_folded[0], unalignedStart); + bool ascii7Bit = lfoldua(f.data(), f.size(), &_folded[0], unalignedStart); if (ascii7Bit) { char * folded = &_folded[unalignedStart]; /// Add the pattern 00 01 00 to avoid multiple eof tests of falling off the edge. @@ -240,7 +240,7 @@ size_t FUTF8StrChrFieldSearcher::matchTerms(const FieldRef & f, const size_t min { _folded.reserve(f.size()+16*3); //Enable fulle xmm0 store size_t unalignedStart(0); - bool ascii7Bit = lfoldua(f.c_str(), f.size(), &_folded[0], unalignedStart); + bool ascii7Bit = lfoldua(f.data(), f.size(), &_folded[0], unalignedStart); if (ascii7Bit) { char * folded = &_folded[unalignedStart]; /// Add the pattern 00 01 00 to avoid multiple eof tests of falling off the edge. diff --git a/vsm/src/vespa/vsm/searcher/strchrfieldsearcher.cpp b/vsm/src/vespa/vsm/searcher/strchrfieldsearcher.cpp index 93bfa76081f..1be1326807e 100644 --- a/vsm/src/vespa/vsm/searcher/strchrfieldsearcher.cpp +++ b/vsm/src/vespa/vsm/searcher/strchrfieldsearcher.cpp @@ -16,7 +16,7 @@ void StrChrFieldSearcher::onValue(const document::FieldValue & fv) { const document::LiteralFieldValueB & sfv = static_cast<const document::LiteralFieldValueB &>(fv); vespalib::stringref val = sfv.getValueRef(); - FieldRef fr(val.c_str(), std::min(maxFieldLength(), val.size())); + FieldRef fr(val.data(), std::min(maxFieldLength(), val.size())); matchDoc(fr); } diff --git a/vsm/src/vespa/vsm/searcher/utf8strchrfieldsearcher.cpp b/vsm/src/vespa/vsm/searcher/utf8strchrfieldsearcher.cpp index 82821dfeaff..b54ed2c583d 100644 --- a/vsm/src/vespa/vsm/searcher/utf8strchrfieldsearcher.cpp +++ b/vsm/src/vespa/vsm/searcher/utf8strchrfieldsearcher.cpp @@ -14,7 +14,7 @@ UTF8StrChrFieldSearcher::matchTerms(const FieldRef & f, const size_t mintsz) { (void) mintsz; termcount_t words(0); - const byte * n = reinterpret_cast<const byte *> (f.c_str()); + const byte * n = reinterpret_cast<const byte *> (f.data()); const byte * e = n + f.size(); if (f.size() >= _buf->size()) { _buf->reserve(f.size() + 1); diff --git a/vsm/src/vespa/vsm/searcher/utf8stringfieldsearcherbase.cpp b/vsm/src/vespa/vsm/searcher/utf8stringfieldsearcherbase.cpp index 0ce002e6765..872cfebfd70 100644 --- a/vsm/src/vespa/vsm/searcher/utf8stringfieldsearcherbase.cpp +++ b/vsm/src/vespa/vsm/searcher/utf8stringfieldsearcherbase.cpp @@ -104,7 +104,7 @@ size_t UTF8StringFieldSearcherBase::matchTermRegular(const FieldRef & f, QueryTerm & qt) { termcount_t words(0); - const byte * n = reinterpret_cast<const byte *> (f.c_str()); + const byte * n = reinterpret_cast<const byte *> (f.data()); // __builtin_prefetch(n, 0, 0); const cmptype_t * term; termsize_t tsz = qt.term(term); @@ -134,7 +134,7 @@ UTF8StringFieldSearcherBase::matchTermRegular(const FieldRef & f, QueryTerm & qt size_t UTF8StringFieldSearcherBase::matchTermExact(const FieldRef & f, QueryTerm & qt) { - const byte * n = reinterpret_cast<const byte *> (f.c_str()); + const byte * n = reinterpret_cast<const byte *> (f.data()); const cmptype_t * term; termsize_t tsz = qt.term(term); const cmptype_t * eterm = term+tsz; @@ -161,7 +161,7 @@ size_t UTF8StringFieldSearcherBase::matchTermSubstring(const FieldRef & f, QueryTerm & qt) { if (qt.termLen() == 0) { return 0; } - const byte * n = reinterpret_cast<const byte *> (f.c_str()); + const byte * n = reinterpret_cast<const byte *> (f.data()); const cmptype_t * term; termsize_t tsz = qt.term(term); if ( f.size() >= _buf->size()) { @@ -195,7 +195,7 @@ size_t UTF8StringFieldSearcherBase::matchTermSuffix(const FieldRef & f, QueryTerm & qt) { termcount_t words = 0; - const byte * srcbuf = reinterpret_cast<const byte *> (f.c_str()); + const byte * srcbuf = reinterpret_cast<const byte *> (f.data()); const byte * srcend = srcbuf + f.size(); const cmptype_t * term; termsize_t tsz = qt.term(term); diff --git a/vsm/src/vespa/vsm/searcher/utf8substringsearcher.cpp b/vsm/src/vespa/vsm/searcher/utf8substringsearcher.cpp index 94fb14b6217..4b8c6e31927 100644 --- a/vsm/src/vespa/vsm/searcher/utf8substringsearcher.cpp +++ b/vsm/src/vespa/vsm/searcher/utf8substringsearcher.cpp @@ -13,7 +13,7 @@ IMPLEMENT_DUPLICATE(UTF8SubStringFieldSearcher); size_t UTF8SubStringFieldSearcher::matchTerms(const FieldRef & f, const size_t mintsz) { - const byte * n = reinterpret_cast<const byte *> (f.c_str()); + const byte * n = reinterpret_cast<const byte *> (f.data()); if ( f.size() >= _buf->size()) { _buf->reserve(f.size() + 1); } diff --git a/vsm/src/vespa/vsm/searcher/utf8substringsnippetmodifier.cpp b/vsm/src/vespa/vsm/searcher/utf8substringsnippetmodifier.cpp index b229b7a5ebd..eee88b34ea6 100644 --- a/vsm/src/vespa/vsm/searcher/utf8substringsnippetmodifier.cpp +++ b/vsm/src/vespa/vsm/searcher/utf8substringsnippetmodifier.cpp @@ -14,8 +14,8 @@ size_t UTF8SubstringSnippetModifier::matchTerms(const FieldRef & f, const size_t mintsz) { _modified->reset(); - _readPtr = f.c_str(); - const byte * src = reinterpret_cast<const byte *> (f.c_str()); + _readPtr = f.data(); + const byte * src = reinterpret_cast<const byte *> (f.data()); // resize ucs4 buffer if (f.size() >= _buf->size()) { _buf->resize(f.size() + 1); @@ -46,8 +46,8 @@ UTF8SubstringSnippetModifier::matchTerms(const FieldRef & f, const size_t mintsz const cmptype_t * dtmp = ditr; for (; (titr < tend) && (*titr == *dtmp); ++titr, ++dtmp); if (titr == tend) { - const char * mbegin = f.c_str() + (*_offsets)[ditr - dbegin]; - const char * mend = f.c_str() + ((dtmp < dend) ? ((*_offsets)[dtmp - dbegin]) : f.size()); + const char * mbegin = f.data() + (*_offsets)[ditr - dbegin]; + const char * mend = f.data() + ((dtmp < dend) ? ((*_offsets)[dtmp - dbegin]) : f.size()); if (_readPtr <= mbegin) { // We will only copy from the field ref once. // If we have overlapping matches only the first one will be considered. @@ -61,9 +61,9 @@ UTF8SubstringSnippetModifier::matchTerms(const FieldRef & f, const size_t mintsz for(; (ditr < drend) && ! Fast_UnicodeUtil::IsWordChar(*ditr) ; ++ditr ); } } - assert(_readPtr <= (f.c_str() + f.size())); + assert(_readPtr <= (f.data() + f.size())); // copy remaining - size_t toCopy = f.size() - (_readPtr - f.c_str()); + size_t toCopy = f.size() - (_readPtr - f.data()); copyToModified(toCopy); return words + 1; // we must also count the last word diff --git a/vsm/src/vespa/vsm/searcher/utf8suffixstringfieldsearcher.cpp b/vsm/src/vespa/vsm/searcher/utf8suffixstringfieldsearcher.cpp index f469fa2ea73..13074937185 100644 --- a/vsm/src/vespa/vsm/searcher/utf8suffixstringfieldsearcher.cpp +++ b/vsm/src/vespa/vsm/searcher/utf8suffixstringfieldsearcher.cpp @@ -14,7 +14,7 @@ UTF8SuffixStringFieldSearcher::matchTerms(const FieldRef & f, const size_t mints { (void) mintsz; termcount_t words = 0; - const byte * srcbuf = reinterpret_cast<const byte *> (f.c_str()); + const byte * srcbuf = reinterpret_cast<const byte *> (f.data()); const byte * srcend = srcbuf + f.size(); if (f.size() >= _buf->size()) { _buf->reserve(f.size() + 1); diff --git a/vsm/src/vespa/vsm/vsm/docsumfilter.cpp b/vsm/src/vespa/vsm/vsm/docsumfilter.cpp index e6af5fb6477..034c3c57bde 100644 --- a/vsm/src/vespa/vsm/vsm/docsumfilter.cpp +++ b/vsm/src/vespa/vsm/vsm/docsumfilter.cpp @@ -74,7 +74,7 @@ public: if (fv.getClass().inherits(document::LiteralFieldValueB::classId)) { const document::LiteralFieldValueB & lfv = static_cast<const document::LiteralFieldValueB &>(fv); vespalib::stringref s = lfv.getValueRef(); - addToPacker(s.c_str(), s.size()); + addToPacker(s.data(), s.size()); } else { vespalib::string s = fv.toString(); addToPacker(s.c_str(), s.size()); diff --git a/vsm/src/vespa/vsm/vsm/flattendocsumwriter.cpp b/vsm/src/vespa/vsm/vsm/flattendocsumwriter.cpp index bf690e50719..080723e1dbd 100644 --- a/vsm/src/vespa/vsm/vsm/flattendocsumwriter.cpp +++ b/vsm/src/vespa/vsm/vsm/flattendocsumwriter.cpp @@ -21,13 +21,13 @@ FlattenDocsumWriter::onPrimitive(uint32_t, const Content & c) if (fv.getClass().inherits(document::LiteralFieldValueB::classId)) { const document::LiteralFieldValueB & lfv = static_cast<const document::LiteralFieldValueB &>(fv); vespalib::stringref value = lfv.getValueRef(); - _output.put(value.c_str(), value.size()); + _output.put(value.data(), value.size()); } else if (fv.getClass().inherits(document::NumericFieldValueBase::classId)) { vespalib::string value = fv.getAsString(); - _output.put(value.c_str(), value.size()); + _output.put(value.data(), value.size()); } else { vespalib::string value = fv.toString(); - _output.put(value.c_str(), value.size()); + _output.put(value.data(), value.size()); } _useSeparator = true; } |