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.
toStringRef(bool B)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.
hexDigitValue(char C)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.
toHex(StringRef 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 
itostr(int64_t X)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).
getOrdinalSuffix(unsigned Val)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>
join_impl(IteratorT Begin,IteratorT End,StringRef Separator,std::input_iterator_tag)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>
join_impl(IteratorT Begin,IteratorT End,StringRef Separator,std::forward_iterator_tag)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>
join_items_impl(std::string & Result,Sep Separator)195 inline void join_items_impl(std::string &Result, Sep Separator) {}
196 
197 template <typename Sep, typename Arg>
join_items_impl(std::string & Result,Sep Separator,const Arg & Item)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>
join_items_impl(std::string & Result,Sep Separator,const Arg1 & A1,Args &&...Items)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 
join_one_item_size(char C)211 inline size_t join_one_item_size(char C) { return 1; }
join_one_item_size(const char * S)212 inline size_t join_one_item_size(const char *S) { return S ? ::strlen(S) : 0; }
213 
join_one_item_size(const T & Str)214 template <typename T> inline size_t join_one_item_size(const T &Str) {
215   return Str.size();
216 }
217 
join_items_size()218 inline size_t join_items_size() { return 0; }
219 
join_items_size(const A1 & A)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>
join_items_size(const A1 & A,Args &&...Items)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>
join(IteratorT Begin,IteratorT End,StringRef Separator)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>
join_items(Sep Separator,Args &&...Items)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
257