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