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