Loading...
Searching...
No Matches
stringUtils.h
Go to the documentation of this file.
1//
2// Copyright 2016 Pixar
3//
4// Licensed under the Apache License, Version 2.0 (the "Apache License")
5// with the following modification; you may not use this file except in
6// compliance with the Apache License and the following modification to it:
7// Section 6. Trademarks. is deleted and replaced with:
8//
9// 6. Trademarks. This License does not grant permission to use the trade
10// names, trademarks, service marks, or product names of the Licensor
11// and its affiliates, except as required to comply with Section 4(c) of
12// the License and to reproduce the content of the NOTICE file.
13//
14// You may obtain a copy of the Apache License at
15//
16// http://www.apache.org/licenses/LICENSE-2.0
17//
18// Unless required by applicable law or agreed to in writing, software
19// distributed under the Apache License with the above modification is
20// distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
21// KIND, either express or implied. See the Apache License for the specific
22// language governing permissions and limitations under the Apache License.
23//
24#ifndef PXR_BASE_TF_STRING_UTILS_H
25#define PXR_BASE_TF_STRING_UTILS_H
26
30
31#include "pxr/pxr.h"
32
34#include "pxr/base/arch/hints.h"
36#include "pxr/base/tf/api.h"
37#include "pxr/base/tf/enum.h"
38
39#include <cstdarg>
40#include <cstring>
41#include <list>
42#include <set>
43#include <sstream>
44#include <string>
45#include <type_traits>
46#include <vector>
47
48PXR_NAMESPACE_OPEN_SCOPE
49
50class TfToken;
51
54
72TF_API
73std::string TfStringPrintf(const char *fmt, ...)
74#ifndef doxygen
76#endif /* doxygen */
77 ;
78
88TF_API
89std::string TfVStringPrintf(const std::string& fmt, va_list ap);
90
92
93TF_API
94std::string TfVStringPrintf(const char *fmt, va_list ap)
95#ifndef doxygen
97#endif /* doxygen */
98 ;
99
103inline std::string TfSafeString(const char* ptr) {
104 return ptr ? std::string(ptr) : std::string();
105}
106
108inline std::string TfIntToString(int i) {
109 return TfStringPrintf("%d", i);
110}
111
131TF_API double TfStringToDouble(const std::string& txt);
132
134TF_API double TfStringToDouble(const char *text);
135
137TF_API double TfStringToDouble(const char *text, int len);
138
150TF_API
151long TfStringToLong(const std::string &txt, bool *outOfRange=NULL);
152
154
155TF_API
156long TfStringToLong(const char *txt, bool *outOfRange=NULL);
157
168TF_API
169unsigned long TfStringToULong(const std::string &txt, bool *outOfRange=NULL);
170
172
173TF_API
174unsigned long TfStringToULong(const char *txt, bool *outOfRange=NULL);
175
187TF_API
188int64_t TfStringToInt64(const std::string &txt, bool *outOfRange=NULL);
189
191TF_API
192int64_t TfStringToInt64(const char *txt, bool *outOfRange=NULL);
193
204TF_API
205uint64_t TfStringToUInt64(const std::string &txt, bool *outOfRange=NULL);
206
208TF_API
209uint64_t TfStringToUInt64(const char *txt, bool *outOfRange=NULL);
210
211inline bool
212Tf_StringStartsWithImpl(char const *s, size_t slen,
213 char const *prefix, size_t prelen)
214{
215 return slen >= prelen && strncmp(s, prefix, prelen) == 0;
216}
217
219inline bool
220TfStringStartsWith(const std::string& s, const char *prefix)
221{
222 return Tf_StringStartsWithImpl(
223 s.c_str(), s.length(), prefix, strlen(prefix));
224}
225
227inline bool
228TfStringStartsWith(const std::string& s, const std::string& prefix) {
229 return TfStringStartsWith(s, prefix.c_str());
230}
231
232inline bool
233Tf_StringEndsWithImpl(char const *s, size_t slen,
234 char const *suffix, size_t suflen)
235{
236 return slen >= suflen && strcmp(s + (slen - suflen), suffix) == 0;
237}
238
240inline bool TfStringEndsWith(const std::string& s, const char *suffix)
241{
242 return Tf_StringEndsWithImpl(s.c_str(), s.length(),
243 suffix, strlen(suffix));
244}
245
247inline bool
248TfStringEndsWith(const std::string& s, const std::string& suffix)
249{
250 return TfStringEndsWith(s, suffix.c_str());
251}
252
254// \ingroup group_tf_String
255TF_API
256bool TfStringContains(const std::string& s, const char *substring);
257
259inline bool
260TfStringContains(const std::string &s, const std::string &substring) {
261 return TfStringContains(s, substring.c_str());
262}
263
265TF_API
266bool TfStringContains(const std::string &s, const TfToken& substring);
267
269TF_API
270std::string TfStringToLower(const std::string& source);
271
273TF_API
274std::string TfStringToUpper(const std::string& source);
275
278TF_API
279std::string TfStringCapitalize(const std::string& source);
280
292TF_API
293std::string TfStringToLowerAscii(const std::string& source);
294
299TF_API
300std::string TfStringTrimLeft(const std::string& s,
301 const char* trimChars = " \n\t\r");
302
307TF_API
308std::string TfStringTrimRight(const std::string& s,
309 const char* trimChars = " \n\t\r");
310
316TF_API
317std::string TfStringTrim(const std::string& s,
318 const char* trimChars = " \n\t\r");
319
325TF_API
326std::string TfStringGetCommonPrefix(std::string a, std::string b);
327
333TF_API
334std::string TfStringGetSuffix(const std::string& name, char delimiter = '.');
335
342TF_API
343std::string TfStringGetBeforeSuffix(const std::string& name, char delimiter = '.');
344
346TF_API
347std::string TfGetBaseName(const std::string& fileName);
348
356TF_API
357std::string TfGetPathName(const std::string& fileName);
358
364TF_API
365std::string TfStringReplace(const std::string& source, const std::string& from,
366 const std::string& to);
367
373template <class ForwardIterator>
374std::string TfStringJoin(
375 ForwardIterator begin, ForwardIterator end,
376 const char* separator = " ")
377{
378 if (begin == end)
379 return std::string();
380
381 size_t distance = std::distance(begin, end);
382 if (distance == 1)
383 return *begin;
384
385 std::string retVal;
386
387 size_t sum = 0;
388 ForwardIterator i = begin;
389 for (i = begin; i != end; ++i)
390 sum += i->size();
391 retVal.reserve(sum + strlen(separator) * (distance - 1));
392
393 i = begin;
394 retVal.append(*i);
395 while (++i != end) {
396 retVal.append(separator);
397 retVal.append(*i);
398 }
399
400 return retVal;
401}
402
407TF_API
408std::string TfStringJoin(const std::vector<std::string>& strings,
409 const char* separator = " ");
410
415TF_API
416std::string TfStringJoin(const std::set<std::string>& strings,
417 const char* separator = " ");
418
424TF_API
425std::vector<std::string> TfStringSplit(std::string const &src,
426 std::string const &separator);
427
437TF_API
438std::vector<std::string> TfStringTokenize(const std::string& source,
439 const char* delimiters = " \t\n");
440
444TF_API
445std::set<std::string> TfStringTokenizeToSet(const std::string& source,
446 const char* delimiters = " \t\n");
447
457TF_API
458std::vector<std::string>
459TfQuotedStringTokenize(const std::string& source,
460 const char* delimiters = " \t\n",
461 std::string *errors = NULL);
462
473TF_API
474std::vector<std::string>
475TfMatchedStringTokenize(const std::string& source,
476 char openDelimiter,
477 char closeDelimiter,
478 char escapeCharacter = '\0',
479 std::string *errors = NULL);
480
487inline
488std::vector<std::string>
489TfMatchedStringTokenize(const std::string& source,
490 char openDelimiter,
491 char closeDelimiter,
492 std::string *errors)
493{
494 return TfMatchedStringTokenize(source, openDelimiter,
495 closeDelimiter, '\0', errors);
496}
497
541 inline bool operator()(const std::string &lhs,
542 const std::string &rhs) const {
543 // Check first chars first. By far, it is most common that these
544 // characters are ASCII letters that differ. It is very rare that we
545 // have to account for different cases, or numerical comparisons, or
546 // UTF-8 characters so we special-case this first.
547 const unsigned char l = lhs.c_str()[0], r = rhs.c_str()[0];
548 const bool bothAscii = l < 0x80 && r < 0x80;
549 const bool differsIgnoringCase = (l & ~0x20) != (r & ~0x20);
550 const bool inLetterZone = (l >= 0x40) && (r >= 0x40);
551 if (ARCH_LIKELY(bothAscii && differsIgnoringCase && inLetterZone)) {
552 // This bit about add 5 mod 32 makes it so that '_' sorts less than
553 // all letters, which preserves existing behavior.
554 return ((l + 5) & 31) < ((r + 5) & 31);
555 }
556 else {
557 return _LessImpl(lhs, rhs);
558 }
559 }
560private:
561 TF_API bool _LessImpl(const std::string &lhs,
562 const std::string &rhs) const;
563};
564
570template <typename T>
571std::string
572TfStringify(const T& v)
573{
574 if constexpr (std::is_enum<T>::value) {
575 return TfEnum::GetName(v);
576 }
577 else {
578 std::ostringstream stream;
579 stream << v;
580 return stream.str();
581 }
582}
583
585TF_API std::string TfStringify(bool v);
587TF_API std::string TfStringify(std::string const&);
589TF_API std::string TfStringify(float);
591TF_API std::string TfStringify(double);
592
600 double d, char* buffer, int len, bool emitTrailingZero);
601
607 explicit TfStreamFloat(float f) : value(f) {}
608 float value;
609};
610
611TF_API std::ostream& operator<<(std::ostream& o, TfStreamFloat t);
612
618 explicit TfStreamDouble(double d) : value(d) {}
619 double value;
620};
621
622TF_API std::ostream& operator<<(std::ostream& o, TfStreamDouble t);
623
629template <typename T>
630T
631TfUnstringify(const std::string &instring, bool* status = NULL)
632{
633 T v = T();
634 std::istringstream stream(instring);
635 stream >> v;
636 if (status && !stream)
637 *status = false;
638 return v;
639}
640
642template <>
643TF_API
644bool TfUnstringify(const std::string &instring, bool* status);
646template <>
647TF_API
648std::string TfUnstringify(const std::string &instring, bool* status);
649
655TF_API
656std::string TfStringGlobToRegex(const std::string& s);
657
684//
689TF_API std::string TfEscapeString(const std::string &in);
690TF_API void TfEscapeStringReplaceChar(const char** in, char** out);
691
702TF_API
703std::string TfStringCatPaths( const std::string &prefix,
704 const std::string &suffix );
705
711inline bool
712TfIsValidIdentifier(std::string const &identifier)
713{
714 char const *p = identifier.c_str();
715 auto letter = [](unsigned c) { return ((c-'A') < 26) || ((c-'a') < 26); };
716 auto number = [](unsigned c) { return (c-'0') < 10; };
717 auto under = [](unsigned c) { return c == '_'; };
718 unsigned x = *p;
719 if (!x || number(x)) {
720 return false;
721 }
722 while (letter(x) || number(x) || under(x)) {
723 x = *p++;
724 };
725 return x == 0;
726}
727
730TF_API
731std::string
732TfMakeValidIdentifier(const std::string &in);
733
738TF_API
739std::string TfGetXmlEscapedString(const std::string &in);
740
742
743PXR_NAMESPACE_CLOSE_SCOPE
744
745#endif // PXR_BASE_TF_STRING_UTILS_H
Define function attributes.
#define ARCH_PRINTF_FUNCTION(_fmt, _firstArg)
Macro used to indicate a function takes a printf-like specification.
Definition: attributes.h:51
static TF_API std::string GetName(TfEnum val)
Returns the name associated with an enumerated value.
Token for efficient comparison, assignment, and hashing of known strings.
Definition: token.h:88
GF_API std::ostream & operator<<(std::ostream &, const GfBBox3d &)
Output a GfBBox3d using the format [(range) matrix zeroArea].
TF_API int64_t TfStringToInt64(const std::string &txt, bool *outOfRange=NULL)
Convert a sequence of digits in txt to an int64_t value.
TF_API bool TfStringContains(const std::string &s, const char *substring)
Returns true if s contains substring.
TF_API std::string TfStringTrimLeft(const std::string &s, const char *trimChars=" \n\t\r")
Trims characters (by default, whitespace) from the left.
bool TfStringStartsWith(const std::string &s, const char *prefix)
Returns true if s starts with prefix.
Definition: stringUtils.h:220
T TfUnstringify(const std::string &instring, bool *status=NULL)
Convert a string to an arbitrary type.
Definition: stringUtils.h:631
TF_API std::string TfStringToLower(const std::string &source)
Makes all characters in source lowercase, and returns the result.
std::string TfSafeString(const char *ptr)
Safely create a std::string from a (possibly NULL) char*.
Definition: stringUtils.h:103
TF_API std::string TfStringToLowerAscii(const std::string &source)
Locale-independent case folding of [A-Z] for ASCII or UTF-8 encoded source strings.
std::string TfIntToString(int i)
Returns the given integer as a string.
Definition: stringUtils.h:108
TF_API bool TfDoubleToString(double d, char *buffer, int len, bool emitTrailingZero)
Writes the string representation of d to buffer of length len.
TF_API std::string TfMakeValidIdentifier(const std::string &in)
Produce a valid identifier (see TfIsValidIdentifier) from in by replacing invalid characters with '_'...
std::string TfStringify(const T &v)
Convert an arbitrary type into a string.
Definition: stringUtils.h:572
TF_API std::string TfVStringPrintf(const std::string &fmt, va_list ap)
Returns a string formed by a printf()-like specification.
TF_API std::string TfStringGlobToRegex(const std::string &s)
Returns a string with glob characters converted to their regular expression equivalents.
TF_API std::set< std::string > TfStringTokenizeToSet(const std::string &source, const char *delimiters=" \t\n")
Breaks the given string apart, returning a set of strings.
bool TfIsValidIdentifier(std::string const &identifier)
Test whether identifier is valid.
Definition: stringUtils.h:712
TF_API std::vector< std::string > TfQuotedStringTokenize(const std::string &source, const char *delimiters=" \t\n", std::string *errors=NULL)
Breaks the given quoted string apart, returning a vector of strings.
TF_API std::string TfStringCatPaths(const std::string &prefix, const std::string &suffix)
Concatenate two strings containing '/' and '..' tokens like a file path or scope name.
TF_API std::vector< std::string > TfMatchedStringTokenize(const std::string &source, char openDelimiter, char closeDelimiter, char escapeCharacter='\0', std::string *errors=NULL)
Breaks the given string apart by matching delimiters.
TF_API std::string TfEscapeString(const std::string &in)
Process escape sequences in ANSI C string constants.
TF_API std::vector< std::string > TfStringTokenize(const std::string &source, const char *delimiters=" \t\n")
Breaks the given string apart, returning a vector of strings.
TF_API std::string TfStringReplace(const std::string &source, const std::string &from, const std::string &to)
Replaces all occurrences of string from with to in source.
TF_API long TfStringToLong(const std::string &txt, bool *outOfRange=NULL)
Convert a sequence of digits in txt to a long int value.
TF_API std::string TfStringGetBeforeSuffix(const std::string &name, char delimiter='.')
Returns everything up to the suffix of a string.
bool TfStringEndsWith(const std::string &s, const char *suffix)
Returns true if s ends with suffix.
Definition: stringUtils.h:240
TF_API uint64_t TfStringToUInt64(const std::string &txt, bool *outOfRange=NULL)
Convert a sequence of digits in txt to a uint64_t value.
std::string TfStringJoin(ForwardIterator begin, ForwardIterator end, const char *separator=" ")
Concatenates the strings (begin, end), with default separator.
Definition: stringUtils.h:374
TF_API std::string TfStringCapitalize(const std::string &source)
Returns a copy of the source string with only its first character capitalized.
TF_API std::string TfStringGetCommonPrefix(std::string a, std::string b)
Returns the common prefix of the input strings, if any.
TF_API unsigned long TfStringToULong(const std::string &txt, bool *outOfRange=NULL)
Convert a sequence of digits in txt to an unsigned long value.
TF_API std::string TfGetBaseName(const std::string &fileName)
Returns the base name of a file (final component of the path).
TF_API std::string TfStringToUpper(const std::string &source)
Makes all characters in source uppercase, and returns the result.
TF_API std::string TfStringPrintf(const char *fmt,...)
Returns a string formed by a printf()-like specification.
TF_API std::string TfStringTrimRight(const std::string &s, const char *trimChars=" \n\t\r")
Trims characters (by default, whitespace) from the right.
TF_API double TfStringToDouble(const std::string &txt)
Converts text string to double.
TF_API std::string TfGetXmlEscapedString(const std::string &in)
Escapes characters in in so that they are valid XML.
TF_API std::string TfGetPathName(const std::string &fileName)
Returns the path component of a file (complement of TfGetBaseName()).
TF_API std::string TfStringGetSuffix(const std::string &name, char delimiter='.')
Returns the suffix of a string.
TF_API std::string TfStringTrim(const std::string &s, const char *trimChars=" \n\t\r")
Trims characters (by default, whitespace) from the beginning and end of string.
TF_API std::vector< std::string > TfStringSplit(std::string const &src, std::string const &separator)
Breaks the given string apart, returning a vector of strings.
Compiler hints.
Define integral types.
Provides dictionary ordering binary predicate function on strings.
Definition: stringUtils.h:528
bool operator()(const std::string &lhs, const std::string &rhs) const
Return true if lhs is less than rhs in dictionary order.
Definition: stringUtils.h:541
A type which offers streaming for doubles in a canonical format that can safely roundtrip with the mi...
Definition: stringUtils.h:617
A type which offers streaming for floats in a canonical format that can safely roundtrip with the min...
Definition: stringUtils.h:606