HDK
 All Classes Namespaces Files Functions Variables Typedefs Enumerations Enumerator Friends Macros Groups Pages
UT_StringView.h
Go to the documentation of this file.
1 /*
2  * PROPRIETARY INFORMATION. This software is proprietary to
3  * Side Effects Software Inc., and is not to be reproduced,
4  * transmitted, or disclosed in any way without written permission.
5  *
6  * NAME: UT_StringView.h ( UT Library, C++)
7  *
8  * COMMENTS:
9  */
10 
11 #ifndef __UT_StringView__
12 #define __UT_StringView__
13 
14 #include "UT_API.h"
15 #include "UT_Assert.h"
16 
17 #include <SYS/SYS_Compiler.h>
18 #include <SYS/SYS_Inline.h>
19 #include <SYS/SYS_String.h>
20 #include <SYS/SYS_TypeTraits.h>
21 
22 #include <limits.h>
23 #include <string.h>
24 #include <memory>
25 #include <iosfwd>
26 
27 class UT_StringLit;
28 class UT_StringRef;
29 class UT_StringHolder;
30 class UT_WorkBuffer;
31 class UT_StringView;
32 template <typename T> class UT_Array;
34 
35 /// @brief A utility class to do read-only operations on a subset of an
36 /// existing string.
37 /// @note This object does not take ownership over the data being looked at,
38 /// so care must be taken that the owning object doesn't not go out of scope
39 /// before the view object.
41 {
42 public:
43  /// Default constructor. Constructs an empty non-string.
44  constexpr SYS_FORCE_INLINE
46  : myStart(nullptr)
47  , myEnd(nullptr)
48  { /**/ }
49 
50  /// Construct a string view from the entirety of a null-terminated string.
51  constexpr SYS_FORCE_INLINE
52  UT_StringView(const char *str)
53  : myStart(str)
54  , myEnd(nullptr)
55  {
56  if (myStart)
57  myEnd = myStart + __builtin_strlen(myStart);
58  }
59 
60  /// Construct a string view on a string of a given length.
61  constexpr SYS_FORCE_INLINE
62  explicit UT_StringView(const char *str, exint len)
63  : myStart(str)
64  , myEnd(nullptr)
65  {
66  //UT_ASSERT(len >= 0 && "String View length should not be negative");
67  if (myStart)
68  myEnd = myStart + len;
69  }
70 
71  /// Construct a string view on a given string range. The @c end pointer
72  /// should point to one past the end of the string (i.e. in the case of
73  /// null terminated strings, it should point at the null character).
75  explicit UT_StringView(const char *start, const char *end)
76  : myStart(start), myEnd(end)
77  {
78  UT_ASSERT((!myStart && !myEnd) || myStart <= myEnd);
79  }
80 
81  /// Construct a string view on a string from a start and end index
83  explicit UT_StringView(
84  const char *str,
85  exint start_index,
86  exint end_index)
87  : UT_StringView(str + start_index, str + end_index)
88  {
89  }
90 
91  /// Copy constructor.
93  UT_StringView(const UT_StringView &o) = default;
94 
99 
100  /// Assignment operator
102  UT_StringView & operator=(const UT_StringView &o) = default;
103 
104  /// The exact meaning depends on context, but generally used either as
105  /// end of view indicator by the functions that expect a view index or
106  /// as the error indicator by the functions that return a view index.
107  static constexpr exint npos = std::numeric_limits<exint>::max();
108 
109  /// @name Query functions
110  /// @{
111 
112  /// Returns the length of the string in bytes.
114  exint length() const { return exint(myEnd - myStart); }
115 
116  /// Returns @c true if the string is empty.
118  bool isEmpty() const { return myStart == myEnd; }
119 
120  /// Returns @c true if the view points to a non-empty string
122  bool isstring() const { return !isEmpty(); }
123 
124  /// Test whether the string is not an empty string (or nullptr)
126  explicit operator bool() const { return !isEmpty(); }
127 
128  /// Returns the memory, in bytes, used by this object.
130  int64 getMemoryUsage(bool inclusive) const
131  { return inclusive ? sizeof(*this) : 0; }
132 
133  /// Returns the character at index @c i. No bounds checking is performed.
135  char operator[](exint i) const { return myStart[i]; }
136  /// Returns the character at index @c i.
138  const char& at(exint pos) const
139  {
140  UT_ASSERT_P(pos < length() && pos >= 0);
141 
142  return myStart[pos];
143  }
144 
145  /// Returns a pointer to the first character of a view.
147  const char* data() const noexcept { return myStart; }
148 
149  /// Returns a constant reference to the first character in the view.
150  /// Undefined behaviour if view is empty.
152  {
154  !isEmpty(),
155  "Undefined behaviour trying to get front of empty string.");
156  return myStart[0];
157  }
158  /// Returns a constant reference to the last character in the view.
159  /// Undefined behaviour if the view is empty.
161  {
163  !isEmpty(),
164  "Undefined behaviour trying to get back of empty string.");
165  return myStart[length() - 1];
166  }
167 
168  /// Find first character equal to any of the characters in the given
169  /// character sequence.
171  findFirstOf(UT_StringView view, exint pos = 0) const noexcept;
172  SYS_NO_DISCARD_RESULT exint findFirstOf(char item, exint pos = 0) const
173  noexcept
174  {
175  UT_ASSERT(pos >= 0 && myStart + pos >= myStart);
176  for (const char *c = myStart + pos; c < myEnd; ++c)
177  {
178  if (*c == item)
179  return static_cast<exint>(c - myStart);
180  }
181  return UT_StringView::npos;
182  }
184  findFirstOf(const char *s, exint pos, exint count) const
185  {
186  return findFirstOf(UT_StringView(s, count), pos);
187  }
189  {
190  return findFirstOf(UT_StringView(s), pos);
191  }
192 
193  /// Find the last character equal to any of the characters in the viven
194  /// character sequence.
196  findLastOf(UT_StringView view, exint pos = npos) const noexcept;
197  SYS_NO_DISCARD_RESULT exint findLastOf(char item, exint pos = npos) const
198  noexcept
199  {
200  return findLastOf(UT_StringView(SYSaddressof(item), 1), pos);
201  }
203  findLastOf(const char *s, exint pos, exint count) const
204  {
205  return findLastOf(UT_StringView(s, count), pos);
206  }
208  findLastOf(const char *s, exint pos = npos) const
209  {
210  return findLastOf(UT_StringView(s), pos);
211  }
212 
213  /// Find the first character not equal to any of the characters in the given
214  /// character sequence.
216  findFirstNotOf(UT_StringView view, exint pos = 0) const noexcept;
217  SYS_NO_DISCARD_RESULT exint findFirstNotOf(char item, exint pos = 0) const
218  noexcept
219  {
220  UT_ASSERT(pos >= 0 && myStart + pos >= myStart);
221  for (const char *c = myStart + pos; c < myEnd; ++c)
222  {
223  if (*c != item)
224  return static_cast<exint>(c - myStart);
225  }
226 
227  return UT_StringView::npos;
228  }
230  findFirstNotOf(const char *s, exint pos, exint count) const
231  {
232  return findFirstNotOf(UT_StringView(s, count), pos);
233  }
235  {
236  return findFirstNotOf(UT_StringView(s), pos);
237  }
238 
239  /// Find the last character not equal to any of the characters in the given
240  /// character sequence.
242  findLastNotOf(UT_StringView view, exint pos = npos) const noexcept;
243  SYS_NO_DISCARD_RESULT exint findLastNotOf(char item, exint pos = npos) const
244  noexcept
245  {
246  return findLastNotOf(UT_StringView(SYSaddressof(item), 1), pos);
247  }
249  findLastNotOf(const char *s, exint pos, exint count) const
250  {
251  return findLastNotOf(UT_StringView(s, count), pos);
252  }
254  {
255  return findLastNotOf(UT_StringView(s), pos);
256  }
257  /// @}
258 
259  /// @name Iterators
260  /// @{
261 
262  /// The iterator type. @ref UT_StringView only provides read-only iterators.
263  typedef const char * const_iterator;
264 
265  /// Returns a constant iterator pointing to the beginning of the string.
267  const_iterator begin() const { return myStart; }
268 
269  /// Returns a constant iterator pointing to the end of the string.
271  const_iterator end() const { return myEnd; }
272  /// @}
273 
274  /// @name Manipulators
275  /// @{
276 
277  /// Clears the string. After this operation @ref isstring will return false,
278  /// and @ref isEmpty will return true.
279  void clear() { myStart = myEnd = nullptr; }
280 
281  /// Trim characters from the left- and right-hand side of the string.
282  /// By default this will trim the ASCII space characters.
284  UT_StringView trim(const char *c =" \t\n\r") const
285  { return trimInternal(c, true, true); }
286 
287  /// Trim characters from the left-hand side of the string.
288  /// By default this will trim the ASCII space characters.
290  UT_StringView trimLeft(const char *c =" \t\n\r") const
291  { return trimInternal(c, true, false); }
292 
293  /// Trim characters from the right-hand side of the string.
294  /// By default this will trim the ASCII space characters.
296  UT_StringView trimRight(const char *c =" \t\n\r") const
297  { return trimInternal(c, false, true); }
298 
299  /// Return the first token
301  UT_StringView firstToken(const char *sep_chars = " \t\n\r") const;
302 
303  /// Splits the string into individual tokens, separated by one or more of
304  /// the @c sep characters given. If @c group_separators is false, the
305  /// delimiters are not grouped together, e.g., ",," => ('', '', ''), which
306  /// is equivalent of Python's split().
308  UT_StringViewArray tokenize(const char *sep_chars =" \t\n\r",
309  bool group_separators = true) const;
310 
311  /// Splits the string into a list of words, using sep_str as the separator
312  /// string. Unlike tokenize, consecutive delimiters are not grouped
313  /// together and are instead taken to delimit empty strings.
314  /// If @c max_split is set, the string is split into at most @c max_sep
315  /// pieces.
317  UT_StringViewArray split(const char *sep_str = " ",
318  int max_split = INT_MAX) const;
319 
320  /// Returns a sub-string of the current string. If positive, the
321  /// @c index parameter is relative to the start. If negative, it's
322  /// relative to the end (e.g. substr(-1,1) will return the last character
323  /// of the string).
324  /// The empty string will be returned for out-of-range values.
327 
328  /// Move the start of the view forward by n characters.
329  /// If N is grreater then length() then it moves to the end.
330  void removePrefix(exint n);
331  /// Move the end of the view backwards by n characters.
332  /// If n is greater then the length() then it moves to the start.
333  void removeSuffix(exint n);
334  /// @}
335 
336  /// @name Operators
337  /// @{
338 
339  /// The @ref compare function compares this string with another, and returns
340  /// and integer less than, equal to, or greater than zero if this string
341  /// is found to be less than, equal to, or greater than the given string,
342  /// respectively. If a length is given, then the strings are compared as
343  /// if they were both of that length, or smaller.
345  int compare(const char *str, exint str_len,
346  bool case_sensitive=true) const;
348  int compare(const UT_StringView &sv,
349  bool case_sensitive=true) const;
350 
351  /// Returns true if the two strings compare as being equal.
352  /// If @c case_sensitive is set to @c false then the strings are compared
353  /// in a case-insensitive fashion.
355  bool equal(const char *str, bool case_sensitive=true) const
356  { return compare(UT_StringView(str),
357  case_sensitive) == 0; }
359  bool equal(const UT_StringView &other,
360  bool case_sensitive=true) const
361  { return compare(other, case_sensitive) == 0; }
362 
363  /// Returns true if the two strings compare as being equal.
365  bool operator==(const char *str) const
366  { return compare(UT_StringView(str)) == 0; }
368  bool operator==(const UT_StringView &other) const
369  { return compare(other) == 0; }
370 
371  /// Returns true if the two strings compare as being not equal.
373  bool operator!=(const char *str) const
374  { return compare(UT_StringView(str)) != 0; }
376  bool operator!=(const UT_StringView &other) const
377  { return compare(other) != 0; }
378 
379  /// Returns true if this string is lexicographically less than the given
380  /// string.
382  bool operator<(const char *str) const
383  { return compare(UT_StringView(str)) < 0; }
385  bool operator<(const UT_StringView &other) const
386  { return compare(other) < 0; }
387 
388  /// Find the first instance of the given character in this string.
389  const_iterator find(char c, const_iterator start) const;
391  const_iterator find(char c) const
392  { return find(c, begin()); }
393 
394  /// Find the first instance of the given substring in this string.
395  const_iterator find(const char *str, const_iterator start) const;
397  const_iterator find(const char *str) const
398  { return find(str, begin()); }
399 
400  /// Find last instance of the given character in this string, searching
401  /// backwards from 'pos'.
403  const_iterator rfind(char c, const_iterator pos) const;
405  const_iterator rfind(char c) const
406  { return rfind(c, end() - 1); }
407  /// Returns true if our string starts with the specified prefix.
409  bool startsWith(const char* prefix,
410  bool case_sensitive = true,
411  exint len = -1) const;
413  bool endsWith(const char* prefix,
414  bool case_sensitive = true,
415  exint len = -1) const;
416  /// @}
417 
418  /// Determine if string can be seen as a single floating point number
420  bool isFloat(bool skip_spaces = false,
421  bool loose = false,
422  bool allow_underscore = false) const;
423  /// Determine if string can be seen as a single integer number
425  bool isInteger(bool skip_spaces = false) const;
426 
428  unsigned hash() const
429  {
430  return SYSstring_hash(myStart, length(), /*allow_nulls*/true);
431  }
432 private:
434  UT_StringView trimInternal(const char *c, bool left, bool right) const;
435 
436  const char *myStart, *myEnd;
437 };
438 
439 // In very specific cases it can be helpful to store string views in a standard
440 // container such as map. When doing so EXTREME CAUTION must be taken!!!
441 namespace std
442 {
443  template <>
444  struct hash<UT_StringView>
445  {
446  size_t operator()(const UT_StringView& s) const
447  {
448  return s.hash();
449  }
450  };
451 }
452 // Implicitly adding support for hboost::hash hash doesn't work right now
453 // because it leads to ambiguity with the one for UT_String, I think because
454 // both of them can be created implicitly from const char pointers.
455 #if 0
456 // Hash for hboost. Same warning as above to use EXTREME CAUTION!!!
457 SYS_FORCE_INLINE size_t
458 hash_value(const UT_StringView &str)
459 {
460  return str.hash();
461 }
462 #endif
463 
464 UT_API std::ostream &
465 operator<<(std::ostream &os, const UT_StringView &sv);
466 
467 
468 #endif // __UT_StringView__
UT_API std::ostream & operator<<(std::ostream &os, const UT_StringView &sv)
SYS_NO_DISCARD_RESULT SYS_FORCE_INLINE const_iterator find(const char *str) const
SYS_NO_DISCARD_RESULT exint findFirstNotOf(const char *s, exint pos) const
Returns the length of the string in bytes.
SYS_NO_DISCARD_RESULT SYS_FORCE_INLINE const char & back() const
constexpr SYS_FORCE_INLINE UT_StringView(const char *str)
Construct a string view from the entirety of a null-terminated string.
Definition: UT_StringView.h:52
SYS_NO_DISCARD_RESULT exint findLastNotOf(const char *s, exint pos) const
Returns the length of the string in bytes.
GLint left
Definition: glcorearb.h:2005
SYS_NO_DISCARD_RESULT SYS_FORCE_INLINE const_iterator find(char c) const
SYS_NO_DISCARD_RESULT SYS_FORCE_INLINE bool operator<(const UT_StringView &other) const
GLuint start
Definition: glcorearb.h:475
SYS_NO_DISCARD_RESULT SYS_FORCE_INLINE bool operator<(const char *str) const
SYS_NO_DISCARD_RESULT SYS_FORCE_INLINE UT_StringView trimLeft(const char *c=" \t\n\r") const
CompareResults OIIO_API compare(const ImageBuf &A, const ImageBuf &B, float failthresh, float warnthresh, float failrelative, float warnrelative, ROI roi={}, int nthreads=0)
GLdouble right
Definition: glad.h:2817
constexpr SYS_FORCE_INLINE UT_StringView()
Default constructor. Constructs an empty non-string.
Definition: UT_StringView.h:45
int64 exint
Definition: SYS_Types.h:125
SYS_NO_DISCARD_RESULT SYS_FORCE_INLINE const_iterator end() const
Returns a constant iterator pointing to the end of the string.
GLdouble s
Definition: glad.h:3009
GLuint GLsizei GLsizei * length
Definition: glcorearb.h:795
#define UT_API
Definition: UT_API.h:14
#define SYS_EXINT_MAX
Definition: SYS_Types.h:181
FMT_CONSTEXPR auto find(Ptr first, Ptr last, T value, Ptr &out) -> bool
Definition: core.h:2138
SYS_NO_DISCARD_RESULT exint findLastOf(const char *s, exint pos, exint count) const
Returns the length of the string in bytes.
size_t operator()(const UT_StringView &s) const
OutGridT const XformOp bool bool
SYS_NO_DISCARD_RESULT SYS_FORCE_INLINE bool operator==(const char *str) const
Returns true if the two strings compare as being equal.
SYS_FORCE_INLINE UT_StringView(const char *str, exint start_index, exint end_index)
Construct a string view on a string from a start and end index.
Definition: UT_StringView.h:83
SYS_NO_DISCARD_RESULT unsigned hash() const
const char * const_iterator
The iterator type. UT_StringView only provides read-only iterators.
#define UT_ASSERT_MSG(ZZ,...)
Definition: UT_Assert.h:168
SYS_NO_DISCARD_RESULT SYS_FORCE_INLINE const char * data() const noexcept
Returns a pointer to the first character of a view.
SYS_NO_DISCARD_RESULT SYS_FORCE_INLINE int64 getMemoryUsage(bool inclusive) const
Returns the memory, in bytes, used by this object.
A utility class to do read-only operations on a subset of an existing string.
Definition: UT_StringView.h:40
SYS_NO_DISCARD_RESULT SYS_FORCE_INLINE bool isEmpty() const
Returns true if the string is empty.
GLdouble n
Definition: glcorearb.h:2008
SYS_NO_DISCARD_RESULT SYS_FORCE_INLINE exint length() const
Returns the length of the string in bytes.
SYS_NO_DISCARD_RESULT SYS_FORCE_INLINE constexpr T * SYSaddressof(T &val) noexcept
SYS_NO_DISCARD_RESULT SYS_FORCE_INLINE bool equal(const UT_StringView &other, bool case_sensitive=true) const
SYS_NO_DISCARD_RESULT SYS_FORCE_INLINE const_iterator rfind(char c) const
SYS_NO_DISCARD_RESULT SYS_FORCE_INLINE const char & at(exint pos) const
Returns the character at index i.
SYS_NO_DISCARD_RESULT SYS_FORCE_INLINE const char & front() const
#define UT_ASSERT_P(ZZ)
Definition: UT_Assert.h:164
size_t OIIO_UTIL_API rfind(string_view a, string_view b)
GLuint GLuint end
Definition: glcorearb.h:475
#define SYS_FORCE_INLINE
Definition: SYS_Inline.h:45
static constexpr exint npos
long long int64
Definition: SYS_Types.h:116
#define SYS_NO_DISCARD_RESULT
Definition: SYS_Compiler.h:86
SYS_NO_DISCARD_RESULT SYS_FORCE_INLINE bool operator==(const UT_StringView &other) const
constexpr SYS_FORCE_INLINE UT_StringView(const char *str, exint len)
Construct a string view on a string of a given length.
Definition: UT_StringView.h:62
SYS_NO_DISCARD_RESULT SYS_FORCE_INLINE char operator[](exint i) const
Returns the character at index i. No bounds checking is performed.
SYS_NO_DISCARD_RESULT exint findFirstNotOf(const char *s, exint pos, exint count) const
Returns the length of the string in bytes.
__hostdev__ bool isInteger(GridType gridType)
Return true if the GridType maps to a POD integer type.
Definition: NanoVDB.h:820
SYS_NO_DISCARD_RESULT SYS_FORCE_INLINE bool equal(const char *str, bool case_sensitive=true) const
SYS_NO_DISCARD_RESULT exint findFirstOf(const char *s, exint pos, exint count) const
Returns the length of the string in bytes.
PcpNodeRef_ChildrenIterator begin(const PcpNodeRef::child_const_range &r)
Support for range-based for loops for PcpNodeRef children ranges.
Definition: node.h:587
SYS_NO_DISCARD_RESULT exint findLastOf(const char *s, exint pos=npos) const
Returns the length of the string in bytes.
LeafData & operator=(const LeafData &)=delete
GLuint index
Definition: glcorearb.h:786
ImageBuf OIIO_API max(Image_or_Const A, Image_or_Const B, ROI roi={}, int nthreads=0)
SYS_NO_DISCARD_RESULT SYS_FORCE_INLINE const_iterator begin() const
Returns a constant iterator pointing to the beginning of the string.
SYS_FORCE_INLINE UT_StringView(const char *start, const char *end)
Definition: UT_StringView.h:75
SYS_NO_DISCARD_RESULT SYS_FORCE_INLINE bool isstring() const
Returns true if the view points to a non-empty string.
SYS_NO_DISCARD_RESULT SYS_FORCE_INLINE UT_StringView trimRight(const char *c=" \t\n\r") const
#define UT_ASSERT(ZZ)
Definition: UT_Assert.h:165
UT_Array< UT_StringView > UT_StringViewArray
Definition: UT_StringView.h:32
void OIIO_UTIL_API split(string_view str, std::vector< string_view > &result, string_view sep=string_view(), int maxsplit=-1)
SYS_NO_DISCARD_RESULT SYS_FORCE_INLINE bool operator!=(const UT_StringView &other) const
SYS_NO_DISCARD_RESULT exint findLastNotOf(const char *s, exint pos, exint count) const
Returns the length of the string in bytes.
size_t hash_value(const CH_ChannelRef &ref)
SYS_NO_DISCARD_RESULT exint findFirstOf(const char *s, exint pos) const
Returns the length of the string in bytes.
SYS_NO_DISCARD_RESULT SYS_FORCE_INLINE UT_StringView trim(const char *c=" \t\n\r") const
SYS_NO_DISCARD_RESULT SYS_FORCE_INLINE bool operator!=(const char *str) const
Returns true if the two strings compare as being not equal.
GLint GLsizei count
Definition: glcorearb.h:405