LLVM  4.0.0
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/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 std::string utostr(uint64_t X, bool isNeg = false) {
80  char Buffer[21];
81  char *BufPtr = std::end(Buffer);
82 
83  if (X == 0) *--BufPtr = '0'; // Handle special case...
84 
85  while (X) {
86  *--BufPtr = '0' + char(X % 10);
87  X /= 10;
88  }
89 
90  if (isNeg) *--BufPtr = '-'; // Add negative sign...
91  return std::string(BufPtr, std::end(Buffer));
92 }
93 
94 
95 static inline std::string itostr(int64_t X) {
96  if (X < 0)
97  return utostr(static_cast<uint64_t>(-X), true);
98  else
99  return utostr(static_cast<uint64_t>(X));
100 }
101 
102 /// StrInStrNoCase - Portable version of strcasestr. Locates the first
103 /// occurrence of string 's1' in string 's2', ignoring case. Returns
104 /// the offset of s2 in s1 or npos if s2 cannot be found.
105 StringRef::size_type StrInStrNoCase(StringRef s1, StringRef s2);
106 
107 /// getToken - This function extracts one token from source, ignoring any
108 /// leading characters that appear in the Delimiters string, and ending the
109 /// token at any of the characters that appear in the Delimiters string. If
110 /// there are no tokens in the source string, an empty string is returned.
111 /// The function returns a pair containing the extracted token and the
112 /// remaining tail string.
113 std::pair<StringRef, StringRef> getToken(StringRef Source,
114  StringRef Delimiters = " \t\n\v\f\r");
115 
116 /// SplitString - Split up the specified string according to the specified
117 /// delimiters, appending the result fragments to the output list.
118 void SplitString(StringRef Source,
119  SmallVectorImpl<StringRef> &OutFragments,
120  StringRef Delimiters = " \t\n\v\f\r");
121 
122 /// HashString - Hash function for strings.
123 ///
124 /// This is the Bernstein hash function.
125 //
126 // FIXME: Investigate whether a modified bernstein hash function performs
127 // better: http://eternallyconfuzzled.com/tuts/algorithms/jsw_tut_hashing.aspx
128 // X*33+c -> X*33^c
129 static inline unsigned HashString(StringRef Str, unsigned Result = 0) {
130  for (StringRef::size_type i = 0, e = Str.size(); i != e; ++i)
131  Result = Result * 33 + (unsigned char)Str[i];
132  return Result;
133 }
134 
135 /// Returns the English suffix for an ordinal integer (-st, -nd, -rd, -th).
136 static inline StringRef getOrdinalSuffix(unsigned Val) {
137  // It is critically important that we do this perfectly for
138  // user-written sequences with over 100 elements.
139  switch (Val % 100) {
140  case 11:
141  case 12:
142  case 13:
143  return "th";
144  default:
145  switch (Val % 10) {
146  case 1: return "st";
147  case 2: return "nd";
148  case 3: return "rd";
149  default: return "th";
150  }
151  }
152 }
153 
154 /// PrintEscapedString - Print each character of the specified string, escaping
155 /// it if it is not printable or if it is an escape char.
156 void PrintEscapedString(StringRef Name, raw_ostream &Out);
157 
158 namespace detail {
159 
160 template <typename IteratorT>
161 inline std::string join_impl(IteratorT Begin, IteratorT End,
162  StringRef Separator, std::input_iterator_tag) {
163  std::string S;
164  if (Begin == End)
165  return S;
166 
167  S += (*Begin);
168  while (++Begin != End) {
169  S += Separator;
170  S += (*Begin);
171  }
172  return S;
173 }
174 
175 template <typename IteratorT>
176 inline std::string join_impl(IteratorT Begin, IteratorT End,
177  StringRef Separator, std::forward_iterator_tag) {
178  std::string S;
179  if (Begin == End)
180  return S;
181 
182  size_t Len = (std::distance(Begin, End) - 1) * Separator.size();
183  for (IteratorT I = Begin; I != End; ++I)
184  Len += (*Begin).size();
185  S.reserve(Len);
186  S += (*Begin);
187  while (++Begin != End) {
188  S += Separator;
189  S += (*Begin);
190  }
191  return S;
192 }
193 
194 template <typename Sep>
195 inline void join_items_impl(std::string &Result, Sep Separator) {}
196 
197 template <typename Sep, typename Arg>
198 inline void join_items_impl(std::string &Result, Sep Separator,
199  const Arg &Item) {
200  Result += Item;
201 }
202 
203 template <typename Sep, typename Arg1, typename... Args>
204 inline void join_items_impl(std::string &Result, Sep Separator, const Arg1 &A1,
205  Args &&... Items) {
206  Result += A1;
207  Result += Separator;
208  join_items_impl(Result, Separator, std::forward<Args>(Items)...);
209 }
210 
211 inline size_t join_one_item_size(char C) { return 1; }
212 inline size_t join_one_item_size(const char *S) { return S ? ::strlen(S) : 0; }
213 
214 template <typename T> inline size_t join_one_item_size(const T &Str) {
215  return Str.size();
216 }
217 
218 inline size_t join_items_size() { return 0; }
219 
220 template <typename A1> inline size_t join_items_size(const A1 &A) {
221  return join_one_item_size(A);
222 }
223 template <typename A1, typename... Args>
224 inline size_t join_items_size(const A1 &A, Args &&... Items) {
225  return join_one_item_size(A) + join_items_size(std::forward<Args>(Items)...);
226 }
227 }
228 
229 /// Joins the strings in the range [Begin, End), adding Separator between
230 /// the elements.
231 template <typename IteratorT>
232 inline std::string join(IteratorT Begin, IteratorT End, StringRef Separator) {
233  typedef typename std::iterator_traits<IteratorT>::iterator_category tag;
234  return detail::join_impl(Begin, End, Separator, tag());
235 }
236 
237 /// Joins the strings in the parameter pack \p Items, adding \p Separator
238 /// between the elements. All arguments must be implicitly convertible to
239 /// std::string, or there should be an overload of std::string::operator+=()
240 /// that accepts the argument explicitly.
241 template <typename Sep, typename... Args>
242 inline std::string join_items(Sep Separator, Args &&... Items) {
243  std::string Result;
244  if (sizeof...(Items) == 0)
245  return Result;
246 
247  size_t NS = detail::join_one_item_size(Separator);
248  size_t NI = detail::join_items_size(std::forward<Args>(Items)...);
249  Result.reserve(NI + (sizeof...(Items) - 1) * NS + 1);
250  detail::join_items_impl(Result, Separator, std::forward<Args>(Items)...);
251  return Result;
252 }
253 
254 } // End llvm namespace
255 
256 #endif
std::string join_items(Sep Separator, Args &&...Items)
Joins the strings in the parameter pack Items, adding Separator between the elements.
Definition: StringExtras.h:242
const_iterator end(StringRef path)
Get end iterator over path.
Definition: Path.cpp:241
static unsigned HashString(StringRef Str, unsigned Result=0)
HashString - Hash function for strings.
Definition: StringExtras.h:129
size_t i
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:341
size_t join_items_size()
Definition: StringExtras.h:218
std::pair< StringRef, StringRef > getToken(StringRef Source, StringRef Delimiters=" \t\n\v\f\r")
getToken - This function extracts one token from source, ignoring any leading characters that appear ...
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:232
static std::string toHex(StringRef Input)
Convert buffer Input to its hexadecimal representation.
Definition: StringExtras.h:65
static std::string utostr(uint64_t X, bool isNeg=false)
Definition: StringExtras.h:79
static GCRegistry::Add< OcamlGC > B("ocaml","ocaml 3.10-compatible GC")
LLVM_NODISCARD LLVM_ATTRIBUTE_ALWAYS_INLINE size_t size() const
size - Get the string size.
Definition: StringRef.h:135
static StringRef getOrdinalSuffix(unsigned Val)
Returns the English suffix for an ordinal integer (-st, -nd, -rd, -th).
Definition: StringExtras.h:136
void join_items_impl(std::string &Result, Sep Separator)
Definition: StringExtras.h:195
static GCMetadataPrinterRegistry::Add< ErlangGCPrinter > X("erlang","erlang-compatible garbage collector")
static const unsigned End
static std::string itostr(int64_t X)
Definition: StringExtras.h:95
size_t join_one_item_size(char C)
Definition: StringExtras.h:211
void SplitString(StringRef Source, SmallVectorImpl< StringRef > &OutFragments, StringRef Delimiters=" \t\n\v\f\r")
SplitString - Split up the specified string according to the specified delimiters, appending the result fragments to the output list.
static const char * Separator
static GCRegistry::Add< ShadowStackGC > C("shadow-stack","Very portable GC for uncooperative code generators")
static StringRef toStringRef(bool B)
Construct a string ref from a boolean.
Definition: StringExtras.h:33
static 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:27
size_t size_type
Definition: StringRef.h:52
#define I(x, y, z)
Definition: MD5.cpp:54
StringRef::size_type StrInStrNoCase(StringRef s1, StringRef s2)
StrInStrNoCase - Portable version of strcasestr.
static std::string utohexstr(uint64_t X, bool LowerCase=false)
Definition: StringExtras.h:48
static unsigned hexDigitValue(char C)
Interpret the given character C as a hexadecimal digit and return its value.
Definition: StringExtras.h:41
StringRef - Represent a constant reference to a string, i.e.
Definition: StringRef.h:47
static GCRegistry::Add< ErlangGC > A("erlang","erlang-compatible garbage collector")
std::string join_impl(IteratorT Begin, IteratorT End, StringRef Separator, std::input_iterator_tag)
Definition: StringExtras.h:161