WPILibC++  2020.3.2-60-g3011ebe
StringExtras.h
1 //===- llvm/ADT/StringExtras.h - Useful string functions --------*- C++ -*-===//
2 //
3 // The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This file contains some functions that are useful when dealing with strings.
11 //
12 //===----------------------------------------------------------------------===//
13 
14 #ifndef WPIUTIL_WPI_STRINGEXTRAS_H
15 #define WPIUTIL_WPI_STRINGEXTRAS_H
16 
17 #include "wpi/ArrayRef.h"
18 #include "wpi/SmallString.h"
19 #include "wpi/StringRef.h"
20 #include "wpi/Twine.h"
21 #include <cassert>
22 #include <cstddef>
23 #include <cstdint>
24 #include <cstdlib>
25 #include <cstring>
26 #include <iterator>
27 #include <string>
28 #include <utility>
29 
30 namespace wpi {
31 
32 template<typename T> class SmallVectorImpl;
33 class raw_ostream;
34 
37 inline char hexdigit(unsigned X, bool LowerCase = false) {
38  const char HexChar = LowerCase ? 'a' : 'A';
39  return X < 10 ? '0' + X : HexChar + X - 10;
40 }
41 
43 inline StringRef toStringRef(bool B) { return StringRef(B ? "true" : "false"); }
44 
47  return StringRef(reinterpret_cast<const char *>(Input.begin()), Input.size());
48 }
49 
52  return {Input.bytes_begin(), Input.bytes_end()};
53 }
54 
59 inline unsigned hexDigitValue(char C) {
60  if (C >= '0' && C <= '9') return C-'0';
61  if (C >= 'a' && C <= 'f') return C-'a'+10U;
62  if (C >= 'A' && C <= 'F') return C-'A'+10U;
63  return (std::numeric_limits<unsigned>::max)();
64 }
65 
67 inline bool isDigit(char C) { return C >= '0' && C <= '9'; }
68 
70 inline bool isHexDigit(char C) { return hexDigitValue(C) != (std::numeric_limits<unsigned>::max)(); }
71 
73 inline bool isAlpha(char C) {
74  return ('a' <= C && C <= 'z') || ('A' <= C && C <= 'Z');
75 }
76 
79 inline bool isAlnum(char C) { return isAlpha(C) || isDigit(C); }
80 
82 inline bool isASCII(char C) { return static_cast<unsigned char>(C) <= 127; }
83 
85 inline bool isASCII(wpi::StringRef S) {
86  for (char C : S)
87  if (LLVM_UNLIKELY(!isASCII(C)))
88  return false;
89  return true;
90 }
91 
96 inline bool isPrint(char C) {
97  unsigned char UC = static_cast<unsigned char>(C);
98  return (0x20 <= UC) && (UC <= 0x7E);
99 }
100 
102 inline char toLower(char x) {
103  if (x >= 'A' && x <= 'Z')
104  return x - 'A' + 'a';
105  return x;
106 }
107 
109 inline char toUpper(char x) {
110  if (x >= 'a' && x <= 'z')
111  return x - 'a' + 'A';
112  return x;
113 }
114 
115 inline std::string utohexstr(uint64_t X, bool LowerCase = false) {
116  char Buffer[17];
117  char *BufPtr = std::end(Buffer);
118 
119  if (X == 0) *--BufPtr = '0';
120 
121  while (X) {
122  unsigned char Mod = static_cast<unsigned char>(X) & 15;
123  *--BufPtr = hexdigit(Mod, LowerCase);
124  X >>= 4;
125  }
126 
127  return std::string(BufPtr, std::end(Buffer));
128 }
129 
132 inline std::string toHex(StringRef Input, bool LowerCase = false) {
133  static const char *const LUT = "0123456789ABCDEF";
134  const uint8_t Offset = LowerCase ? 32 : 0;
135  size_t Length = Input.size();
136 
137  std::string Output;
138  Output.reserve(2 * Length);
139  for (size_t i = 0; i < Length; ++i) {
140  const unsigned char c = Input[i];
141  Output.push_back(LUT[c >> 4] | Offset);
142  Output.push_back(LUT[c & 15] | Offset);
143  }
144  return Output;
145 }
146 
147 inline std::string toHex(ArrayRef<uint8_t> Input, bool LowerCase = false) {
148  return toHex(toStringRef(Input), LowerCase);
149 }
150 
151 inline uint8_t hexFromNibbles(char MSB, char LSB) {
152  unsigned U1 = hexDigitValue(MSB);
153  unsigned U2 = hexDigitValue(LSB);
154  assert(U1 != (std::numeric_limits<unsigned>::max)() && U2 != (std::numeric_limits<unsigned>::max)());
155 
156  return static_cast<uint8_t>((U1 << 4) | U2);
157 }
158 
161 inline std::string fromHex(StringRef Input) {
162  if (Input.empty())
163  return std::string();
164 
165  std::string Output;
166  Output.reserve((Input.size() + 1) / 2);
167  if (Input.size() % 2 == 1) {
168  Output.push_back(hexFromNibbles('0', Input.front()));
169  Input = Input.drop_front();
170  }
171 
172  assert(Input.size() % 2 == 0);
173  while (!Input.empty()) {
174  uint8_t Hex = hexFromNibbles(Input[0], Input[1]);
175  Output.push_back(Hex);
176  Input = Input.drop_front(2);
177  }
178  return Output;
179 }
180 
184 template <typename N> bool to_integer(StringRef S, N &Num, unsigned Base = 0) {
185  return !S.getAsInteger(Base, Num);
186 }
187 
188 namespace detail {
189 template <typename N>
190 inline bool to_float(const Twine &T, N &Num, N (*StrTo)(const char *, char **)) {
191  SmallString<32> Storage;
192  StringRef S = T.toNullTerminatedStringRef(Storage);
193  char *End;
194  N Temp = StrTo(S.data(), &End);
195  if (*End != '\0')
196  return false;
197  Num = Temp;
198  return true;
199 }
200 }
201 
202 inline bool to_float(const Twine &T, float &Num) {
203  return detail::to_float(T, Num, strtof);
204 }
205 
206 inline bool to_float(const Twine &T, double &Num) {
207  return detail::to_float(T, Num, strtod);
208 }
209 
210 inline bool to_float(const Twine &T, long double &Num) {
211  return detail::to_float(T, Num, strtold);
212 }
213 
214 inline std::string utostr(uint64_t X, bool isNeg = false) {
215  char Buffer[21];
216  char *BufPtr = std::end(Buffer);
217 
218  if (X == 0) *--BufPtr = '0'; // Handle special case...
219 
220  while (X) {
221  *--BufPtr = '0' + char(X % 10);
222  X /= 10;
223  }
224 
225  if (isNeg) *--BufPtr = '-'; // Add negative sign...
226  return std::string(BufPtr, std::end(Buffer));
227 }
228 
229 inline std::string itostr(int64_t X) {
230  if (X < 0)
231  return utostr(static_cast<uint64_t>(-X), true);
232  else
233  return utostr(static_cast<uint64_t>(X));
234 }
235 
239 StringRef::size_type StrInStrNoCase(StringRef s1, StringRef s2);
240 
247 std::pair<StringRef, StringRef> getToken(StringRef Source,
248  StringRef Delimiters = " \t\n\v\f\r");
249 
252 void SplitString(StringRef Source,
253  SmallVectorImpl<StringRef> &OutFragments,
254  StringRef Delimiters = " \t\n\v\f\r");
255 
259 //
260 // FIXME: Investigate whether a modified bernstein hash function performs
261 // better: http://eternallyconfuzzled.com/tuts/algorithms/jsw_tut_hashing.aspx
262 // X*33+c -> X*33^c
263 static inline unsigned HashString(StringRef Str, unsigned Result = 0) {
264  for (StringRef::size_type i = 0, e = Str.size(); i != e; ++i)
265  Result = Result * 33 + (unsigned char)Str[i];
266  return Result;
267 }
268 
270 inline StringRef getOrdinalSuffix(unsigned Val) {
271  // It is critically important that we do this perfectly for
272  // user-written sequences with over 100 elements.
273  switch (Val % 100) {
274  case 11:
275  case 12:
276  case 13:
277  return "th";
278  default:
279  switch (Val % 10) {
280  case 1: return "st";
281  case 2: return "nd";
282  case 3: return "rd";
283  default: return "th";
284  }
285  }
286 }
287 
290 void printEscapedString(StringRef Name, raw_ostream &Out);
291 
294 void printHTMLEscaped(StringRef String, raw_ostream &Out);
295 
297 void printLowerCase(StringRef String, raw_ostream &Out);
298 
299 namespace detail {
300 
301 template <typename IteratorT>
302 inline std::string join_impl(IteratorT Begin, IteratorT End,
303  StringRef Separator, std::input_iterator_tag) {
304  std::string S;
305  if (Begin == End)
306  return S;
307 
308  S += (*Begin);
309  while (++Begin != End) {
310  S += Separator;
311  S += (*Begin);
312  }
313  return S;
314 }
315 
316 template <typename IteratorT>
317 inline std::string join_impl(IteratorT Begin, IteratorT End,
318  StringRef Separator, std::forward_iterator_tag) {
319  std::string S;
320  if (Begin == End)
321  return S;
322 
323  size_t Len = (std::distance(Begin, End) - 1) * Separator.size();
324  for (IteratorT I = Begin; I != End; ++I)
325  Len += (*Begin).size();
326  S.reserve(Len);
327  S += (*Begin);
328  while (++Begin != End) {
329  S += Separator;
330  S += (*Begin);
331  }
332  return S;
333 }
334 
335 template <typename Sep>
336 inline void join_items_impl(std::string &Result, Sep Separator) {}
337 
338 template <typename Sep, typename Arg>
339 inline void join_items_impl(std::string &Result, Sep Separator,
340  const Arg &Item) {
341  Result += Item;
342 }
343 
344 template <typename Sep, typename Arg1, typename... Args>
345 inline void join_items_impl(std::string &Result, Sep Separator, const Arg1 &A1,
346  Args &&... Items) {
347  Result += A1;
348  Result += Separator;
349  join_items_impl(Result, Separator, std::forward<Args>(Items)...);
350 }
351 
352 inline size_t join_one_item_size(char C) { return 1; }
353 inline size_t join_one_item_size(const char *S) { return S ? ::strlen(S) : 0; }
354 
355 template <typename T> inline size_t join_one_item_size(const T &Str) {
356  return Str.size();
357 }
358 
359 inline size_t join_items_size() { return 0; }
360 
361 template <typename A1> inline size_t join_items_size(const A1 &A) {
362  return join_one_item_size(A);
363 }
364 template <typename A1, typename... Args>
365 inline size_t join_items_size(const A1 &A, Args &&... Items) {
366  return join_one_item_size(A) + join_items_size(std::forward<Args>(Items)...);
367 }
368 
369 } // end namespace detail
370 
373 template <typename IteratorT>
374 inline std::string join(IteratorT Begin, IteratorT End, StringRef Separator) {
375  using tag = typename std::iterator_traits<IteratorT>::iterator_category;
376  return detail::join_impl(Begin, End, Separator, tag());
377 }
378 
381 template <typename Range>
382 inline std::string join(Range &&R, StringRef Separator) {
383  return join(R.begin(), R.end(), Separator);
384 }
385 
390 template <typename Sep, typename... Args>
391 inline std::string join_items(Sep Separator, Args &&... Items) {
392  std::string Result;
393  if (sizeof...(Items) == 0)
394  return Result;
395 
396  size_t NS = detail::join_one_item_size(Separator);
397  size_t NI = detail::join_items_size(std::forward<Args>(Items)...);
398  Result.reserve(NI + (sizeof...(Items) - 1) * NS + 1);
399  detail::join_items_impl(Result, Separator, std::forward<Args>(Items)...);
400  return Result;
401 }
402 
403 } // end namespace wpi
404 
405 #endif // WPIUTIL_WPI_STRINGEXTRAS_H
wpi::StringRef::empty
LLVM_NODISCARD LLVM_ATTRIBUTE_ALWAYS_INLINE bool empty() const noexcept
empty - Check if the string is empty.
Definition: StringRef.h:133
wpi::toStringRef
StringRef toStringRef(bool B)
Construct a string ref from a boolean.
Definition: StringExtras.h:43
wpi::ArrayRef< uint8_t >
wpi::StringRef::size
LLVM_NODISCARD LLVM_ATTRIBUTE_ALWAYS_INLINE size_t size() const noexcept
size - Get the string size.
Definition: StringRef.h:138
wpi::SmallVectorImpl
This class consists of common code factored out of the SmallVector class to reduce code duplication b...
Definition: StringExtras.h:32
wpi::to_integer
bool to_integer(StringRef S, N &Num, unsigned Base=0)
Convert the string S to an integer of the specified type using the radix Base.
Definition: StringExtras.h:184
wpi::isASCII
bool isASCII(char C)
Checks whether character C is valid ASCII (high bit is zero).
Definition: StringExtras.h:82
wpi::StrInStrNoCase
StringRef::size_type StrInStrNoCase(StringRef s1, StringRef s2)
StrInStrNoCase - Portable version of strcasestr.
wpi::detail::value_t::string
string value
wpi::isAlpha
bool isAlpha(char C)
Checks if character C is a valid letter as classified by "C" locale.
Definition: StringExtras.h:73
wpi::HashString
static unsigned HashString(StringRef Str, unsigned Result=0)
HashString - Hash function for strings.
Definition: StringExtras.h:263
wpi::isDigit
bool isDigit(char C)
Checks if character C is one of the 10 decimal digits.
Definition: StringExtras.h:67
wpi::isPrint
bool isPrint(char C)
Checks whether character C is printable.
Definition: StringExtras.h:96
wpi::getOrdinalSuffix
StringRef getOrdinalSuffix(unsigned Val)
Returns the English suffix for an ordinal integer (-st, -nd, -rd, -th).
Definition: StringExtras.h:270
wpi::getToken
std::pair< StringRef, StringRef > getToken(StringRef Source, StringRef Delimiters=" \t\n\v\f\r")
getToken - This function extracts one token from source, ignoring any leading characters that appear ...
wpi
WPILib C++ utilities (wpiutil) namespace.
Definition: Endian.h:31
wpi::hexdigit
char hexdigit(unsigned X, bool LowerCase=false)
hexdigit - Return the hexadecimal character for the given number X (which should be less than 16).
Definition: StringExtras.h:37
wpi::SmallString< 32 >
wpi::printLowerCase
void printLowerCase(StringRef String, raw_ostream &Out)
printLowerCase - Print each character as lowercase if it is uppercase.
wpi::hexDigitValue
unsigned hexDigitValue(char C)
Interpret the given character C as a hexadecimal digit and return its value.
Definition: StringExtras.h:59
wpi::toLower
char toLower(char x)
Returns the corresponding lowercase character if x is uppercase.
Definition: StringExtras.h:102
wpi::Twine::toNullTerminatedStringRef
StringRef toNullTerminatedStringRef(SmallVectorImpl< char > &Out) const
This returns the twine as a single null terminated StringRef if it can be represented as such.
wpi::StringRef
StringRef - Represent a constant reference to a string, i.e.
Definition: StringRef.h:49
wpi::ArrayRef::size
size_t size() const
size - Get the array size.
Definition: ArrayRef.h:145
wpi::printHTMLEscaped
void printHTMLEscaped(StringRef String, raw_ostream &Out)
Print each character of the specified string, escaping HTML special characters.
wpi::join
std::string join(IteratorT Begin, IteratorT End, StringRef Separator)
Joins the strings in the range [Begin, End), adding Separator between the elements.
Definition: StringExtras.h:374
wpi::isAlnum
bool isAlnum(char C)
Checks whether character C is either a decimal digit or an uppercase or lowercase letter as classifie...
Definition: StringExtras.h:79
wpi::StringRef::front
LLVM_NODISCARD char front() const noexcept
front - Get the first character in the string.
Definition: StringRef.h:142
wpi::arrayRefFromStringRef
ArrayRef< uint8_t > arrayRefFromStringRef(StringRef Input)
Construct a string ref from an array ref of unsigned chars.
Definition: StringExtras.h:51
wpi::SplitString
void SplitString(StringRef Source, SmallVectorImpl< StringRef > &OutFragments, StringRef Delimiters=" \t\n\v\f\r")
SplitString - Split up the specified string according to the specified delimiters,...
wpi::toHex
std::string toHex(StringRef Input, bool LowerCase=false)
Convert buffer Input to its hexadecimal representation.
Definition: StringExtras.h:132
wpi::join_items
std::string join_items(Sep Separator, Args &&... Items)
Joins the strings in the parameter pack Items, adding Separator between the elements.
Definition: StringExtras.h:391
wpi::raw_ostream
This class implements an extremely fast bulk output stream that can only output to a stream.
Definition: raw_ostream.h:47
wpi::printEscapedString
void printEscapedString(StringRef Name, raw_ostream &Out)
Print each character of the specified string, escaping it if it is not printable or if it is an escap...
wpi::Twine
Twine - A lightweight data structure for efficiently representing the concatenation of temporary valu...
Definition: Twine.h:85
wpi::toUpper
char toUpper(char x)
Returns the corresponding uppercase character if x is lowercase.
Definition: StringExtras.h:109
wpi::fromHex
std::string fromHex(StringRef Input)
Convert hexadecimal string Input to its binary representation.
Definition: StringExtras.h:161
wpi::StringRef::drop_front
LLVM_NODISCARD LLVM_ATTRIBUTE_ALWAYS_INLINE StringRef drop_front(size_t N=1) const noexcept
Return a StringRef equal to 'this' but with the first N elements dropped.
Definition: StringRef.h:603
wpi::isHexDigit
bool isHexDigit(char C)
Checks if character C is a hexadecimal numeric character.
Definition: StringExtras.h:70