Counter Strike : Global Offensive Source Code
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

553 lines
19 KiB

  1. //===--- StringRef.h - Constant String Reference Wrapper --------*- 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. #ifndef LLVM_ADT_STRINGREF_H
  10. #define LLVM_ADT_STRINGREF_H
  11. #include "llvm/Support/type_traits.h"
  12. #include <algorithm>
  13. #include <cassert>
  14. #include <cstring>
  15. #include <limits>
  16. #include <string>
  17. #include <utility>
  18. namespace llvm {
  19. template<typename T>
  20. class SmallVectorImpl;
  21. class APInt;
  22. class hash_code;
  23. class StringRef;
  24. /// Helper functions for StringRef::getAsInteger.
  25. bool getAsUnsignedInteger(StringRef Str, unsigned Radix,
  26. unsigned long long &Result);
  27. bool getAsSignedInteger(StringRef Str, unsigned Radix, long long &Result);
  28. /// StringRef - Represent a constant reference to a string, i.e. a character
  29. /// array and a length, which need not be null terminated.
  30. ///
  31. /// This class does not own the string data, it is expected to be used in
  32. /// situations where the character data resides in some other buffer, whose
  33. /// lifetime extends past that of the StringRef. For this reason, it is not in
  34. /// general safe to store a StringRef.
  35. class StringRef {
  36. public:
  37. typedef const char *iterator;
  38. typedef const char *const_iterator;
  39. static const size_t npos = ~size_t(0);
  40. typedef size_t size_type;
  41. private:
  42. /// The start of the string, in an external buffer.
  43. const char *Data;
  44. /// The length of the string.
  45. size_t Length;
  46. // Workaround PR5482: nearly all gcc 4.x miscompile StringRef and std::min()
  47. // Changing the arg of min to be an integer, instead of a reference to an
  48. // integer works around this bug.
  49. static size_t min(size_t a, size_t b) { return a < b ? a : b; }
  50. static size_t max(size_t a, size_t b) { return a > b ? a : b; }
  51. // Workaround memcmp issue with null pointers (undefined behavior)
  52. // by providing a specialized version
  53. static int compareMemory(const char *Lhs, const char *Rhs, size_t Length) {
  54. if (Length == 0) { return 0; }
  55. return ::memcmp(Lhs,Rhs,Length);
  56. }
  57. public:
  58. /// @name Constructors
  59. /// @{
  60. /// Construct an empty string ref.
  61. /*implicit*/ StringRef() : Data(0), Length(0) {}
  62. /// Construct a string ref from a cstring.
  63. /*implicit*/ StringRef(const char *Str)
  64. : Data(Str) {
  65. assert(Str && "StringRef cannot be built from a NULL argument");
  66. Length = ::strlen(Str); // invoking strlen(NULL) is undefined behavior
  67. }
  68. /// Construct a string ref from a pointer and length.
  69. /*implicit*/ StringRef(const char *data, size_t length)
  70. : Data(data), Length(length) {
  71. assert((data || length == 0) &&
  72. "StringRef cannot be built from a NULL argument with non-null length");
  73. }
  74. /// Construct a string ref from an std::string.
  75. /*implicit*/ StringRef(const std::string &Str)
  76. : Data(Str.data()), Length(Str.length()) {}
  77. /// @}
  78. /// @name Iterators
  79. /// @{
  80. iterator begin() const { return Data; }
  81. iterator end() const { return Data + Length; }
  82. /// @}
  83. /// @name String Operations
  84. /// @{
  85. /// data - Get a pointer to the start of the string (which may not be null
  86. /// terminated).
  87. const char *data() const { return Data; }
  88. /// empty - Check if the string is empty.
  89. bool empty() const { return Length == 0; }
  90. /// size - Get the string size.
  91. size_t size() const { return Length; }
  92. /// front - Get the first character in the string.
  93. char front() const {
  94. assert(!empty());
  95. return Data[0];
  96. }
  97. /// back - Get the last character in the string.
  98. char back() const {
  99. assert(!empty());
  100. return Data[Length-1];
  101. }
  102. /// equals - Check for string equality, this is more efficient than
  103. /// compare() when the relative ordering of inequal strings isn't needed.
  104. bool equals(StringRef RHS) const {
  105. return (Length == RHS.Length &&
  106. compareMemory(Data, RHS.Data, RHS.Length) == 0);
  107. }
  108. /// equals_lower - Check for string equality, ignoring case.
  109. bool equals_lower(StringRef RHS) const {
  110. return Length == RHS.Length && compare_lower(RHS) == 0;
  111. }
  112. /// compare - Compare two strings; the result is -1, 0, or 1 if this string
  113. /// is lexicographically less than, equal to, or greater than the \p RHS.
  114. int compare(StringRef RHS) const {
  115. // Check the prefix for a mismatch.
  116. if (int Res = compareMemory(Data, RHS.Data, min(Length, RHS.Length)))
  117. return Res < 0 ? -1 : 1;
  118. // Otherwise the prefixes match, so we only need to check the lengths.
  119. if (Length == RHS.Length)
  120. return 0;
  121. return Length < RHS.Length ? -1 : 1;
  122. }
  123. /// compare_lower - Compare two strings, ignoring case.
  124. int compare_lower(StringRef RHS) const;
  125. /// compare_numeric - Compare two strings, treating sequences of digits as
  126. /// numbers.
  127. int compare_numeric(StringRef RHS) const;
  128. /// \brief Determine the edit distance between this string and another
  129. /// string.
  130. ///
  131. /// \param Other the string to compare this string against.
  132. ///
  133. /// \param AllowReplacements whether to allow character
  134. /// replacements (change one character into another) as a single
  135. /// operation, rather than as two operations (an insertion and a
  136. /// removal).
  137. ///
  138. /// \param MaxEditDistance If non-zero, the maximum edit distance that
  139. /// this routine is allowed to compute. If the edit distance will exceed
  140. /// that maximum, returns \c MaxEditDistance+1.
  141. ///
  142. /// \returns the minimum number of character insertions, removals,
  143. /// or (if \p AllowReplacements is \c true) replacements needed to
  144. /// transform one of the given strings into the other. If zero,
  145. /// the strings are identical.
  146. unsigned edit_distance(StringRef Other, bool AllowReplacements = true,
  147. unsigned MaxEditDistance = 0);
  148. /// str - Get the contents as an std::string.
  149. std::string str() const {
  150. if (Data == 0) return std::string();
  151. return std::string(Data, Length);
  152. }
  153. /// @}
  154. /// @name Operator Overloads
  155. /// @{
  156. char operator[](size_t Index) const {
  157. assert(Index < Length && "Invalid index!");
  158. return Data[Index];
  159. }
  160. /// @}
  161. /// @name Type Conversions
  162. /// @{
  163. operator std::string() const {
  164. return str();
  165. }
  166. /// @}
  167. /// @name String Predicates
  168. /// @{
  169. /// Check if this string starts with the given \p Prefix.
  170. bool startswith(StringRef Prefix) const {
  171. return Length >= Prefix.Length &&
  172. compareMemory(Data, Prefix.Data, Prefix.Length) == 0;
  173. }
  174. /// Check if this string ends with the given \p Suffix.
  175. bool endswith(StringRef Suffix) const {
  176. return Length >= Suffix.Length &&
  177. compareMemory(end() - Suffix.Length, Suffix.Data, Suffix.Length) == 0;
  178. }
  179. /// @}
  180. /// @name String Searching
  181. /// @{
  182. /// Search for the first character \p C in the string.
  183. ///
  184. /// \returns The index of the first occurrence of \p C, or npos if not
  185. /// found.
  186. size_t find(char C, size_t From = 0) const {
  187. for (size_t i = min(From, Length), e = Length; i != e; ++i)
  188. if (Data[i] == C)
  189. return i;
  190. return npos;
  191. }
  192. /// Search for the first string \p Str in the string.
  193. ///
  194. /// \returns The index of the first occurrence of \p Str, or npos if not
  195. /// found.
  196. size_t find(StringRef Str, size_t From = 0) const;
  197. /// Search for the last character \p C in the string.
  198. ///
  199. /// \returns The index of the last occurrence of \p C, or npos if not
  200. /// found.
  201. size_t rfind(char C, size_t From = npos) const {
  202. From = min(From, Length);
  203. size_t i = From;
  204. while (i != 0) {
  205. --i;
  206. if (Data[i] == C)
  207. return i;
  208. }
  209. return npos;
  210. }
  211. /// Search for the last string \p Str in the string.
  212. ///
  213. /// \returns The index of the last occurrence of \p Str, or npos if not
  214. /// found.
  215. size_t rfind(StringRef Str) const;
  216. /// Find the first character in the string that is \p C, or npos if not
  217. /// found. Same as find.
  218. size_type find_first_of(char C, size_t From = 0) const {
  219. return find(C, From);
  220. }
  221. /// Find the first character in the string that is in \p Chars, or npos if
  222. /// not found.
  223. ///
  224. /// Complexity: O(size() + Chars.size())
  225. size_type find_first_of(StringRef Chars, size_t From = 0) const;
  226. /// Find the first character in the string that is not \p C or npos if not
  227. /// found.
  228. size_type find_first_not_of(char C, size_t From = 0) const;
  229. /// Find the first character in the string that is not in the string
  230. /// \p Chars, or npos if not found.
  231. ///
  232. /// Complexity: O(size() + Chars.size())
  233. size_type find_first_not_of(StringRef Chars, size_t From = 0) const;
  234. /// Find the last character in the string that is \p C, or npos if not
  235. /// found.
  236. size_type find_last_of(char C, size_t From = npos) const {
  237. return rfind(C, From);
  238. }
  239. /// Find the last character in the string that is in \p C, or npos if not
  240. /// found.
  241. ///
  242. /// Complexity: O(size() + Chars.size())
  243. size_type find_last_of(StringRef Chars, size_t From = npos) const;
  244. /// Find the last character in the string that is not \p C, or npos if not
  245. /// found.
  246. size_type find_last_not_of(char C, size_t From = npos) const;
  247. /// Find the last character in the string that is not in \p Chars, or
  248. /// npos if not found.
  249. ///
  250. /// Complexity: O(size() + Chars.size())
  251. size_type find_last_not_of(StringRef Chars, size_t From = npos) const;
  252. /// @}
  253. /// @name Helpful Algorithms
  254. /// @{
  255. /// Return the number of occurrences of \p C in the string.
  256. size_t count(char C) const {
  257. size_t Count = 0;
  258. for (size_t i = 0, e = Length; i != e; ++i)
  259. if (Data[i] == C)
  260. ++Count;
  261. return Count;
  262. }
  263. /// Return the number of non-overlapped occurrences of \p Str in
  264. /// the string.
  265. size_t count(StringRef Str) const;
  266. /// Parse the current string as an integer of the specified radix. If
  267. /// \p Radix is specified as zero, this does radix autosensing using
  268. /// extended C rules: 0 is octal, 0x is hex, 0b is binary.
  269. ///
  270. /// If the string is invalid or if only a subset of the string is valid,
  271. /// this returns true to signify the error. The string is considered
  272. /// erroneous if empty or if it overflows T.
  273. template <typename T>
  274. typename enable_if_c<std::numeric_limits<T>::is_signed, bool>::type
  275. getAsInteger(unsigned Radix, T &Result) const {
  276. long long LLVal;
  277. if (getAsSignedInteger(*this, Radix, LLVal) ||
  278. static_cast<T>(LLVal) != LLVal)
  279. return true;
  280. Result = LLVal;
  281. return false;
  282. }
  283. template <typename T>
  284. typename enable_if_c<!std::numeric_limits<T>::is_signed, bool>::type
  285. getAsInteger(unsigned Radix, T &Result) const {
  286. unsigned long long ULLVal;
  287. if (getAsUnsignedInteger(*this, Radix, ULLVal) ||
  288. static_cast<T>(ULLVal) != ULLVal)
  289. return true;
  290. Result = ULLVal;
  291. return false;
  292. }
  293. /// Parse the current string as an integer of the specified \p Radix, or of
  294. /// an autosensed radix if the \p Radix given is 0. The current value in
  295. /// \p Result is discarded, and the storage is changed to be wide enough to
  296. /// store the parsed integer.
  297. ///
  298. /// \returns true if the string does not solely consist of a valid
  299. /// non-empty number in the appropriate base.
  300. ///
  301. /// APInt::fromString is superficially similar but assumes the
  302. /// string is well-formed in the given radix.
  303. bool getAsInteger(unsigned Radix, APInt &Result) const;
  304. /// @}
  305. /// @name String Operations
  306. /// @{
  307. // Convert the given ASCII string to lowercase.
  308. std::string lower() const;
  309. /// Convert the given ASCII string to uppercase.
  310. std::string upper() const;
  311. /// @}
  312. /// @name Substring Operations
  313. /// @{
  314. /// Return a reference to the substring from [Start, Start + N).
  315. ///
  316. /// \param Start The index of the starting character in the substring; if
  317. /// the index is npos or greater than the length of the string then the
  318. /// empty substring will be returned.
  319. ///
  320. /// \param N The number of characters to included in the substring. If N
  321. /// exceeds the number of characters remaining in the string, the string
  322. /// suffix (starting with \p Start) will be returned.
  323. StringRef substr(size_t Start, size_t N = npos) const {
  324. Start = min(Start, Length);
  325. return StringRef(Data + Start, min(N, Length - Start));
  326. }
  327. /// Return a StringRef equal to 'this' but with the first \p N elements
  328. /// dropped.
  329. StringRef drop_front(unsigned N = 1) const {
  330. assert(size() >= N && "Dropping more elements than exist");
  331. return substr(N);
  332. }
  333. /// Return a StringRef equal to 'this' but with the last \p N elements
  334. /// dropped.
  335. StringRef drop_back(unsigned N = 1) const {
  336. assert(size() >= N && "Dropping more elements than exist");
  337. return substr(0, size()-N);
  338. }
  339. /// Return a reference to the substring from [Start, End).
  340. ///
  341. /// \param Start The index of the starting character in the substring; if
  342. /// the index is npos or greater than the length of the string then the
  343. /// empty substring will be returned.
  344. ///
  345. /// \param End The index following the last character to include in the
  346. /// substring. If this is npos, or less than \p Start, or exceeds the
  347. /// number of characters remaining in the string, the string suffix
  348. /// (starting with \p Start) will be returned.
  349. StringRef slice(size_t Start, size_t End) const {
  350. Start = min(Start, Length);
  351. End = min(max(Start, End), Length);
  352. return StringRef(Data + Start, End - Start);
  353. }
  354. /// Split into two substrings around the first occurrence of a separator
  355. /// character.
  356. ///
  357. /// If \p Separator is in the string, then the result is a pair (LHS, RHS)
  358. /// such that (*this == LHS + Separator + RHS) is true and RHS is
  359. /// maximal. If \p Separator is not in the string, then the result is a
  360. /// pair (LHS, RHS) where (*this == LHS) and (RHS == "").
  361. ///
  362. /// \param Separator The character to split on.
  363. /// \returns The split substrings.
  364. std::pair<StringRef, StringRef> split(char Separator) const {
  365. size_t Idx = find(Separator);
  366. if (Idx == npos)
  367. return std::make_pair(*this, StringRef());
  368. return std::make_pair(slice(0, Idx), slice(Idx+1, npos));
  369. }
  370. /// Split into two substrings around the first occurrence of a separator
  371. /// string.
  372. ///
  373. /// If \p Separator is in the string, then the result is a pair (LHS, RHS)
  374. /// such that (*this == LHS + Separator + RHS) is true and RHS is
  375. /// maximal. If \p Separator is not in the string, then the result is a
  376. /// pair (LHS, RHS) where (*this == LHS) and (RHS == "").
  377. ///
  378. /// \param Separator - The string to split on.
  379. /// \return - The split substrings.
  380. std::pair<StringRef, StringRef> split(StringRef Separator) const {
  381. size_t Idx = find(Separator);
  382. if (Idx == npos)
  383. return std::make_pair(*this, StringRef());
  384. return std::make_pair(slice(0, Idx), slice(Idx + Separator.size(), npos));
  385. }
  386. /// Split into substrings around the occurrences of a separator string.
  387. ///
  388. /// Each substring is stored in \p A. If \p MaxSplit is >= 0, at most
  389. /// \p MaxSplit splits are done and consequently <= \p MaxSplit
  390. /// elements are added to A.
  391. /// If \p KeepEmpty is false, empty strings are not added to \p A. They
  392. /// still count when considering \p MaxSplit
  393. /// An useful invariant is that
  394. /// Separator.join(A) == *this if MaxSplit == -1 and KeepEmpty == true
  395. ///
  396. /// \param A - Where to put the substrings.
  397. /// \param Separator - The string to split on.
  398. /// \param MaxSplit - The maximum number of times the string is split.
  399. /// \param KeepEmpty - True if empty substring should be added.
  400. void split(SmallVectorImpl<StringRef> &A,
  401. StringRef Separator, int MaxSplit = -1,
  402. bool KeepEmpty = true) const;
  403. /// Split into two substrings around the last occurrence of a separator
  404. /// character.
  405. ///
  406. /// If \p Separator is in the string, then the result is a pair (LHS, RHS)
  407. /// such that (*this == LHS + Separator + RHS) is true and RHS is
  408. /// minimal. If \p Separator is not in the string, then the result is a
  409. /// pair (LHS, RHS) where (*this == LHS) and (RHS == "").
  410. ///
  411. /// \param Separator - The character to split on.
  412. /// \return - The split substrings.
  413. std::pair<StringRef, StringRef> rsplit(char Separator) const {
  414. size_t Idx = rfind(Separator);
  415. if (Idx == npos)
  416. return std::make_pair(*this, StringRef());
  417. return std::make_pair(slice(0, Idx), slice(Idx+1, npos));
  418. }
  419. /// Return string with consecutive characters in \p Chars starting from
  420. /// the left removed.
  421. StringRef ltrim(StringRef Chars = " \t\n\v\f\r") const {
  422. return drop_front(std::min(Length, find_first_not_of(Chars)));
  423. }
  424. /// Return string with consecutive characters in \p Chars starting from
  425. /// the right removed.
  426. StringRef rtrim(StringRef Chars = " \t\n\v\f\r") const {
  427. return drop_back(Length - std::min(Length, find_last_not_of(Chars) + 1));
  428. }
  429. /// Return string with consecutive characters in \p Chars starting from
  430. /// the left and right removed.
  431. StringRef trim(StringRef Chars = " \t\n\v\f\r") const {
  432. return ltrim(Chars).rtrim(Chars);
  433. }
  434. /// @}
  435. };
  436. /// @name StringRef Comparison Operators
  437. /// @{
  438. inline bool operator==(StringRef LHS, StringRef RHS) {
  439. return LHS.equals(RHS);
  440. }
  441. inline bool operator!=(StringRef LHS, StringRef RHS) {
  442. return !(LHS == RHS);
  443. }
  444. inline bool operator<(StringRef LHS, StringRef RHS) {
  445. return LHS.compare(RHS) == -1;
  446. }
  447. inline bool operator<=(StringRef LHS, StringRef RHS) {
  448. return LHS.compare(RHS) != 1;
  449. }
  450. inline bool operator>(StringRef LHS, StringRef RHS) {
  451. return LHS.compare(RHS) == 1;
  452. }
  453. inline bool operator>=(StringRef LHS, StringRef RHS) {
  454. return LHS.compare(RHS) != -1;
  455. }
  456. inline std::string &operator+=(std::string &buffer, StringRef string) {
  457. return buffer.append(string.data(), string.size());
  458. }
  459. /// @}
  460. /// \brief Compute a hash_code for a StringRef.
  461. hash_code hash_value(StringRef S);
  462. // StringRefs can be treated like a POD type.
  463. template <typename T> struct isPodLike;
  464. template <> struct isPodLike<StringRef> { static const bool value = true; };
  465. }
  466. #endif