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