StringExtras.h 6.7 KB

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