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