1 //===-- llvm/ADT/StringExtras.h - Useful string functions -------*- C++ -*-===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file contains some functions that are useful when dealing with strings.
12 //===----------------------------------------------------------------------===//
14 #ifndef LLVM_ADT_STRINGEXTRAS_H
15 #define LLVM_ADT_STRINGEXTRAS_H
17 #include "llvm/ADT/StringRef.h"
18 #include "llvm/Support/DataTypes.h"
23 template<typename T> class SmallVectorImpl;
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;
32 /// Construct a string ref from a boolean.
33 static inline StringRef toStringRef(bool B) {
34 return StringRef(B ? "true" : "false");
37 /// Interpret the given character \p C as a hexadecimal digit and return its
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;
48 static inline std::string utohexstr(uint64_t X, bool LowerCase = false) {
50 char *BufPtr = std::end(Buffer);
52 if (X == 0) *--BufPtr = '0';
55 unsigned char Mod = static_cast<unsigned char>(X) & 15;
56 *--BufPtr = hexdigit(Mod, LowerCase);
60 return std::string(BufPtr, std::end(Buffer));
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();
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]);
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);
84 return static_cast<uint8_t>((U1 << 4) | U2);
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) {
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();
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);
109 static inline std::string utostr(uint64_t X, bool isNeg = false) {
111 char *BufPtr = std::end(Buffer);
113 if (X == 0) *--BufPtr = '0'; // Handle special case...
116 *--BufPtr = '0' + char(X % 10);
120 if (isNeg) *--BufPtr = '-'; // Add negative sign...
121 return std::string(BufPtr, std::end(Buffer));
125 static inline std::string itostr(int64_t X) {
127 return utostr(static_cast<uint64_t>(-X), true);
129 return utostr(static_cast<uint64_t>(X));
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);
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");
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");
152 /// HashString - Hash function for strings.
154 /// This is the Bernstein hash function.
156 // FIXME: Investigate whether a modified bernstein hash function performs
157 // better: http://eternallyconfuzzled.com/tuts/algorithms/jsw_tut_hashing.aspx
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];
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.
179 default: return "th";
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);
190 template <typename IteratorT>
191 inline std::string join_impl(IteratorT Begin, IteratorT End,
192 StringRef Separator, std::input_iterator_tag) {
198 while (++Begin != End) {
205 template <typename IteratorT>
206 inline std::string join_impl(IteratorT Begin, IteratorT End,
207 StringRef Separator, std::forward_iterator_tag) {
212 size_t Len = (std::distance(Begin, End) - 1) * Separator.size();
213 for (IteratorT I = Begin; I != End; ++I)
214 Len += (*Begin).size();
217 while (++Begin != End) {
224 template <typename Sep>
225 inline void join_items_impl(std::string &Result, Sep Separator) {}
227 template <typename Sep, typename Arg>
228 inline void join_items_impl(std::string &Result, Sep Separator,
233 template <typename Sep, typename Arg1, typename... Args>
234 inline void join_items_impl(std::string &Result, Sep Separator, const Arg1 &A1,
238 join_items_impl(Result, Separator, std::forward<Args>(Items)...);
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; }
244 template <typename T> inline size_t join_one_item_size(const T &Str) {
248 inline size_t join_items_size() { return 0; }
250 template <typename A1> inline size_t join_items_size(const A1 &A) {
251 return join_one_item_size(A);
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)...);
259 /// Joins the strings in the range [Begin, End), adding Separator between
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());
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);
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) {
281 if (sizeof...(Items) == 0)
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)...);
291 } // End llvm namespace