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