PageRenderTime 97ms CodeModel.GetById 53ms RepoModel.GetById 4ms app.codeStats 0ms

/contrib/llvm/include/llvm/ADT/StringExtras.h

https://bitbucket.org/freebsd/freebsd-base
C Header | 401 lines | 264 code | 67 blank | 70 comment | 53 complexity | c6dca8a4da995deb1ae4453632f478ab MD5 | raw file
  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. if (C >= '0' && C <= '9') return C-'0';
  60. if (C >= 'a' && C <= 'f') return C-'a'+10U;
  61. if (C >= 'A' && C <= 'F') return C-'A'+10U;
  62. return -1U;
  63. }
  64. /// Checks if character \p C is one of the 10 decimal digits.
  65. inline bool isDigit(char C) { return C >= '0' && C <= '9'; }
  66. /// Checks if character \p C is a hexadecimal numeric character.
  67. inline bool isHexDigit(char C) { return hexDigitValue(C) != -1U; }
  68. /// Checks if character \p C is a valid letter as classified by "C" locale.
  69. inline bool isAlpha(char C) {
  70. return ('a' <= C && C <= 'z') || ('A' <= C && C <= 'Z');
  71. }
  72. /// Checks whether character \p C is either a decimal digit or an uppercase or
  73. /// lowercase letter as classified by "C" locale.
  74. inline bool isAlnum(char C) { return isAlpha(C) || isDigit(C); }
  75. /// Checks whether character \p C is valid ASCII (high bit is zero).
  76. inline bool isASCII(char C) { return static_cast<unsigned char>(C) <= 127; }
  77. /// Checks whether all characters in S are ASCII.
  78. inline bool isASCII(llvm::StringRef S) {
  79. for (char C : S)
  80. if (LLVM_UNLIKELY(!isASCII(C)))
  81. return false;
  82. return true;
  83. }
  84. /// Checks whether character \p C is printable.
  85. ///
  86. /// Locale-independent version of the C standard library isprint whose results
  87. /// may differ on different platforms.
  88. inline bool isPrint(char C) {
  89. unsigned char UC = static_cast<unsigned char>(C);
  90. return (0x20 <= UC) && (UC <= 0x7E);
  91. }
  92. /// Returns the corresponding lowercase character if \p x is uppercase.
  93. inline char toLower(char x) {
  94. if (x >= 'A' && x <= 'Z')
  95. return x - 'A' + 'a';
  96. return x;
  97. }
  98. /// Returns the corresponding uppercase character if \p x is lowercase.
  99. inline char toUpper(char x) {
  100. if (x >= 'a' && x <= 'z')
  101. return x - 'a' + 'A';
  102. return x;
  103. }
  104. inline std::string utohexstr(uint64_t X, bool LowerCase = false) {
  105. char Buffer[17];
  106. char *BufPtr = std::end(Buffer);
  107. if (X == 0) *--BufPtr = '0';
  108. while (X) {
  109. unsigned char Mod = static_cast<unsigned char>(X) & 15;
  110. *--BufPtr = hexdigit(Mod, LowerCase);
  111. X >>= 4;
  112. }
  113. return std::string(BufPtr, std::end(Buffer));
  114. }
  115. /// Convert buffer \p Input to its hexadecimal representation.
  116. /// The returned string is double the size of \p Input.
  117. inline std::string toHex(StringRef Input, bool LowerCase = false) {
  118. static const char *const LUT = "0123456789ABCDEF";
  119. const uint8_t Offset = LowerCase ? 32 : 0;
  120. size_t Length = Input.size();
  121. std::string Output;
  122. Output.reserve(2 * Length);
  123. for (size_t i = 0; i < Length; ++i) {
  124. const unsigned char c = Input[i];
  125. Output.push_back(LUT[c >> 4] | Offset);
  126. Output.push_back(LUT[c & 15] | Offset);
  127. }
  128. return Output;
  129. }
  130. inline std::string toHex(ArrayRef<uint8_t> Input, bool LowerCase = false) {
  131. return toHex(toStringRef(Input), LowerCase);
  132. }
  133. inline uint8_t hexFromNibbles(char MSB, char LSB) {
  134. unsigned U1 = hexDigitValue(MSB);
  135. unsigned U2 = hexDigitValue(LSB);
  136. assert(U1 != -1U && U2 != -1U);
  137. return static_cast<uint8_t>((U1 << 4) | U2);
  138. }
  139. /// Convert hexadecimal string \p Input to its binary representation.
  140. /// The return string is half the size of \p Input.
  141. inline std::string fromHex(StringRef Input) {
  142. if (Input.empty())
  143. return std::string();
  144. std::string Output;
  145. Output.reserve((Input.size() + 1) / 2);
  146. if (Input.size() % 2 == 1) {
  147. Output.push_back(hexFromNibbles('0', Input.front()));
  148. Input = Input.drop_front();
  149. }
  150. assert(Input.size() % 2 == 0);
  151. while (!Input.empty()) {
  152. uint8_t Hex = hexFromNibbles(Input[0], Input[1]);
  153. Output.push_back(Hex);
  154. Input = Input.drop_front(2);
  155. }
  156. return Output;
  157. }
  158. /// Convert the string \p S to an integer of the specified type using
  159. /// the radix \p Base. If \p Base is 0, auto-detects the radix.
  160. /// Returns true if the number was successfully converted, false otherwise.
  161. template <typename N> bool to_integer(StringRef S, N &Num, unsigned Base = 0) {
  162. return !S.getAsInteger(Base, Num);
  163. }
  164. namespace detail {
  165. template <typename N>
  166. inline bool to_float(const Twine &T, N &Num, N (*StrTo)(const char *, char **)) {
  167. SmallString<32> Storage;
  168. StringRef S = T.toNullTerminatedStringRef(Storage);
  169. char *End;
  170. N Temp = StrTo(S.data(), &End);
  171. if (*End != '\0')
  172. return false;
  173. Num = Temp;
  174. return true;
  175. }
  176. }
  177. inline bool to_float(const Twine &T, float &Num) {
  178. return detail::to_float(T, Num, strtof);
  179. }
  180. inline bool to_float(const Twine &T, double &Num) {
  181. return detail::to_float(T, Num, strtod);
  182. }
  183. inline bool to_float(const Twine &T, long double &Num) {
  184. return detail::to_float(T, Num, strtold);
  185. }
  186. inline std::string utostr(uint64_t X, bool isNeg = false) {
  187. char Buffer[21];
  188. char *BufPtr = std::end(Buffer);
  189. if (X == 0) *--BufPtr = '0'; // Handle special case...
  190. while (X) {
  191. *--BufPtr = '0' + char(X % 10);
  192. X /= 10;
  193. }
  194. if (isNeg) *--BufPtr = '-'; // Add negative sign...
  195. return std::string(BufPtr, std::end(Buffer));
  196. }
  197. inline std::string itostr(int64_t X) {
  198. if (X < 0)
  199. return utostr(static_cast<uint64_t>(-X), true);
  200. else
  201. return utostr(static_cast<uint64_t>(X));
  202. }
  203. /// StrInStrNoCase - Portable version of strcasestr. Locates the first
  204. /// occurrence of string 's1' in string 's2', ignoring case. Returns
  205. /// the offset of s2 in s1 or npos if s2 cannot be found.
  206. StringRef::size_type StrInStrNoCase(StringRef s1, StringRef s2);
  207. /// getToken - This function extracts one token from source, ignoring any
  208. /// leading characters that appear in the Delimiters string, and ending the
  209. /// token at any of the characters that appear in the Delimiters string. If
  210. /// there are no tokens in the source string, an empty string is returned.
  211. /// The function returns a pair containing the extracted token and the
  212. /// remaining tail string.
  213. std::pair<StringRef, StringRef> getToken(StringRef Source,
  214. StringRef Delimiters = " \t\n\v\f\r");
  215. /// SplitString - Split up the specified string according to the specified
  216. /// delimiters, appending the result fragments to the output list.
  217. void SplitString(StringRef Source,
  218. SmallVectorImpl<StringRef> &OutFragments,
  219. StringRef Delimiters = " \t\n\v\f\r");
  220. /// Returns the English suffix for an ordinal integer (-st, -nd, -rd, -th).
  221. inline StringRef getOrdinalSuffix(unsigned Val) {
  222. // It is critically important that we do this perfectly for
  223. // user-written sequences with over 100 elements.
  224. switch (Val % 100) {
  225. case 11:
  226. case 12:
  227. case 13:
  228. return "th";
  229. default:
  230. switch (Val % 10) {
  231. case 1: return "st";
  232. case 2: return "nd";
  233. case 3: return "rd";
  234. default: return "th";
  235. }
  236. }
  237. }
  238. /// Print each character of the specified string, escaping it if it is not
  239. /// printable or if it is an escape char.
  240. void printEscapedString(StringRef Name, raw_ostream &Out);
  241. /// Print each character of the specified string, escaping HTML special
  242. /// characters.
  243. void printHTMLEscaped(StringRef String, raw_ostream &Out);
  244. /// printLowerCase - Print each character as lowercase if it is uppercase.
  245. void printLowerCase(StringRef String, raw_ostream &Out);
  246. namespace detail {
  247. template <typename IteratorT>
  248. inline std::string join_impl(IteratorT Begin, IteratorT End,
  249. StringRef Separator, std::input_iterator_tag) {
  250. std::string S;
  251. if (Begin == End)
  252. return S;
  253. S += (*Begin);
  254. while (++Begin != End) {
  255. S += Separator;
  256. S += (*Begin);
  257. }
  258. return S;
  259. }
  260. template <typename IteratorT>
  261. inline std::string join_impl(IteratorT Begin, IteratorT End,
  262. StringRef Separator, std::forward_iterator_tag) {
  263. std::string S;
  264. if (Begin == End)
  265. return S;
  266. size_t Len = (std::distance(Begin, End) - 1) * Separator.size();
  267. for (IteratorT I = Begin; I != End; ++I)
  268. Len += (*Begin).size();
  269. S.reserve(Len);
  270. S += (*Begin);
  271. while (++Begin != End) {
  272. S += Separator;
  273. S += (*Begin);
  274. }
  275. return S;
  276. }
  277. template <typename Sep>
  278. inline void join_items_impl(std::string &Result, Sep Separator) {}
  279. template <typename Sep, typename Arg>
  280. inline void join_items_impl(std::string &Result, Sep Separator,
  281. const Arg &Item) {
  282. Result += Item;
  283. }
  284. template <typename Sep, typename Arg1, typename... Args>
  285. inline void join_items_impl(std::string &Result, Sep Separator, const Arg1 &A1,
  286. Args &&... Items) {
  287. Result += A1;
  288. Result += Separator;
  289. join_items_impl(Result, Separator, std::forward<Args>(Items)...);
  290. }
  291. inline size_t join_one_item_size(char C) { return 1; }
  292. inline size_t join_one_item_size(const char *S) { return S ? ::strlen(S) : 0; }
  293. template <typename T> inline size_t join_one_item_size(const T &Str) {
  294. return Str.size();
  295. }
  296. inline size_t join_items_size() { return 0; }
  297. template <typename A1> inline size_t join_items_size(const A1 &A) {
  298. return join_one_item_size(A);
  299. }
  300. template <typename A1, typename... Args>
  301. inline size_t join_items_size(const A1 &A, Args &&... Items) {
  302. return join_one_item_size(A) + join_items_size(std::forward<Args>(Items)...);
  303. }
  304. } // end namespace detail
  305. /// Joins the strings in the range [Begin, End), adding Separator between
  306. /// the elements.
  307. template <typename IteratorT>
  308. inline std::string join(IteratorT Begin, IteratorT End, StringRef Separator) {
  309. using tag = typename std::iterator_traits<IteratorT>::iterator_category;
  310. return detail::join_impl(Begin, End, Separator, tag());
  311. }
  312. /// Joins the strings in the range [R.begin(), R.end()), adding Separator
  313. /// between the elements.
  314. template <typename Range>
  315. inline std::string join(Range &&R, StringRef Separator) {
  316. return join(R.begin(), R.end(), Separator);
  317. }
  318. /// Joins the strings in the parameter pack \p Items, adding \p Separator
  319. /// between the elements. All arguments must be implicitly convertible to
  320. /// std::string, or there should be an overload of std::string::operator+=()
  321. /// that accepts the argument explicitly.
  322. template <typename Sep, typename... Args>
  323. inline std::string join_items(Sep Separator, Args &&... Items) {
  324. std::string Result;
  325. if (sizeof...(Items) == 0)
  326. return Result;
  327. size_t NS = detail::join_one_item_size(Separator);
  328. size_t NI = detail::join_items_size(std::forward<Args>(Items)...);
  329. Result.reserve(NI + (sizeof...(Items) - 1) * NS + 1);
  330. detail::join_items_impl(Result, Separator, std::forward<Args>(Items)...);
  331. return Result;
  332. }
  333. } // end namespace llvm
  334. #endif // LLVM_ADT_STRINGEXTRAS_H