HDK
 All Classes Namespaces Files Functions Variables Typedefs Enumerations Enumerator Friends Macros Groups Pages
strutil.h
Go to the documentation of this file.
1 // Copyright Contributors to the OpenImageIO project.
2 // SPDX-License-Identifier: Apache-2.0
3 // https://github.com/AcademySoftwareFoundation/OpenImageIO
4 
5 // clang-format off
6 
7 /////////////////////////////////////////////////////////////////////////
8 /// @file strutil.h
9 ///
10 /// @brief String-related utilities, all in namespace Strutil.
11 /////////////////////////////////////////////////////////////////////////
12 
13 
14 
15 #pragma once
16 
17 #include <cstdio>
18 #include <map>
19 #include <sstream>
20 #include <string>
21 #include <utility>
22 #include <vector>
23 
24 #include <OpenImageIO/export.h>
25 #include <OpenImageIO/hash.h>
27 #include <OpenImageIO/platform.h>
29 
30 #include <OpenImageIO/detail/fmt.h>
32 
33 // Allow client software to know if this version of OIIO has Strutil::sprintf
34 #define OIIO_HAS_SPRINTF 1
35 
36 // Allow client software to know (and to determine, by setting this value
37 // before including this header) if this version of OIIO has Strutil::format
38 // behave like sprintf (OIIO_FORMAT_IS_FMT==0) or like python / {fmt} /
39 // C++20ish std::format (OIIO_FORMAT_IS_FMT==1).
40 #ifndef OIIO_FORMAT_IS_FMT
41 # define OIIO_FORMAT_IS_FMT 0
42 #endif
43 
44 // If OIIO_HIDE_FORMAT is defined, mark the old-style format functions as
45 // deprecated. (This is a debugging aid for downstream projects who want to
46 // root out any places where they might be using the old one).
47 #ifdef OIIO_HIDE_FORMAT
48 # define OIIO_FORMAT_DEPRECATED OIIO_DEPRECATED("old style (printf-like) formatting version of this function is deprecated")
49 #else
50 # define OIIO_FORMAT_DEPRECATED
51 #endif
52 
53 // If OIIO_PRINT_IS_SYNCHRONIZED is not defined, assume unsynchronized.
54 #ifndef OIIO_PRINT_IS_SYNCHRONIZED
55 # define OIIO_PRINT_IS_SYNCHRONIZED 0
56 #endif
57 
58 // Allow client software to know that at this moment, the fmt-based string
59 // formatting is locale-independent. This was 0 in older versions when fmt
60 // was locale dependent.
61 #define OIIO_FMT_LOCALE_INDEPENDENT 1
62 
63 
64 
66 /// @namespace Strutil
67 ///
68 /// @brief String-related utilities.
69 namespace Strutil {
70 
71 /// Output the string to the file/stream in a synchronized fashion, with an
72 /// internal mutex used to prevent threads from clobbering each other --
73 /// output strings coming from concurrent threads may be interleaved, but each
74 /// string is "atomic" and will never splice each other
75 /// character-by-character. If `flush` is true, the underlying stream will be
76 /// flushed after the string is output.
77 void OIIO_UTIL_API sync_output (FILE* file, string_view str,
78  bool flush = true);
79 void OIIO_UTIL_API sync_output (std::ostream& file, string_view str,
80  bool flush = true);
81 
82 
83 /// Construct a std::string in a printf-like fashion. For example:
84 ///
85 /// std::string s = Strutil::sprintf ("blah %d %g", (int)foo, (float)bar);
86 ///
87 /// Uses the fmt library underneath, so it's fully type-safe, and
88 /// works with any types that understand stream output via '<<'.
89 /// The formatting of the string will always use the classic "C" locale
90 /// conventions (in particular, '.' as decimal separator for float values).
91 #ifdef OIIO_DOXYGEN
92 template<typename Str, typename... Args>
93 std::string sprintf(const Str& fmt, Args&&... args);
94 #else
96 #endif
97 
98 
99 
100 /// format() constructs formatted strings. Note that this is in transition!
101 ///
102 /// Strutil::old::format() uses printf conventions and matches format() used
103 /// in OIIO 1.x. It is equivalent to Strutil::sprintf().
104 ///
105 /// std::string s = Strutil::old::sprintf ("blah %d %g", (int)foo, (float)bar);
106 ///
107 /// Strutil::fmt::format() uses "Python" conventions, in the style of string
108 /// formatting used by C++20 std::format and implemented today in the {fmt}
109 /// package (https://github.com/fmtlib/fmt). For example:
110 ///
111 /// std::string s = Strutil::format ("blah {} {}", (int)foo, (float)bar);
112 ///
113 /// Straight-up Strutil::format is today aliased to old::format for the sake
114 /// of back-compatibility, but will someday be switched to fmt::format.
115 ///
116 /// Recommended strategy for users:
117 /// * If you want printf conventions, switch to Strutil::sprintf().
118 /// * If you want to use the python conventions prior to the big switch,
119 /// use Strutil::fmt::format() explicitly (but see the caveat below).
120 /// * Use of unspecified Strutil::format() is, for back compatibility,
121 /// currently equivalent to sprintf, but beware that some point it will
122 /// switch to the future-standard formatting rules.
123 ///
124 
125 namespace fmt {
126 template<typename Str, typename... Args>
128 inline std::string format(const Str& fmt, Args&&... args)
129 {
131 }
132 } // namespace fmt
133 
134 namespace old {
135 template<typename... Args>
137 inline std::string format (const char* fmt, const Args&... args)
138 {
139  return Strutil::sprintf (fmt, args...);
140 }
141 
142 // DEPRECATED(2.0) string_view version. Phasing this out because
143 // std::string_view won't have a c_str() method.
144 template<typename... Args>
146 inline std::string format (string_view fmt, const Args&... args)
147 {
148  return format ({ fmt.data(), fmt.size() }, args...);
149 }
150 } // namespace old
151 
152 
153 // Choose whether Strutil::format is the old or new kind based on
154 // OIIO_FORMAT_IS_FMT.
155 #if OIIO_FORMAT_IS_FMT
156 using fmt::format;
157 #else
158 using old::format;
159 #endif
160 
161 
162 
163 /// Strutil::printf (fmt, ...)
164 /// Strutil::fprintf (FILE*, fmt, ...)
165 /// Strutil::fprintf (ostream& fmt, ...)
166 ///
167 /// Output formatted strings to stdout, a FILE*, or a stream, respectively.
168 /// All use printf-like formatting rules, are type-safe, are thread-safe
169 /// (the outputs are "atomic", at least versus other calls to
170 /// Strutil::*printf), and automatically flush their outputs. They are all
171 /// locale-independent (forcing classic "C" locale).
172 
173 template<typename... Args>
174 inline void printf (const char* fmt, const Args&... args)
175 {
176  sync_output (stdout, Strutil::sprintf(fmt, args...));
177 }
178 
179 template<typename... Args>
180 inline void fprintf (FILE *file, const char* fmt, const Args&... args)
181 {
182  sync_output (file, Strutil::sprintf(fmt, args...));
183 }
184 
185 template<typename... Args>
186 inline void fprintf (std::ostream &file, const char* fmt, const Args&... args)
187 {
188  sync_output (file, Strutil::sprintf(fmt, args...));
189 }
190 
191 
192 
193 namespace sync {
194 
195 /// Strutil::sync::print (fmt, ...)
196 /// Strutil::sync::print (FILE*, fmt, ...)
197 /// Strutil::sync::print (ostream& fmt, ...)
198 ///
199 /// Output formatted strings to stdout, a FILE*, or a stream, using a
200 /// "Python-like/std::format" type-safe formatting description. Results are
201 /// locale-independent (use `{:n}` locale-aware formatting).
202 ///
203 /// Output is fully thread-safe (the outputs are "atomic" to the file or
204 /// stream), and if the stream is buffered, it is flushed after the output).
205 
206 #if FMT_VERSION >= 70000
207 template<typename Str, typename... Args>
208 inline void print (FILE *file, const Str& fmt, Args&&... args)
209 {
210  sync_output (file, ::fmt::vformat(fmt, ::fmt::make_format_args(args...)));
211 }
212 
213 template<typename Str, typename... Args>
214 inline void print (const Str& fmt, Args&&... args)
215 {
216  sync_output(stdout, ::fmt::vformat(fmt, ::fmt::make_format_args(args...)));
217 }
218 
219 template<typename Str, typename... Args>
220 inline void print (std::ostream &file, const Str& fmt, Args&&... args)
221 {
222  sync_output (file, ::fmt::vformat(fmt, ::fmt::make_format_args(args...)));
223 }
224 
225 #else
226 
227 template<typename... Args>
228 inline void print (FILE *file, const char* fmt, Args&&... args)
229 {
230  sync_output (file, ::fmt::format(fmt, std::forward<Args>(args)...));
231 }
232 
233 template<typename... Args>
234 inline void print (const char* fmt, Args&&... args)
235 {
236  print(stdout, fmt, std::forward<Args>(args)...);
237 }
238 
239 template<typename... Args>
240 inline void print (std::ostream &file, const char* fmt, Args&&... args)
241 {
242  sync_output (file, ::fmt::format(fmt, std::forward<Args>(args)...));
243 }
244 #endif
245 } // namespace sync
246 
247 
248 
249 /// Strutil::print (fmt, ...)
250 /// Strutil::print (FILE*, fmt, ...)
251 /// Strutil::print (ostream& fmt, ...)
252 ///
253 /// Output formatted strings to stdout, a FILE*, or a stream, using a
254 /// "Python-like/std::format" type-safe formatting description. Results are
255 /// locale-independent (use `{:n}` locale-aware formatting).
256 ///
257 /// As wrappers around fmt::print (https://fmt.dev), these appear currently to
258 /// be thread-safe and "atomic" (multiple concurrent calls using the same
259 /// stream should not interleave their characters within the output strings).
260 /// But we can't 100% guarantee that on all platforms and all versions of fmt.
261 /// See the `Strutil::sync::print()` for similar functionality that is
262 /// guaranteed to be thread-safe and atomic, as well as flush their outputs
263 /// fully after each call (but are, as expected, slower). If
264 /// `OIIO_PRINT_IS_SYNCHRONIZED` is defined to be 1 prior to including
265 /// `<OpenImageIO/strutil.h>`, then print will be also be thread-safe and
266 /// atomic, like `sync::print`.
267 #ifdef OIIO_DOXYGEN
268 template<typename... Args>
269 void print (const char* fmt, const Args&... args);
270 
271 template<typename... Args>
272 void print (FILE *file, const char* fmt, const Args&... args);
273 
274 template<typename... Args>
275 void print (std::ostream &file, const char* fmt, const Args&... args);
276 
277 #elif FMT_VERSION >= 70000 && !OIIO_PRINT_IS_SYNCHRONIZED
279 #else
280 using sync::print;
281 #endif
282 
283 
284 namespace pvt {
286 }
287 
288 /// `debug(format, ...)` prints debugging message when attribute "debug" is
289 /// nonzero, which it is by default for DEBUG compiles or when the environment
290 /// variable OPENIMAGEIO_DEBUG is set. This is preferred to raw output to
291 /// stderr for debugging statements.
292 template<typename... Args>
293 void debug(const char* fmt, Args&&... args)
294 {
295  pvt::debug(fmt::format(fmt, std::forward<Args>(args)...));
296 }
297 
298 
299 
300 /// Return a std::string formatted from printf-like arguments -- passed
301 /// already as a va_list. This is not guaranteed type-safe and is not
302 /// extensible like format(). Use with caution!
303 std::string OIIO_UTIL_API vsprintf (const char *fmt, va_list ap)
304 #if defined(__GNUC__) && !defined(__CUDACC__)
305  __attribute__ ((format (printf, 1, 0) ))
306 #endif
307  ;
308 
309 /// Return a std::string formatted like Strutil::format, but passed
310 /// already as a va_list. This is not guaranteed type-safe and is not
311 /// extensible like format(). Use with caution!
312 OIIO_DEPRECATED("use `vsprintf` instead")
313 std::string OIIO_UTIL_API vformat (const char *fmt, va_list ap)
314 #if defined(__GNUC__) && !defined(__CUDACC__)
315  __attribute__ ((format (printf, 1, 0) ))
316 #endif
317  ;
318 
319 /// Return a string expressing a number of bytes, in human readable form.
320 /// - memformat(153) -> "153 B"
321 /// - memformat(15300) -> "14.9 KB"
322 /// - memformat(15300000) -> "14.6 MB"
323 /// - memformat(15300000000LL) -> "14.2 GB"
324 std::string OIIO_UTIL_API memformat (long long bytes, int digits=1);
325 
326 /// Return a string expressing an elapsed time, in human readable form.
327 /// e.g. "0:35.2"
328 std::string OIIO_UTIL_API timeintervalformat (double secs, int digits=1);
329 
330 
331 /// Get a map with RESTful arguments extracted from the given string 'str'.
332 /// Add it into the 'result' argument (Warning: the 'result' argument may
333 /// be changed even if 'get_rest_arguments ()' return an error!).
334 /// Return true on success, false on error.
335 /// Acceptable forms:
336 /// - text?arg1=val1&arg2=val2...
337 /// - ?arg1=val1&arg2=val2...
338 /// Everything before question mark will be saved into the 'base' argument.
339 bool OIIO_UTIL_API get_rest_arguments (const std::string &str, std::string &base,
340  std::map<std::string, std::string> &result);
341 
342 /// Take a string that may have embedded newlines, tabs, etc., and turn
343 /// those characters into escape sequences like `\n`, `\t`, `\v`, `\b`,
344 /// `\r`, `\f`, `\a`, `\\`, `\"`.
345 std::string OIIO_UTIL_API escape_chars (string_view unescaped);
346 
347 /// Take a string that has embedded escape sequences (`\\`, `\"`, `\n`,
348 /// etc.) and collapse them into the 'real' characters.
349 std::string OIIO_UTIL_API unescape_chars (string_view escaped);
350 
351 /// Word-wrap string `src` to no more than `columns` width, starting with an
352 /// assumed position of `prefix` on the first line and intending by `prefix`
353 /// blanks before all lines other than the first.
354 ///
355 /// Words may be split AT any characters in `sep` or immediately AFTER any
356 /// characters in `presep`. After the break, any extra `sep` characters will
357 /// be deleted.
358 ///
359 /// By illustration,
360 /// wordwrap("0 1 2 3 4 5 6 7 8", 10, 4)
361 /// should return:
362 /// "0 1 2\n 3 4 5\n 6 7 8"
363 std::string OIIO_UTIL_API wordwrap (string_view src, int columns = 80,
364  int prefix = 0, string_view sep = " ",
365  string_view presep = "");
366 
367 
368 /// Our favorite "string" hash of a length of bytes. Currently, it is just
369 /// a wrapper for an inlined, constexpr, Cuda-safe farmhash.
370 /// It returns a size_t, so will be a 64 bit hash on 64-bit platforms, but
371 /// a 32 bit hash on 32-bit platforms.
372 inline constexpr size_t
373 strhash(size_t len, const char *s)
374 {
375  return size_t(OIIO::farmhash::inlined::Hash64(s, len));
376 }
377 
378 
379 /// A guaranteed 64-bit string hash on all platforms.
380 inline constexpr uint64_t
381 strhash64(size_t len, const char *s)
382 {
383  return OIIO::farmhash::inlined::Hash64(s, len);
384 }
385 
386 
387 /// Hash a string_view. This is OIIO's default favorite string hasher.
388 /// Currently, it uses farmhash, is constexpr (for C++14), and works in Cuda.
389 /// This is rigged, though, so that empty strings hash always hash to 0 (that
390 /// isn't what a raw farmhash would give you, but it's a useful property,
391 /// especially for trivial initialization). It returns a size_t, so will be a
392 /// 64 bit hash on 64-bit platforms, but a 32 bit hash on 32-bit platforms.
393 inline constexpr size_t
395 {
396  return s.length() ? strhash(s.length(), s.data()) : 0;
397 }
398 
399 
400 
401 /// Hash a string_view, guaranteed 64 bits (even on 32 bit platforms).
402 inline constexpr uint64_t
404 {
405  return s.length() ? strhash64(s.length(), s.data()) : 0;
406 }
407 
408 
409 
410 /// Case-insensitive comparison of strings. For speed, this always uses a
411 /// static locale that doesn't require a mutex. Caveat: the case-sensivive
412 /// `==` of string_view's is about 20x faster than this case-insensitive
413 /// function.
415 
416 /// Case-insensitive ordered comparison of strings. For speed, this always
417 /// uses a static locale that doesn't require a mutex.
419 
420 /// Does 'a' start with the string 'b', with a case-sensitive comparison?
422 
423 /// Does 'a' start with the string 'b', with a case-insensitive comparison?
424 /// For speed, this always uses a static locale that doesn't require a
425 /// mutex. Caveat: the case-sensivive starts_with() is about 20x faster than
426 /// this case-insensitive function.
428 
429 /// Does 'a' end with the string 'b', with a case-sensitive comparison?
431 
432 /// Does 'a' end with the string 'b', with a case-insensitive comparison?
433 /// For speed, this always uses a static locale that doesn't require a
434 /// mutex. Caveat: the case-sensivive ends_with() is about 20x faster than
435 /// this case-insensitive function.
437 
438 /// Return the position of the first occurrence of `b` within `a`, or
439 /// std::npos if not found.
441 
442 /// Return the position of the first occurrence of `b` within `a`, with a
443 /// case-insensitive comparison, or std::npos if not found. Caveat: the
444 /// case-sensivive find() is about 20x faster than this case-insensitive
445 /// function.
447 
448 /// Return the position of the last occurrence of `b` within `a`, or npos if
449 /// not found.
451 
452 /// Return the position of the last occurrence of `b` within `a`, with a
453 /// case-insensitive comparison, or npos if not found. Caveat: the
454 /// case-sensivive rfind() is about 20x faster than this case-insensitive
455 /// function.
457 
458 /// Does 'a' contain the string 'b' within it?
460 
461 /// Does 'a' contain the string 'b' within it, using a case-insensitive
462 /// comparison? Caveat: the case-sensivive contains() is about 20x faster
463 /// than this case-insensitive function.
465 
466 /// Does 'a' contain the string 'b' within it? But start looking at the end!
467 /// This can be a bit faster than contains() if you think that the substring
468 /// `b` will tend to be close to the end of `a`.
470  return rfind(a, b) != string_view::npos;
471 }
472 
473 /// Does 'a' contain the string 'b' within it? But start looking at the end!
474 /// This can be a bit faster than contains() if you think that the substring
475 /// `b` will tend to be close to the end of `a`. Caveat: the case-sensivive
476 /// rcontains() is about 20x faster than this case-insensitive function.
478  return irfind(a, b) != string_view::npos;
479 }
480 
481 /// Does 'a' contain any of the characters within `set`?
483 
484 /// Convert to upper case in place, faster than std::toupper because we use
485 /// a static locale that doesn't require a mutex lock.
486 void OIIO_UTIL_API to_lower (std::string &a);
487 
488 /// Convert to upper case in place, faster than std::toupper because we use
489 /// a static locale that doesn't require a mutex lock.
490 void OIIO_UTIL_API to_upper (std::string &a);
491 
492 /// Return an all-upper case version of `a` (locale-independent).
493 inline std::string lower (string_view a) {
494  std::string result(a);
495  to_lower(result);
496  return result;
497 }
498 
499 /// Return an all-upper case version of `a` (locale-independent).
500 inline std::string upper (string_view a) {
501  std::string result(a);
502  to_upper(result);
503  return result;
504 }
505 
506 
507 
508 /// Return a reference to the section of str that has all consecutive
509 /// characters in chars removed from the beginning and ending. If chars is
510 /// empty, it will be interpreted as " \t\n\r\f\v" (whitespace).
512 
513 /// Return a reference to the section of str that has all consecutive
514 /// characters in chars removed from the beginning (left side). If chars is
515 /// empty, it will be interpreted as " \t\n\r\f\v" (whitespace).
517 
518 /// Return a reference to the section of str that has all consecutive
519 /// characters in chars removed from the ending (right side). If chars is
520 /// empty, it will be interpreted as " \t\n\r\f\v" (whitespace).
522 
523 
524 /// Fills the "result" list with the words in the string, using sep as
525 /// the delimiter string. If `maxsplit` is > -1, the string will be split
526 /// into at most `maxsplit` pieces (a negative value will impose no
527 /// maximum). If sep is "", any whitespace string is a separator. If the
528 /// source `str` is empty, there will be zero pieces.
529 void OIIO_UTIL_API split (string_view str, std::vector<string_view> &result,
530  string_view sep = string_view(), int maxsplit = -1);
531 void OIIO_UTIL_API split (string_view str, std::vector<std::string> &result,
532  string_view sep = string_view(), int maxsplit = -1);
533 
534 /// Split the contents of `str` using `sep` as the delimiter string. If
535 /// `sep` is "", any whitespace string is a separator. If `maxsplit > -1`,
536 /// at most `maxsplit` split fragments will be produced (for example,
537 /// maxsplit=2 will split at only the first separator, yielding at most two
538 /// fragments). The result is returned as a vector of std::string (for
539 /// `splits()`) or a vector of string_view (for `splitsv()`). If the source
540 /// `str` is empty, there will be zero pieces.
541 OIIO_UTIL_API std::vector<std::string>
542 splits (string_view str, string_view sep = "", int maxsplit = -1);
543 OIIO_UTIL_API std::vector<string_view>
544 splitsv (string_view str, string_view sep = "", int maxsplit = -1);
545 
546 /// Join all the strings in 'seq' into one big string, separated by the
547 /// 'sep' string. The Sequence can be any iterable collection of items that
548 /// are able to convert to string via stream output. Examples include:
549 /// std::vector<string_view>, std::vector<std::string>, std::set<ustring>,
550 /// std::vector<int>, etc.
551 template<class Sequence>
552 std::string join (const Sequence& seq, string_view sep="")
553 {
554  std::ostringstream out;
555  out.imbue(std::locale::classic()); // Force "C" locale
556  bool first = true;
557  for (auto&& s : seq) {
558  if (! first && sep.size())
559  out << sep;
560  out << s;
561  first = false;
562  }
563  return out.str();
564 }
565 
566 /// Join all the strings in 'seq' into one big string, separated by the
567 /// 'sep' string. The Sequence can be any iterable collection of items that
568 /// are able to convert to string via stream output. Examples include:
569 /// std::vector<string_view>, std::vector<std::string>, std::set<ustring>,
570 /// std::vector<int>, etc. Values will be rendered into the string in a
571 /// locale-independent manner (i.e., '.' for decimal in floats). If the
572 /// optional `len` is nonzero, exactly that number of elements will be
573 /// output (truncating or default-value-padding the sequence).
574 template<class Sequence>
575 std::string join (const Sequence& seq, string_view sep /*= ""*/, size_t len)
576 {
578  std::ostringstream out;
579  out.imbue(std::locale::classic()); // Force "C" locale
580  bool first = true;
581  for (auto&& s : seq) {
582  if (! first)
583  out << sep;
584  out << s;
585  first = false;
586  if (len && (--len == 0))
587  break;
588  }
589  while (len--) {
590  if (! first)
591  out << sep;
592  out << E();
593  first = false;
594  }
595  return out.str();
596 }
597 
598 /// Concatenate two strings, returning a std::string, implemented carefully
599 /// to not perform any redundant copies or allocations.
601 
602 /// Repeat a string formed by concatenating str n times.
603 std::string OIIO_UTIL_API repeat (string_view str, int n);
604 
605 /// Replace a pattern inside a string and return the result. If global is
606 /// true, replace all instances of the pattern, otherwise just the first.
608  string_view replacement, bool global=false);
609 
610 
611 /// strtod/strtof equivalents that are "locale-independent", always using
612 /// '.' as the decimal separator. This should be preferred for I/O and other
613 /// situations where you want the same standard formatting regardless of
614 /// locale.
615 float OIIO_UTIL_API strtof (const char *nptr, char **endptr = nullptr) noexcept;
616 double OIIO_UTIL_API strtod (const char *nptr, char **endptr = nullptr) noexcept;
617 
618 
619 // stoi() returns the int conversion of text from a string.
620 // No exceptions or errors -- parsing errors just return 0, over/underflow
621 // gets clamped to int range. No locale consideration.
622 OIIO_UTIL_API int stoi (string_view s, size_t* pos=0, int base=10);
623 
624 // stoui() returns the unsigned int conversion of text from a string.
625 // No exceptions or errors -- parsing errors just return 0. Negative
626 // values are cast, overflow is clamped. No locale considerations.
627 OIIO_UTIL_API unsigned int stoui (string_view s, size_t* pos=0, int base=10);
628 
629 /// stof() returns the float conversion of text from several string types.
630 /// No exceptions or errors -- parsing errors just return 0.0. These always
631 /// use '.' for the decimal mark (versus atof and std::strtof, which are
632 /// locale-dependent).
633 OIIO_UTIL_API float stof (string_view s, size_t* pos=0);
634 #define OIIO_STRUTIL_HAS_STOF 1 /* be able to test this */
635 
636 // Temporary fix: allow separate std::string and char* versions, to avoid
637 // string_view allocation on some platforms. This will be deprecated once
638 // we can count on all supported compilers using short string optimization.
639 OIIO_UTIL_API float stof (const std::string& s, size_t* pos=0);
640 OIIO_UTIL_API float stof (const char* s, size_t* pos=0);
641 // N.B. For users of ustring, there's a stof(ustring) defined in ustring.h.
642 
643 OIIO_UTIL_API double stod (string_view s, size_t* pos=0);
644 OIIO_UTIL_API double stod (const std::string& s, size_t* pos=0);
645 OIIO_UTIL_API double stod (const char* s, size_t* pos=0);
646 
647 
648 
649 /// Return true if the string is exactly (other than leading and trailing
650 /// whitespace) a valid int.
652 
653 /// Return true if the string is exactly (other than leading or trailing
654 /// whitespace) a valid float. This operations in a locale-independent
655 /// manner, i.e., it assumes '.' as the decimal mark.
657 
658 
659 
660 // Helper template to convert from generic type to string. Used when you
661 // want stoX but you're in a template. Rigged to use "C" locale.
662 template<typename T>
664  return T(s); // Generic: assume there is an explicit converter
665 }
666 
667 #ifndef OIIO_DOXYGEN
668 // Special case for int
669 template<> inline int from_string<int> (string_view s) {
670  return Strutil::stoi(s);
671 }
672 // Special case for uint
673 template<> inline unsigned int from_string<unsigned int> (string_view s) {
674  return Strutil::stoui(s);
675 }
676 // Special case for float -- note that by using Strutil::strtof, this
677 // always treats '.' as the decimal mark.
678 template<> inline float from_string<float> (string_view s) {
679  return Strutil::stof(s);
680 }
681 // Special case for double -- note that by using Strutil::strtof, this
682 // always treats '.' as the decimal mark.
683 template<> inline double from_string<double> (string_view s) {
684  return Strutil::stod(s);
685 }
686 
687 template<> inline int64_t from_string<int64_t>(string_view s) {
688  // For conversion of string_view to unsigned int, fall back on strtoll.
689  auto r = strtoll(std::string(s).c_str(), nullptr, 10);
690  return static_cast<int64_t>(r);
691 }
692 
693 template<> inline uint64_t from_string<uint64_t>(string_view s) {
694  // For conversion of string_view to unsigned int, fall back on strtoull.
695  auto r = strtoull(std::string(s).c_str(), nullptr, 10);
696  return static_cast<uint64_t>(r);
697 }
698 #endif
699 
700 
701 
702 /// Template function to convert any type to a string. The default
703 /// implementation is just to use sprintf or fmt::to_string. The template
704 /// can be overloaded if there is a better method for particular types.
705 template<typename T>
706 inline std::string to_string (const T& value) {
708 }
709 
710 // Some special pass-through cases
711 inline std::string to_string (const std::string& value) { return value; }
712 inline std::string to_string (string_view value) { return value; }
713 inline std::string to_string (const char* value) { return value; }
714 
715 
716 
717 // Helper template to test if a string is a generic type. Used instead of
718 // string_is_X, but when you're inside templated code.
719 template<typename T>
720 inline bool string_is (string_view /*s*/) {
721  return false; // Generic: assume there is an explicit specialization
722 }
723 // Special case for int
724 template <> inline bool string_is<int> (string_view s) {
725  return string_is_int (s);
726 }
727 // Special case for float. Note that by using Strutil::stof, this always
728 // treats '.' as the decimal character.
729 template <> inline bool string_is<float> (string_view s) {
730  return string_is_float (s);
731 }
732 
733 
734 
735 
736 /// Given a string containing values separated by a comma (or optionally
737 /// another separator), extract the individual values, placing them into
738 /// vals[] which is presumed to already contain defaults. If only a single
739 /// value was in the list, replace all elements of vals[] with the value.
740 /// Otherwise, replace them in the same order. A missing value will simply
741 /// not be replaced. Return the number of values found in the list
742 /// (including blank or malformed ones). If the vals vector was empty
743 /// initially, grow it as necessary.
744 ///
745 /// For example, if T=float, suppose initially, vals[] = {0, 1, 2}, then
746 /// "3.14" results in vals[] = {3.14, 3.14, 3.14}
747 /// "3.14,,-2.0" results in vals[] = {3.14, 1, -2.0}
748 ///
749 /// This can work for type T = int, float, or any type for that has
750 /// an explicit constructor from a std::string.
751 template<class T, class Allocator>
752 int extract_from_list_string (std::vector<T, Allocator> &vals,
753  string_view list,
754  string_view sep = ",")
755 {
756  size_t nvals = vals.size();
757  std::vector<string_view> valuestrings;
758  Strutil::split (list, valuestrings, sep);
759  for (size_t i = 0, e = valuestrings.size(); i < e; ++i) {
760  T v = from_string<T> (valuestrings[i]);
761  if (nvals == 0)
762  vals.push_back (v);
763  else if (valuestrings[i].size()) {
764  if (vals.size() > i) // don't replace non-existent entries
765  vals[i] = from_string<T> (valuestrings[i]);
766  }
767  /* Otherwise, empty space between commas, so leave default alone */
768  }
769  if (valuestrings.size() == 1 && nvals > 0) {
770  vals.resize (1);
771  vals.resize (nvals, vals[0]);
772  }
773  return list.size() ? (int) valuestrings.size() : 0;
774 }
775 
776 
777 /// Given a string containing values separated by a comma (or optionally
778 /// another separator), extract the individual values, returning them as a
779 /// std::vector<T>. The vector will be initialized with `nvals` elements
780 /// with default value `val`. If only a single value was in the list,
781 /// replace all elements of vals[] with the value. Otherwise, replace them
782 /// in the same order. A missing value will simply not be replaced and
783 /// will retain the initialized default value. If the string contains more
784 /// then `nvals` values, they will append to grow the vector.
785 ///
786 /// For example, if T=float,
787 /// extract_from_list_string ("", 3, 42.0f)
788 /// --> {42.0, 42.0, 42.0}
789 /// extract_from_list_string ("3.14", 3, 42.0f)
790 /// --> {3.14, 3.14, 3.14}
791 /// extract_from_list_string ("3.14,,-2.0", 3, 42.0f)
792 /// --> {3.14, 42.0, -2.0}
793 /// extract_from_list_string ("1,2,3,4", 3, 42.0f)
794 /// --> {1.0, 2.0, 3.0, 4.0}
795 ///
796 /// This can work for type T = int, float, or any type for that has
797 /// an explicit constructor from a std::string.
798 template<class T>
799 std::vector<T>
800 extract_from_list_string (string_view list, size_t nvals=0, T val=T(),
801  string_view sep = ",")
802 {
803  std::vector<T> vals (nvals, val);
804  extract_from_list_string (vals, list, sep);
805  return vals;
806 }
807 
808 
809 
810 /// Scan a string for date and time information. Return true upon success,
811 /// false if the string did not appear to contain a valid date/time. If, after
812 /// parsing a valid date/time (including out of range values), `str` contains
813 /// more characters after that, it is not considered a failure.
814 ///
815 /// Valid date/time formats include:
816 /// * YYYY-MM-DD HH:MM:SS
817 /// * YYYY:MM:DD HH:MM:SS
818 /// * YYYY/MM/DD HH:MM:SS
819 OIIO_UTIL_API bool
820 scan_datetime(string_view str, int& year, int& month, int& day,
821  int& hour, int& min, int& sec);
822 
823 
824 
825 /// C++ functor wrapper class for using strhash for unordered_map or
826 /// unordered_set. The way this is used, in conjunction with
827 /// StringEqual, to build an efficient hash map for char*'s or
828 /// std::string's is as follows:
829 /// \code
830 /// unordered_map <const char *, Key, Strutil::StringHash, Strutil::StringEqual>
831 /// \endcode
832 class StringHash {
833 public:
834  size_t operator() (string_view s) const {
835  return (size_t)Strutil::strhash(s);
836  }
837 };
838 
839 
840 
841 /// C++ functor for comparing two strings for equality of their characters.
843  bool operator() (const char *a, const char *b) const noexcept { return strcmp (a, b) == 0; }
844  bool operator() (string_view a, string_view b) const noexcept { return a == b; }
845 };
846 
847 
848 /// C++ functor for comparing two strings for equality of their characters
849 /// in a case-insensitive and locale-insensitive way.
851  bool operator() (const char *a, const char *b) const noexcept;
852  bool operator() (string_view a, string_view b) const noexcept { return iequals (a, b); }
853 };
854 
855 
856 /// C++ functor for comparing the ordering of two strings.
858  bool operator() (const char *a, const char *b) const noexcept { return strcmp (a, b) < 0; }
859  bool operator() (string_view a, string_view b) const noexcept { return a < b; }
860 };
861 
862 
863 /// C++ functor for comparing the ordering of two strings in a
864 /// case-insensitive and locale-insensitive way.
866  bool operator() (const char *a, const char *b) const noexcept;
867  bool operator() (string_view a, string_view b) const noexcept { return a < b; }
868 };
869 
870 
871 
872 /// Conversion of normal char-based strings (presumed to be UTF-8 encoding)
873 /// to a UTF-16 encoded wide char string, wstring.
874 std::wstring OIIO_UTIL_API utf8_to_utf16wstring (string_view utf8str) noexcept;
875 
876 #if OPENIMAGEIO_VERSION < 30000
877 /// Old name for utf8_to_utf16wstring. Will be deprecated for OIIO 2.5+ and
878 /// removed for OIIO 3.0. Use utf8_to_utf16wstring which is more clear that
879 /// this particular conversion from utf8 to utf16 returns a std::wstring and
880 /// not a std::u16string.
881 #if OPENIMAGEIO_VERSION >= 20500
882 OIIO_DEPRECATED("Use utf8_to_utf16wstring instead")
883 #endif
884 std::wstring OIIO_UTIL_API utf8_to_utf16 (string_view utf8str) noexcept;
885 #endif
886 
887 /// Conversion from wstring UTF-16 to a UTF-8 std::string. This is the
888 /// standard way to convert from Windows wide character strings used for
889 /// filenames into the UTF-8 strings OIIO expects for filenames when passed to
890 /// functions like ImageInput::open().
891 std::string OIIO_UTIL_API utf16_to_utf8(const std::wstring& utf16str) noexcept;
892 
893 /// Conversion from UTF-16 std::u16string to a UTF-8 std::string.
894 std::string OIIO_UTIL_API utf16_to_utf8(const std::u16string& utf16str) noexcept;
895 
896 
897 
898 /// Copy at most size characters (including terminating 0 character) from
899 /// src into dst[], filling any remaining characters with 0 values. Returns
900 /// dst. Note that this behavior is identical to strncpy, except that it
901 /// guarantees that there will be a terminating 0 character.
902 OIIO_UTIL_API char * safe_strcpy (char *dst, string_view src, size_t size) noexcept;
903 
904 
905 /// Append `src` to the end of the C-string buffer dst, plus a terminating
906 /// null, assuming that dst can hold at most `size` characters (including
907 /// terminating 0 character). Returns dst. Note that this behavior is similar
908 /// to strcat, but guarantees that the resulting string fits into `size` bytes
909 /// and is null-terminated.
910 OIIO_UTIL_API char* safe_strcat(char *dst, string_view src, size_t size) noexcept;
911 
912 
913 /// Return the length of null-terminated string `str`, up to maximum `size`.
914 /// If str is nullptr, return 0. This is equivalent to C11 strnlen_s.
915 OIIO_UTIL_API size_t safe_strlen(const char* str, size_t size) noexcept;
916 
917 
918 /// Return a string_view that is a substring of the given C string, ending at
919 /// the first null character or after size characters, whichever comes first.
920 inline string_view safe_string_view(const char* str, size_t size) noexcept
921 {
922  return string_view(str, safe_strlen(str, size));
923 }
924 
925 /// Return a std::string that is a substring of the given C string, ending at
926 /// the first null character or after size characters, whichever comes first.
927 inline std::string safe_string(const char* str, size_t size)
928 {
929  return safe_string_view(str, size);
930 }
931 
932 
933 
934 /// Is the character a whitespace character (space, linefeed, tab, carrage
935 /// return)? Note: this is safer than C isspace(), which has undefined
936 /// behavior for negative char values. Also note that it differs from C
937 /// isspace by not detecting form feed or vertical tab, because who cares.
938 inline bool isspace(char c) {
939  return c == ' ' || c == '\n' || c == '\t' || c == '\r';
940 }
941 
942 /// Modify str to trim any leading whitespace (space, tab, linefeed, cr)
943 /// from the front.
944 void OIIO_UTIL_API skip_whitespace (string_view &str) noexcept;
945 
946 /// Modify str to trim any trailing whitespace (space, tab, linefeed, cr)
947 /// from the back.
949 
950 /// Modify str to trim any whitespace (space, tab, linefeed, cr) from both
951 /// the front and back.
952 inline void trim_whitespace (string_view &str) noexcept {
953  skip_whitespace(str);
955 }
956 
957 /// Return the portion of str that is trimmed of any whitespace (space, tab,
958 /// linefeed, cr) from both the front and back.
960  skip_whitespace(str);
962  return str;
963 }
964 
965 /// If str's first character is c (or first non-whitespace char is c, if
966 /// skip_whitespace is true), return true and additionally modify str to
967 /// skip over that first character if eat is also true. Otherwise, if str
968 /// does not begin with character c, return false and don't modify str.
969 bool OIIO_UTIL_API parse_char (string_view &str, char c,
970  bool skip_whitespace = true, bool eat=true) noexcept;
971 
972 /// Modify str to trim all characters up to (but not including) the first
973 /// occurrence of c, and return true if c was found or false if the whole
974 /// string was trimmed without ever finding c. But if eat is false, then
975 /// don't modify str, just return true if any c is found, false if no c
976 /// is found.
977 bool OIIO_UTIL_API parse_until_char (string_view &str, char c, bool eat=true) noexcept;
978 
979 /// If str's first non-whitespace characters are the prefix, return true and
980 /// additionally modify str to skip over that prefix if eat is also true.
981 /// Otherwise, if str doesn't start with optional whitespace and the prefix,
982 /// return false and don't modify str.
983 bool OIIO_UTIL_API parse_prefix (string_view &str, string_view prefix, bool eat=true) noexcept;
984 
985 /// If str's first non-whitespace characters form a valid integer, return
986 /// true, place the integer's value in val, and additionally modify str to
987 /// skip over the parsed integer if eat is also true. Otherwise, if no
988 /// integer is found at the beginning of str, return false and don't modify
989 /// val or str.
990 bool OIIO_UTIL_API parse_int (string_view &str, int &val, bool eat=true) noexcept;
991 
992 /// If str's first non-whitespace characters form a valid float, return
993 /// true, place the float's value in val, and additionally modify str to
994 /// skip over the parsed float if eat is also true. Otherwise, if no float
995 /// is found at the beginning of str, return false and don't modify val or
996 /// str.
997 bool OIIO_UTIL_API parse_float (string_view &str, float &val, bool eat=true) noexcept;
998 
999 /// Synonym for parse_int
1000 inline bool parse_value(string_view &str, float &val, bool eat=true) noexcept
1001 {
1002  return parse_float(str, val, eat);
1003 }
1004 
1005 /// Synonym for parse_float
1006 inline bool parse_value(string_view &str, int &val, bool eat=true) noexcept
1007 {
1008  return parse_int(str, val, eat);
1009 }
1010 
1011 /// Parse from `str`: a `prefix`, a series of int values separated by the
1012 /// `sep` string, and a `postfix`, placing the values in the elements of
1013 /// mutable span `values`, where the span length indicates the number of
1014 /// values to read. Any of the prefix, separator, or postfix may be empty
1015 /// strings. If `eat` is true and the parse was successful, `str` will be
1016 /// updated in place to trim everything that was parsed, but if any part of
1017 /// the parse failed, `str` will not be altered from its original state.
1018 bool OIIO_UTIL_API
1020  string_view sep = "", string_view postfix = "",
1021  bool eat = true) noexcept;
1022 /// parse_values for float.
1023 bool OIIO_UTIL_API
1024 parse_values(string_view& str, string_view prefix, span<float> values,
1025  string_view sep = "", string_view postfix = "",
1026  bool eat = true) noexcept;
1027 
1028 /// Similar to parse_values, but with no option to "eat" from
1029 /// or modify the source string.
1030 inline bool
1031 scan_values(string_view str, string_view prefix, span<int> values,
1032  string_view sep = "", string_view postfix = "") noexcept
1033 {
1034  string_view sv(str);
1035  return parse_values(sv, prefix, values, sep, postfix);
1036 }
1037 
1038 inline bool
1040  string_view sep = "", string_view postfix = "") noexcept
1041 {
1042  string_view sv(str);
1043  return parse_values(sv, prefix, values, sep, postfix);
1044 }
1045 
1047 /// If str's first non-whitespace characters form a valid string (either a
1048 /// single word separated by whitespace or anything inside a double-quoted
1049 /// ("") or single-quoted ('') string, return true, place the string's value
1050 /// (not including surrounding double quotes) in val, and additionally
1051 /// modify str to skip over the parsed string if eat is also true.
1052 /// Otherwise, if no string is found at the beginning of str, return false
1053 /// and don't modify val or str. If keep_quotes is true, the surrounding
1054 /// double quotes (if present) will be kept in val.
1055 bool OIIO_UTIL_API parse_string (string_view &str, string_view &val, bool eat=true,
1056  QuoteBehavior keep_quotes=DeleteQuotes) noexcept;
1057 
1058 /// Return the first "word" (set of contiguous alphabetical characters) in
1059 /// str, and additionally modify str to skip over the parsed word if eat is
1060 /// also true. Otherwise, if no word is found at the beginning of str,
1061 /// return an empty string_view and don't modify str.
1062 string_view OIIO_UTIL_API parse_word (string_view &str, bool eat=true) noexcept;
1063 
1064 /// If str's first non-whitespace characters form a valid C-like identifier,
1065 /// return the identifier, and additionally modify str to skip over the
1066 /// parsed identifier if eat is also true. Otherwise, if no identifier is
1067 /// found at the beginning of str, return an empty string_view and don't
1068 /// modify str.
1069 string_view OIIO_UTIL_API parse_identifier (string_view &str, bool eat=true) noexcept;
1070 
1071 /// If str's first non-whitespace characters form a valid C-like identifier,
1072 /// return the identifier, and additionally modify str to skip over the
1073 /// parsed identifier if eat is also true. Otherwise, if no identifier is
1074 /// found at the beginning of str, return an empty string_view and don't
1075 /// modify str. The 'allowed' parameter may specify a additional characters
1076 /// accepted that would not ordinarily be allowed in C identifiers, for
1077 /// example, parse_identifier (blah, "$:") would allow "identifiers"
1078 /// containing dollar signs and colons as well as the usual alphanumeric and
1079 /// underscore characters.
1081  string_view allowed, bool eat = true) noexcept;
1082 
1083 /// If the C-like identifier at the head of str exactly matches id,
1084 /// return true, and also advance str if eat is true. If it is not a match
1085 /// for id, return false and do not alter str.
1087  bool eat=true) noexcept;
1088 
1089 /// Return the longest prefix of `str` that does not contain any characters
1090 /// found in `set` (which defaults to the set of common whitespace
1091 /// characters). If `eat` is true, then `str` will be modified to trim off
1092 /// this returned prefix (but not the separator character).
1094  string_view set=" \t\r\n", bool eat=true) noexcept;
1095 
1096 /// Return the longest prefix of `str` that contain only characters found in
1097 /// `set`. If `eat` is true, then `str` will be modified to trim off this
1098 /// returned prefix.
1100  string_view set, bool eat=true) noexcept;
1101 
1102 /// Return the prefix of str up to and including the first newline ('\n')
1103 /// character, or all of str if no newline is found within it. If `eat` is
1104 /// true, then `str` will be modified to trim off this returned prefix
1105 /// (including the newline character).
1106 string_view OIIO_UTIL_API parse_line(string_view& str, bool eat = true) noexcept;
1107 
1108 
1109 /// Assuming the string str starts with either '(', '[', or '{', return the
1110 /// head, up to and including the corresponding closing character (')', ']',
1111 /// or '}', respectively), recognizing nesting structures. For example,
1112 /// parse_nested("(a(b)c)d") should return "(a(b)c)", NOT "(a(b)". Return an
1113 /// empty string if str doesn't start with one of those characters, or
1114 /// doesn't contain a correctly matching nested pair. If eat==true, str will
1115 /// be modified to trim off the part of the string that is returned as the
1116 /// match.
1117 string_view OIIO_UTIL_API parse_nested (string_view &str, bool eat=true) noexcept;
1118 
1119 /// Does the string follow the lexical rule of a C identifier?
1120 inline bool
1122 {
1123  // If a leading identifier is the entirety of str, it's an ident.
1124  string_view ident = parse_identifier(str);
1125  return (!ident.empty() && str.empty());
1126 }
1127 
1128 /// Look within `str` for the pattern:
1129 /// head nonwhitespace_chars whitespace
1130 /// Remove that full pattern from `str` and return the nonwhitespace
1131 /// part that followed the head (or return the empty string and leave `str`
1132 /// unmodified, if the head was never found).
1133 OIIO_UTIL_API std::string
1134 excise_string_after_head (std::string& str, string_view head);
1135 
1136 
1137 /// Converts utf-8 string to vector of unicode codepoints. This function
1138 /// will not stop on invalid sequences. It will let through some invalid
1139 /// utf-8 sequences like: 0xfdd0-0xfdef, 0x??fffe/0x??ffff. It does not
1140 /// support 5-6 bytes long utf-8 sequences. Will skip trailing character if
1141 /// there are not enough bytes for decoding a codepoint.
1142 ///
1143 /// N.B. Following should probably return u32string instead of taking
1144 /// vector, but C++11 support is not yet stabilized across compilers.
1145 /// We will eventually add that and deprecate this one, after everybody
1146 /// is caught up to C++11.
1147 void OIIO_UTIL_API utf8_to_unicode (string_view str, std::vector<uint32_t> &uvec);
1148 
1149 /// Encode the string in base64.
1150 /// https://en.wikipedia.org/wiki/Base64
1151 std::string OIIO_UTIL_API base64_encode (string_view str);
1152 
1153 
1155 
1156 /// Compute an edit distance metric between strings `a` and `b`, roughly
1157 /// speaking, the number of changes that would be made to transform one string
1158 /// into the other. Identical strings have a distance of 0. The `method`
1159 /// selects among possible algorithms, which may have different distance
1160 /// metrics or allow different types of edits. (Currently, the only method
1161 /// supported is Levenshtein; this parameter is for future expansion.)
1162 OIIO_UTIL_API size_t
1165 
1166 
1167 /// Evaluate a string as a boolean value using the following heuristic:
1168 /// - If the string is a valid numeric value (represents an integer or
1169 /// floating point value), return true if it's non-zero, false if it's
1170 /// zero.
1171 /// - If the string is one of "false", "no", or "off", or if it contains
1172 /// only whitespace, return false.
1173 /// - All other non-empty strings return true.
1174 /// The comparisons are case-insensitive and ignore leading and trailing
1175 /// whitespace.
1176 OIIO_UTIL_API bool
1178 
1179 } // namespace Strutil
1180 
1181 
1182 // Bring the ever-useful Strutil::print into the OIIO namespace.
1183 using Strutil::print;
1184 
string_view safe_string_view(const char *str, size_t size) noexcept
Definition: strutil.h:920
type
Definition: core.h:556
uint64_t from_string< uint64_t >(string_view s)
Definition: strutil.h:693
GLint first
Definition: glcorearb.h:405
bool OIIO_UTIL_API parse_int(string_view &str, int &val, bool eat=true) noexcept
typedef int(APIENTRYP RE_PFNGLXSWAPINTERVALSGIPROC)(int)
bool string_is_identifier(string_view str)
Does the string follow the lexical rule of a C identifier?
Definition: strutil.h:1121
OIIO_FORMAT_DEPRECATED std::string format(const char *fmt, const Args &...args)
Definition: strutil.h:137
void printf(const char *fmt, const Args &...args)
Definition: strutil.h:174
std::string upper(string_view a)
Return an all-upper case version of a (locale-independent).
Definition: strutil.h:500
bool OIIO_UTIL_API iequals(string_view a, string_view b)
size_t operator()(string_view s) const
Definition: strutil.h:834
unsigned int from_string< unsigned int >(string_view s)
Definition: strutil.h:673
OIIO_UTIL_API bool scan_datetime(string_view str, int &year, int &month, int &day, int &hour, int &min, int &sec)
OIIO_UTIL_API std::vector< string_view > splitsv(string_view str, string_view sep="", int maxsplit=-1)
bool OIIO_UTIL_API parse_char(string_view &str, char c, bool skip_whitespace=true, bool eat=true) noexcept
OIIO_UTIL_API bool string_is_int(string_view s)
const GLdouble * v
Definition: glcorearb.h:837
GLsizei const GLfloat * value
Definition: glcorearb.h:824
void fprintf(FILE *file, const char *fmt, const Args &...args)
Definition: strutil.h:180
Definition: span.h:74
OIIO_UTIL_API unsigned int stoui(string_view s, size_t *pos=0, int base=10)
std::string to_string(const T &value)
Definition: strutil.h:706
OIIO_NODISCARD std::string format(const Str &fmt, Args &&...args)
Definition: strutil.h:128
size_t OIIO_UTIL_API irfind(string_view a, string_view b)
GLboolean GLboolean GLboolean GLboolean a
Definition: glcorearb.h:1222
GLdouble s
Definition: glad.h:3009
bool OIIO_UTIL_API istarts_with(string_view a, string_view b)
string_view OIIO_UTIL_API rstrip(string_view str, string_view chars=string_view())
OIIO_UTIL_API void debug(string_view str)
bool OIIO_UTIL_API ends_with(string_view a, string_view b)
Does 'a' end with the string 'b', with a case-sensitive comparison?
ImageBuf OIIO_API min(Image_or_Const A, Image_or_Const B, ROI roi={}, int nthreads=0)
#define OIIO_DEPRECATED(msg)
Definition: platform.h:466
**But if you need a result
Definition: thread.h:622
void print(std::ostream &file, const char *fmt, Args &&...args)
Definition: strutil.h:240
OIIO_UTIL_API size_t safe_strlen(const char *str, size_t size) noexcept
bool OIIO_UTIL_API iends_with(string_view a, string_view b)
bool OIIO_UTIL_API icontains(string_view a, string_view b)
#define OIIO_UTIL_API
Definition: export.h:71
std::string OIIO_UTIL_API escape_chars(string_view unescaped)
string_view OIIO_UTIL_API lstrip(string_view str, string_view chars=string_view())
string_view OIIO_UTIL_API parse_nested(string_view &str, bool eat=true) noexcept
bool OIIO_UTIL_API parse_string(string_view &str, string_view &val, bool eat=true, QuoteBehavior keep_quotes=DeleteQuotes) noexcept
OIIO_UTIL_API float stof(string_view s, size_t *pos=0)
basic_string_view< char > string_view
Definition: core.h:501
string_view OIIO_UTIL_API parse_line(string_view &str, bool eat=true) noexcept
OIIO_UTIL_API char * safe_strcpy(char *dst, string_view src, size_t size) noexcept
bool OIIO_UTIL_API iless(string_view a, string_view b)
constexpr size_t strhash(size_t len, const char *s)
Definition: strutil.h:373
GLdouble n
Definition: glcorearb.h:2008
int64_t from_string< int64_t >(string_view s)
Definition: strutil.h:687
OIIO_UTIL_API bool string_is_float(string_view s)
string_view OIIO_UTIL_API parse_while(string_view &str, string_view set, bool eat=true) noexcept
void OIIO_UTIL_API remove_trailing_whitespace(string_view &str) noexcept
std::string OIIO_UTIL_API vformat(const char *fmt, va_list ap)
static const size_type npos
Definition: string_view.h:95
std::string to_string(const char *value)
Definition: strutil.h:713
size_t OIIO_UTIL_API ifind(string_view a, string_view b)
void OIIO_UTIL_API sync_output(FILE *file, string_view str, bool flush=true)
void OIIO_UTIL_API to_lower(std::string &a)
Definition: Name.h:96
bool OIIO_UTIL_API parse_values(string_view &str, string_view prefix, span< int > values, string_view sep="", string_view postfix="", bool eat=true) noexcept
float from_string< float >(string_view s)
Definition: strutil.h:678
constexpr auto set(type rhs) -> int
Definition: core.h:610
size_t OIIO_UTIL_API rfind(string_view a, string_view b)
std::string OIIO_UTIL_API replace(string_view str, string_view pattern, string_view replacement, bool global=false)
bool OIIO_UTIL_API parse_float(string_view &str, float &val, bool eat=true) noexcept
float OIIO_UTIL_API strtof(const char *nptr, char **endptr=nullptr) noexcept
GLint GLint GLsizei GLint GLenum format
Definition: glcorearb.h:108
std::string OIIO_UTIL_API wordwrap(string_view src, int columns=80, int prefix=0, string_view sep=" ", string_view presep="")
std::string safe_string(const char *str, size_t size)
Definition: strutil.h:927
double from_string< double >(string_view s)
Definition: strutil.h:683
OIIO_UTIL_API double stod(string_view s, size_t *pos=0)
OIIO_UTIL_API int stoi(string_view s, size_t *pos=0, int base=10)
QuoteBehavior
Definition: strutil.h:1046
std::string OIIO_UTIL_API memformat(long long bytes, int digits=1)
OIIO_UTIL_API std::string excise_string_after_head(std::string &str, string_view head)
std::wstring OIIO_UTIL_API utf8_to_utf16(string_view utf8str) noexcept
GLushort pattern
Definition: glad.h:2583
string_view trimmed_whitespace(string_view str) noexcept
Definition: strutil.h:959
GLboolean GLboolean GLboolean b
Definition: glcorearb.h:1222
OIIO_UTIL_API char * safe_strcat(char *dst, string_view src, size_t size) noexcept
bool OIIO_UTIL_API contains_any_char(string_view a, string_view set)
Does 'a' contain any of the characters within set?
T from_string(string_view s)
Definition: strutil.h:663
bool isspace(char c)
Definition: strutil.h:938
GLdouble t
Definition: glad.h:2397
void debug(const char *fmt, Args &&...args)
Definition: strutil.h:293
void trim_whitespace(string_view &str) noexcept
Definition: strutil.h:952
constexpr uint64_t strhash64(size_t len, const char *s)
A guaranteed 64-bit string hash on all platforms.
Definition: strutil.h:381
size_t OIIO_UTIL_API find(string_view a, string_view b)
bool OIIO_UTIL_API parse_until_char(string_view &str, char c, bool eat=true) noexcept
#define OIIO_NODISCARD
Definition: platform.h:485
bool string_is(string_view)
Definition: strutil.h:720
constexpr auto size() const noexcept-> size_t
Definition: core.h:443
void print(FILE *file, const char *fmt, Args &&...args)
Definition: strutil.h:228
std::string OIIO_UTIL_API repeat(string_view str, int n)
Repeat a string formed by concatenating str n times.
constexpr auto make_format_args(T &&...args) -> format_arg_store< Context, remove_cvref_t< T >...>
Definition: core.h:1842
GLsizeiptr size
Definition: glcorearb.h:664
GLenum GLenum dst
Definition: glcorearb.h:1793
std::string OIIO_UTIL_API unescape_chars(string_view escaped)
std::string OIIO_UTIL_API base64_encode(string_view str)
std::string join(const Sequence &seq, string_view sep="")
Definition: strutil.h:552
GLenum GLsizei GLsizei GLint * values
Definition: glcorearb.h:1602
OIIO_UTIL_API size_t edit_distance(string_view a, string_view b, EditDistMetric metric=EditDistMetric::Levenshtein)
std::string lower(string_view a)
Return an all-upper case version of a (locale-independent).
Definition: strutil.h:493
int extract_from_list_string(std::vector< T, Allocator > &vals, string_view list, string_view sep=",")
Definition: strutil.h:752
STATIC_INLINE uint64_t Hash64(const char *s, size_t len)
Definition: farmhash.h:691
bool OIIO_UTIL_API starts_with(string_view a, string_view b)
Does 'a' start with the string 'b', with a case-sensitive comparison?
bool ircontains(string_view a, string_view b)
Definition: strutil.h:477
OIIO_UTIL_API std::vector< std::string > splits(string_view str, string_view sep="", int maxsplit=-1)
GLuint GLfloat * val
Definition: glcorearb.h:1608
bool string_is< int >(string_view s)
Definition: strutil.h:724
bool string_is< float >(string_view s)
Definition: strutil.h:729
void OIIO_UTIL_API skip_whitespace(string_view &str) noexcept
**If you just want to fire and args
Definition: thread.h:618
int from_string< int >(string_view s)
Definition: strutil.h:669
constexpr auto data() const noexcept-> const Char *
Definition: core.h:440
OIIO_UTIL_API const char * c_str(string_view str)
EditDistMetric
Definition: strutil.h:1154
OIIO_UTIL_API bool eval_as_bool(string_view value)
#define OIIO_FORMAT_DEPRECATED
Definition: strutil.h:50
std::string OIIO_UTIL_API vsprintf(const char *fmt, va_list ap)
string_view OIIO_UTIL_API parse_identifier(string_view &str, bool eat=true) noexcept
GLboolean r
Definition: glcorearb.h:1222
#define OIIO_NAMESPACE_END
Definition: oiioversion.h:127
auto sprintf(const S &fmt, const T &...args) -> std::basic_string< Char >
Definition: printf.h:617
string_view OIIO_UTIL_API strip(string_view str, string_view chars=string_view())
void OIIO_UTIL_API split(string_view str, std::vector< string_view > &result, string_view sep=string_view(), int maxsplit=-1)
C++ functor for comparing two strings for equality of their characters.
Definition: strutil.h:842
bool OIIO_UTIL_API get_rest_arguments(const std::string &str, std::string &base, std::map< std::string, std::string > &result)
constexpr bool empty() const noexcept
Is the basic_string_view empty, containing no characters?
Definition: string_view.h:209
bool scan_values(string_view str, string_view prefix, span< int > values, string_view sep="", string_view postfix="") noexcept
Definition: strutil.h:1031
std::string OIIO_UTIL_API utf16_to_utf8(const std::wstring &utf16str) noexcept
bool OIIO_UTIL_API contains(string_view a, string_view b)
Does 'a' contain the string 'b' within it?
void OIIO_UTIL_API utf8_to_unicode(string_view str, std::vector< uint32_t > &uvec)
void OIIO_UTIL_API to_upper(std::string &a)
std::string OIIO_UTIL_API concat(string_view s, string_view t)
string_view OIIO_UTIL_API parse_word(string_view &str, bool eat=true) noexcept
std::string OIIO_UTIL_API timeintervalformat(double secs, int digits=1)
C++ functor for comparing the ordering of two strings.
Definition: strutil.h:857
std::wstring OIIO_UTIL_API utf8_to_utf16wstring(string_view utf8str) noexcept
constexpr size_type length() const noexcept
Definition: string_view.h:204
Definition: format.h:4365
bool OIIO_UTIL_API parse_prefix(string_view &str, string_view prefix, bool eat=true) noexcept
bool rcontains(string_view a, string_view b)
Definition: strutil.h:469
string_view OIIO_UTIL_API parse_until(string_view &str, string_view set=" \t\r\n", bool eat=true) noexcept
#define OIIO_NAMESPACE_BEGIN
Definition: oiioversion.h:126
bool OIIO_UTIL_API parse_identifier_if(string_view &str, string_view id, bool eat=true) noexcept
GLenum src
Definition: glcorearb.h:1793
bool parse_value(string_view &str, float &val, bool eat=true) noexcept
Synonym for parse_int.
Definition: strutil.h:1000
double OIIO_UTIL_API strtod(const char *nptr, char **endptr=nullptr) noexcept