StringExtras.h 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494
  1. //===- llvm/ADT/StringExtras.h - Useful string functions --------*- C++ -*-===//
  2. //
  3. // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
  4. // See https://llvm.org/LICENSE.txt for license information.
  5. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
  6. //
  7. //===----------------------------------------------------------------------===//
  8. //
  9. // This file contains some functions that are useful when dealing with strings.
  10. //
  11. //===----------------------------------------------------------------------===//
  12. #ifndef LLVM_ADT_STRINGEXTRAS_H
  13. #define LLVM_ADT_STRINGEXTRAS_H
  14. #include "llvm/ADT/ArrayRef.h"
  15. #include "llvm/ADT/SmallString.h"
  16. #include "llvm/ADT/StringRef.h"
  17. #include "llvm/ADT/Twine.h"
  18. #include <cassert>
  19. #include <cstddef>
  20. #include <cstdint>
  21. #include <cstdlib>
  22. #include <cstring>
  23. #include <iterator>
  24. #include <string>
  25. #include <utility>
  26. namespace llvm {
  27. template<typename T> class SmallVectorImpl;
  28. class raw_ostream;
  29. /// hexdigit - Return the hexadecimal character for the
  30. /// given number \p X (which should be less than 16).
  31. inline char hexdigit(unsigned X, bool LowerCase = false) {
  32. const char HexChar = LowerCase ? 'a' : 'A';
  33. return X < 10 ? '0' + X : HexChar + X - 10;
  34. }
  35. /// Given an array of c-style strings terminated by a null pointer, construct
  36. /// a vector of StringRefs representing the same strings without the terminating
  37. /// null string.
  38. inline std::vector<StringRef> toStringRefArray(const char *const *Strings) {
  39. std::vector<StringRef> Result;
  40. while (*Strings)
  41. Result.push_back(*Strings++);
  42. return Result;
  43. }
  44. /// Construct a string ref from a boolean.
  45. inline StringRef toStringRef(bool B) { return StringRef(B ? "true" : "false"); }
  46. /// Construct a string ref from an array ref of unsigned chars.
  47. inline StringRef toStringRef(ArrayRef<uint8_t> Input) {
  48. return StringRef(reinterpret_cast<const char *>(Input.begin()), Input.size());
  49. }
  50. /// Construct a string ref from an array ref of unsigned chars.
  51. inline ArrayRef<uint8_t> arrayRefFromStringRef(StringRef Input) {
  52. return {Input.bytes_begin(), Input.bytes_end()};
  53. }
  54. /// Interpret the given character \p C as a hexadecimal digit and return its
  55. /// value.
  56. ///
  57. /// If \p C is not a valid hex digit, -1U is returned.
  58. inline unsigned hexDigitValue(char C) {
  59. struct HexTable {
  60. unsigned LUT[255] = {};
  61. constexpr HexTable() {
  62. // Default initialize everything to invalid.
  63. for (int i = 0; i < 255; ++i)
  64. LUT[i] = ~0U;
  65. // Initialize `0`-`9`.
  66. for (int i = 0; i < 10; ++i)
  67. LUT['0' + i] = i;
  68. // Initialize `A`-`F` and `a`-`f`.
  69. for (int i = 0; i < 6; ++i)
  70. LUT['A' + i] = LUT['a' + i] = 10 + i;
  71. }
  72. };
  73. constexpr HexTable Table;
  74. return Table.LUT[static_cast<unsigned char>(C)];
  75. }
  76. /// Checks if character \p C is one of the 10 decimal digits.
  77. inline bool isDigit(char C) { return C >= '0' && C <= '9'; }
  78. /// Checks if character \p C is a hexadecimal numeric character.
  79. inline bool isHexDigit(char C) { return hexDigitValue(C) != ~0U; }
  80. /// Checks if character \p C is a valid letter as classified by "C" locale.
  81. inline bool isAlpha(char C) {
  82. return ('a' <= C && C <= 'z') || ('A' <= C && C <= 'Z');
  83. }
  84. /// Checks whether character \p C is either a decimal digit or an uppercase or
  85. /// lowercase letter as classified by "C" locale.
  86. inline bool isAlnum(char C) { return isAlpha(C) || isDigit(C); }
  87. /// Checks whether character \p C is valid ASCII (high bit is zero).
  88. inline bool isASCII(char C) { return static_cast<unsigned char>(C) <= 127; }
  89. /// Checks whether all characters in S are ASCII.
  90. inline bool isASCII(llvm::StringRef S) {
  91. for (char C : S)
  92. if (LLVM_UNLIKELY(!isASCII(C)))
  93. return false;
  94. return true;
  95. }
  96. /// Checks whether character \p C is printable.
  97. ///
  98. /// Locale-independent version of the C standard library isprint whose results
  99. /// may differ on different platforms.
  100. inline bool isPrint(char C) {
  101. unsigned char UC = static_cast<unsigned char>(C);
  102. return (0x20 <= UC) && (UC <= 0x7E);
  103. }
  104. /// Checks whether character \p C is whitespace in the "C" locale.
  105. ///
  106. /// Locale-independent version of the C standard library isspace.
  107. inline bool isSpace(char C) {
  108. return C == ' ' || C == '\f' || C == '\n' || C == '\r' || C == '\t' ||
  109. C == '\v';
  110. }
  111. /// Returns the corresponding lowercase character if \p x is uppercase.
  112. inline char toLower(char x) {
  113. if (x >= 'A' && x <= 'Z')
  114. return x - 'A' + 'a';
  115. return x;
  116. }
  117. /// Returns the corresponding uppercase character if \p x is lowercase.
  118. inline char toUpper(char x) {
  119. if (x >= 'a' && x <= 'z')
  120. return x - 'a' + 'A';
  121. return x;
  122. }
  123. inline std::string utohexstr(uint64_t X, bool LowerCase = false) {
  124. char Buffer[17];
  125. char *BufPtr = std::end(Buffer);
  126. if (X == 0) *--BufPtr = '0';
  127. while (X) {
  128. unsigned char Mod = static_cast<unsigned char>(X) & 15;
  129. *--BufPtr = hexdigit(Mod, LowerCase);
  130. X >>= 4;
  131. }
  132. return std::string(BufPtr, std::end(Buffer));
  133. }
  134. /// Convert buffer \p Input to its hexadecimal representation.
  135. /// The returned string is double the size of \p Input.
  136. inline std::string toHex(StringRef Input, bool LowerCase = false) {
  137. static const char *const LUT = "0123456789ABCDEF";
  138. const uint8_t Offset = LowerCase ? 32 : 0;
  139. size_t Length = Input.size();
  140. std::string Output;
  141. Output.reserve(2 * Length);
  142. for (size_t i = 0; i < Length; ++i) {
  143. const unsigned char c = Input[i];
  144. Output.push_back(LUT[c >> 4] | Offset);
  145. Output.push_back(LUT[c & 15] | Offset);
  146. }
  147. return Output;
  148. }
  149. inline std::string toHex(ArrayRef<uint8_t> Input, bool LowerCase = false) {
  150. return toHex(toStringRef(Input), LowerCase);
  151. }
  152. /// Store the binary representation of the two provided values, \p MSB and
  153. /// \p LSB, that make up the nibbles of a hexadecimal digit. If \p MSB or \p LSB
  154. /// do not correspond to proper nibbles of a hexadecimal digit, this method
  155. /// returns false. Otherwise, returns true.
  156. inline bool tryGetHexFromNibbles(char MSB, char LSB, uint8_t &Hex) {
  157. unsigned U1 = hexDigitValue(MSB);
  158. unsigned U2 = hexDigitValue(LSB);
  159. if (U1 == ~0U || U2 == ~0U)
  160. return false;
  161. Hex = static_cast<uint8_t>((U1 << 4) | U2);
  162. return true;
  163. }
  164. /// Return the binary representation of the two provided values, \p MSB and
  165. /// \p LSB, that make up the nibbles of a hexadecimal digit.
  166. inline uint8_t hexFromNibbles(char MSB, char LSB) {
  167. uint8_t Hex = 0;
  168. bool GotHex = tryGetHexFromNibbles(MSB, LSB, Hex);
  169. (void)GotHex;
  170. assert(GotHex && "MSB and/or LSB do not correspond to hex digits");
  171. return Hex;
  172. }
  173. /// Convert hexadecimal string \p Input to its binary representation and store
  174. /// the result in \p Output. Returns true if the binary representation could be
  175. /// converted from the hexadecimal string. Returns false if \p Input contains
  176. /// non-hexadecimal digits. The output string is half the size of \p Input.
  177. inline bool tryGetFromHex(StringRef Input, std::string &Output) {
  178. if (Input.empty())
  179. return true;
  180. Output.reserve((Input.size() + 1) / 2);
  181. if (Input.size() % 2 == 1) {
  182. uint8_t Hex = 0;
  183. if (!tryGetHexFromNibbles('0', Input.front(), Hex))
  184. return false;
  185. Output.push_back(Hex);
  186. Input = Input.drop_front();
  187. }
  188. assert(Input.size() % 2 == 0);
  189. while (!Input.empty()) {
  190. uint8_t Hex = 0;
  191. if (!tryGetHexFromNibbles(Input[0], Input[1], Hex))
  192. return false;
  193. Output.push_back(Hex);
  194. Input = Input.drop_front(2);
  195. }
  196. return true;
  197. }
  198. /// Convert hexadecimal string \p Input to its binary representation.
  199. /// The return string is half the size of \p Input.
  200. inline std::string fromHex(StringRef Input) {
  201. std::string Hex;
  202. bool GotHex = tryGetFromHex(Input, Hex);
  203. (void)GotHex;
  204. assert(GotHex && "Input contains non hex digits");
  205. return Hex;
  206. }
  207. /// Convert the string \p S to an integer of the specified type using
  208. /// the radix \p Base. If \p Base is 0, auto-detects the radix.
  209. /// Returns true if the number was successfully converted, false otherwise.
  210. template <typename N> bool to_integer(StringRef S, N &Num, unsigned Base = 0) {
  211. return !S.getAsInteger(Base, Num);
  212. }
  213. namespace detail {
  214. template <typename N>
  215. inline bool to_float(const Twine &T, N &Num, N (*StrTo)(const char *, char **)) {
  216. SmallString<32> Storage;
  217. StringRef S = T.toNullTerminatedStringRef(Storage);
  218. char *End;
  219. N Temp = StrTo(S.data(), &End);
  220. if (*End != '\0')
  221. return false;
  222. Num = Temp;
  223. return true;
  224. }
  225. }
  226. inline bool to_float(const Twine &T, float &Num) {
  227. return detail::to_float(T, Num, strtof);
  228. }
  229. inline bool to_float(const Twine &T, double &Num) {
  230. return detail::to_float(T, Num, strtod);
  231. }
  232. inline bool to_float(const Twine &T, long double &Num) {
  233. return detail::to_float(T, Num, strtold);
  234. }
  235. inline std::string utostr(uint64_t X, bool isNeg = false) {
  236. char Buffer[21];
  237. char *BufPtr = std::end(Buffer);
  238. if (X == 0) *--BufPtr = '0'; // Handle special case...
  239. while (X) {
  240. *--BufPtr = '0' + char(X % 10);
  241. X /= 10;
  242. }
  243. if (isNeg) *--BufPtr = '-'; // Add negative sign...
  244. return std::string(BufPtr, std::end(Buffer));
  245. }
  246. inline std::string itostr(int64_t X) {
  247. if (X < 0)
  248. return utostr(static_cast<uint64_t>(1) + ~static_cast<uint64_t>(X), true);
  249. else
  250. return utostr(static_cast<uint64_t>(X));
  251. }
  252. /// StrInStrNoCase - Portable version of strcasestr. Locates the first
  253. /// occurrence of string 's1' in string 's2', ignoring case. Returns
  254. /// the offset of s2 in s1 or npos if s2 cannot be found.
  255. StringRef::size_type StrInStrNoCase(StringRef s1, StringRef s2);
  256. /// getToken - This function extracts one token from source, ignoring any
  257. /// leading characters that appear in the Delimiters string, and ending the
  258. /// token at any of the characters that appear in the Delimiters string. If
  259. /// there are no tokens in the source string, an empty string is returned.
  260. /// The function returns a pair containing the extracted token and the
  261. /// remaining tail string.
  262. std::pair<StringRef, StringRef> getToken(StringRef Source,
  263. StringRef Delimiters = " \t\n\v\f\r");
  264. /// SplitString - Split up the specified string according to the specified
  265. /// delimiters, appending the result fragments to the output list.
  266. void SplitString(StringRef Source,
  267. SmallVectorImpl<StringRef> &OutFragments,
  268. StringRef Delimiters = " \t\n\v\f\r");
  269. /// Returns the English suffix for an ordinal integer (-st, -nd, -rd, -th).
  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. /// Print each character of the specified string, escaping it if it is not
  288. /// printable or if it is an escape char.
  289. void printEscapedString(StringRef Name, raw_ostream &Out);
  290. /// Print each character of the specified string, escaping HTML special
  291. /// characters.
  292. void printHTMLEscaped(StringRef String, raw_ostream &Out);
  293. /// printLowerCase - Print each character as lowercase if it is uppercase.
  294. void printLowerCase(StringRef String, raw_ostream &Out);
  295. /// Converts a string from camel-case to snake-case by replacing all uppercase
  296. /// letters with '_' followed by the letter in lowercase, except if the
  297. /// uppercase letter is the first character of the string.
  298. std::string convertToSnakeFromCamelCase(StringRef input);
  299. /// Converts a string from snake-case to camel-case by replacing all occurrences
  300. /// of '_' followed by a lowercase letter with the letter in uppercase.
  301. /// Optionally allow capitalization of the first letter (if it is a lowercase
  302. /// letter)
  303. std::string convertToCamelFromSnakeCase(StringRef input,
  304. bool capitalizeFirst = false);
  305. namespace detail {
  306. template <typename IteratorT>
  307. inline std::string join_impl(IteratorT Begin, IteratorT End,
  308. StringRef Separator, std::input_iterator_tag) {
  309. std::string S;
  310. if (Begin == End)
  311. return S;
  312. S += (*Begin);
  313. while (++Begin != End) {
  314. S += Separator;
  315. S += (*Begin);
  316. }
  317. return S;
  318. }
  319. template <typename IteratorT>
  320. inline std::string join_impl(IteratorT Begin, IteratorT End,
  321. StringRef Separator, std::forward_iterator_tag) {
  322. std::string S;
  323. if (Begin == End)
  324. return S;
  325. size_t Len = (std::distance(Begin, End) - 1) * Separator.size();
  326. for (IteratorT I = Begin; I != End; ++I)
  327. Len += (*I).size();
  328. S.reserve(Len);
  329. size_t PrevCapacity = S.capacity();
  330. (void)PrevCapacity;
  331. S += (*Begin);
  332. while (++Begin != End) {
  333. S += Separator;
  334. S += (*Begin);
  335. }
  336. assert(PrevCapacity == S.capacity() && "String grew during building");
  337. return S;
  338. }
  339. template <typename Sep>
  340. inline void join_items_impl(std::string &Result, Sep Separator) {}
  341. template <typename Sep, typename Arg>
  342. inline void join_items_impl(std::string &Result, Sep Separator,
  343. const Arg &Item) {
  344. Result += Item;
  345. }
  346. template <typename Sep, typename Arg1, typename... Args>
  347. inline void join_items_impl(std::string &Result, Sep Separator, const Arg1 &A1,
  348. Args &&... Items) {
  349. Result += A1;
  350. Result += Separator;
  351. join_items_impl(Result, Separator, std::forward<Args>(Items)...);
  352. }
  353. inline size_t join_one_item_size(char) { return 1; }
  354. inline size_t join_one_item_size(const char *S) { return S ? ::strlen(S) : 0; }
  355. template <typename T> inline size_t join_one_item_size(const T &Str) {
  356. return Str.size();
  357. }
  358. inline size_t join_items_size() { return 0; }
  359. template <typename A1> inline size_t join_items_size(const A1 &A) {
  360. return join_one_item_size(A);
  361. }
  362. template <typename A1, typename... Args>
  363. inline size_t join_items_size(const A1 &A, Args &&... Items) {
  364. return join_one_item_size(A) + join_items_size(std::forward<Args>(Items)...);
  365. }
  366. } // end namespace detail
  367. /// Joins the strings in the range [Begin, End), adding Separator between
  368. /// the elements.
  369. template <typename IteratorT>
  370. inline std::string join(IteratorT Begin, IteratorT End, StringRef Separator) {
  371. using tag = typename std::iterator_traits<IteratorT>::iterator_category;
  372. return detail::join_impl(Begin, End, Separator, tag());
  373. }
  374. /// Joins the strings in the range [R.begin(), R.end()), adding Separator
  375. /// between the elements.
  376. template <typename Range>
  377. inline std::string join(Range &&R, StringRef Separator) {
  378. return join(R.begin(), R.end(), Separator);
  379. }
  380. /// Joins the strings in the parameter pack \p Items, adding \p Separator
  381. /// between the elements. All arguments must be implicitly convertible to
  382. /// std::string, or there should be an overload of std::string::operator+=()
  383. /// that accepts the argument explicitly.
  384. template <typename Sep, typename... Args>
  385. inline std::string join_items(Sep Separator, Args &&... Items) {
  386. std::string Result;
  387. if (sizeof...(Items) == 0)
  388. return Result;
  389. size_t NS = detail::join_one_item_size(Separator);
  390. size_t NI = detail::join_items_size(std::forward<Args>(Items)...);
  391. Result.reserve(NI + (sizeof...(Items) - 1) * NS + 1);
  392. detail::join_items_impl(Result, Separator, std::forward<Args>(Items)...);
  393. return Result;
  394. }
  395. /// A helper class to return the specified delimiter string after the first
  396. /// invocation of operator StringRef(). Used to generate a comma-separated
  397. /// list from a loop like so:
  398. ///
  399. /// \code
  400. /// ListSeparator LS;
  401. /// for (auto &I : C)
  402. /// OS << LS << I.getName();
  403. /// \end
  404. class ListSeparator {
  405. bool First = true;
  406. StringRef Separator;
  407. public:
  408. ListSeparator(StringRef Separator = ", ") : Separator(Separator) {}
  409. operator StringRef() {
  410. if (First) {
  411. First = false;
  412. return {};
  413. }
  414. return Separator;
  415. }
  416. };
  417. } // end namespace llvm
  418. #endif // LLVM_ADT_STRINGEXTRAS_H