56dbb5b806899d81bffde29951a5c59e23286825
[oota-llvm.git] / 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 <iterator>
18 #include "llvm/ADT/StringRef.h"
19 #include "llvm/Support/DataTypes.h"
20
21 namespace llvm {
22 template<typename T> class SmallVectorImpl;
23
24 /// hexdigit - Return the hexadecimal character for the
25 /// given number \p X (which should be less than 16).
26 static inline char hexdigit(unsigned X, bool LowerCase = false) {
27   const char HexChar = LowerCase ? 'a' : 'A';
28   return X < 10 ? '0' + X : HexChar + X - 10;
29 }
30
31 /// Interpret the given character \p C as a hexadecimal digit and return its
32 /// value.
33 ///
34 /// If \p C is not a valid hex digit, -1U is returned.
35 static inline unsigned hexDigitValue(char C) {
36   if (C >= '0' && C <= '9') return C-'0';
37   if (C >= 'a' && C <= 'f') return C-'a'+10U;
38   if (C >= 'A' && C <= 'F') return C-'A'+10U;
39   return -1U;
40 }
41
42 /// utohex_buffer - Emit the specified number into the buffer specified by
43 /// BufferEnd, returning a pointer to the start of the string.  This can be used
44 /// like this: (note that the buffer must be large enough to handle any number):
45 ///    char Buffer[40];
46 ///    printf("0x%s", utohex_buffer(X, Buffer+40));
47 ///
48 /// This should only be used with unsigned types.
49 ///
50 template<typename IntTy>
51 static inline char *utohex_buffer(IntTy X, char *BufferEnd) {
52   char *BufPtr = BufferEnd;
53   *--BufPtr = 0;      // Null terminate buffer.
54   if (X == 0) {
55     *--BufPtr = '0';  // Handle special case.
56     return BufPtr;
57   }
58
59   while (X) {
60     unsigned char Mod = static_cast<unsigned char>(X) & 15;
61     *--BufPtr = hexdigit(Mod);
62     X >>= 4;
63   }
64   return BufPtr;
65 }
66
67 static inline std::string utohexstr(uint64_t X) {
68   char Buffer[17];
69   return utohex_buffer(X, Buffer+17);
70 }
71
72 static inline std::string utostr_32(uint32_t X, bool isNeg = false) {
73   char Buffer[11];
74   char *BufPtr = Buffer+11;
75
76   if (X == 0) *--BufPtr = '0';  // Handle special case...
77
78   while (X) {
79     *--BufPtr = '0' + char(X % 10);
80     X /= 10;
81   }
82
83   if (isNeg) *--BufPtr = '-';   // Add negative sign...
84
85   return std::string(BufPtr, Buffer+11);
86 }
87
88 static inline std::string utostr(uint64_t X, bool isNeg = false) {
89   char Buffer[21];
90   char *BufPtr = Buffer+21;
91
92   if (X == 0) *--BufPtr = '0';  // Handle special case...
93
94   while (X) {
95     *--BufPtr = '0' + char(X % 10);
96     X /= 10;
97   }
98
99   if (isNeg) *--BufPtr = '-';   // Add negative sign...
100   return std::string(BufPtr, Buffer+21);
101 }
102
103
104 static inline std::string itostr(int64_t X) {
105   if (X < 0)
106     return utostr(static_cast<uint64_t>(-X), true);
107   else
108     return utostr(static_cast<uint64_t>(X));
109 }
110
111 /// StrInStrNoCase - Portable version of strcasestr.  Locates the first
112 /// occurrence of string 's1' in string 's2', ignoring case.  Returns
113 /// the offset of s2 in s1 or npos if s2 cannot be found.
114 StringRef::size_type StrInStrNoCase(StringRef s1, StringRef s2);
115
116 /// getToken - This function extracts one token from source, ignoring any
117 /// leading characters that appear in the Delimiters string, and ending the
118 /// token at any of the characters that appear in the Delimiters string.  If
119 /// there are no tokens in the source string, an empty string is returned.
120 /// The function returns a pair containing the extracted token and the
121 /// remaining tail string.
122 std::pair<StringRef, StringRef> getToken(StringRef Source,
123                                          StringRef Delimiters = " \t\n\v\f\r");
124
125 /// SplitString - Split up the specified string according to the specified
126 /// delimiters, appending the result fragments to the output list.
127 void SplitString(StringRef Source,
128                  SmallVectorImpl<StringRef> &OutFragments,
129                  StringRef Delimiters = " \t\n\v\f\r");
130
131 /// HashString - Hash function for strings.
132 ///
133 /// This is the Bernstein hash function.
134 //
135 // FIXME: Investigate whether a modified bernstein hash function performs
136 // better: http://eternallyconfuzzled.com/tuts/algorithms/jsw_tut_hashing.aspx
137 //   X*33+c -> X*33^c
138 static inline unsigned HashString(StringRef Str, unsigned Result = 0) {
139   for (unsigned i = 0, e = Str.size(); i != e; ++i)
140     Result = Result * 33 + (unsigned char)Str[i];
141   return Result;
142 }
143
144 /// Returns the English suffix for an ordinal integer (-st, -nd, -rd, -th).
145 static inline StringRef getOrdinalSuffix(unsigned Val) {
146   // It is critically important that we do this perfectly for
147   // user-written sequences with over 100 elements.
148   switch (Val % 100) {
149   case 11:
150   case 12:
151   case 13:
152     return "th";
153   default:
154     switch (Val % 10) {
155       case 1: return "st";
156       case 2: return "nd";
157       case 3: return "rd";
158       default: return "th";
159     }
160   }
161 }
162
163 template <typename IteratorT>
164 inline std::string join_impl(IteratorT Begin, IteratorT End,
165                              StringRef Separator, std::input_iterator_tag) {
166   std::string S;
167   if (Begin == End)
168     return S;
169
170   S += (*Begin);
171   while (++Begin != End) {
172     S += Separator;
173     S += (*Begin);
174   }
175   return S;
176 }
177
178 template <typename IteratorT>
179 inline std::string join_impl(IteratorT Begin, IteratorT End,
180                              StringRef Separator, std::forward_iterator_tag) {
181   std::string S;
182   if (Begin == End)
183     return S;
184
185   size_t Len = (std::distance(Begin, End) - 1) * Separator.size();
186   for (IteratorT I = Begin; I != End; ++I)
187     Len += (*Begin).size();
188   S.reserve(Len);
189   S += (*Begin);
190   while (++Begin != End) {
191     S += Separator;
192     S += (*Begin);
193   }
194   return S;
195 }
196
197 /// Joins the strings in the range [Begin, End), adding Separator between
198 /// the elements.
199 template <typename IteratorT>
200 inline std::string join(IteratorT Begin, IteratorT End, StringRef Separator) {
201   typedef typename std::iterator_traits<IteratorT>::iterator_category tag;
202   return join_impl(Begin, End, Separator, tag());
203 }
204
205 } // End llvm namespace
206
207 #endif