LLVM API Documentation

StringRef.h
Go to the documentation of this file.
00001 //===--- StringRef.h - Constant String Reference Wrapper --------*- C++ -*-===//
00002 //
00003 //                     The LLVM Compiler Infrastructure
00004 //
00005 // This file is distributed under the University of Illinois Open Source
00006 // License. See LICENSE.TXT for details.
00007 //
00008 //===----------------------------------------------------------------------===//
00009 
00010 #ifndef LLVM_ADT_STRINGREF_H
00011 #define LLVM_ADT_STRINGREF_H
00012 
00013 #include "llvm/Support/Allocator.h"
00014 #include <algorithm>
00015 #include <cassert>
00016 #include <cstring>
00017 #include <limits>
00018 #include <string>
00019 #include <utility>
00020 
00021 namespace llvm {
00022   template <typename T>
00023   class SmallVectorImpl;
00024   class APInt;
00025   class hash_code;
00026   class StringRef;
00027 
00028   /// Helper functions for StringRef::getAsInteger.
00029   bool getAsUnsignedInteger(StringRef Str, unsigned Radix,
00030                             unsigned long long &Result);
00031 
00032   bool getAsSignedInteger(StringRef Str, unsigned Radix, long long &Result);
00033 
00034   /// StringRef - Represent a constant reference to a string, i.e. a character
00035   /// array and a length, which need not be null terminated.
00036   ///
00037   /// This class does not own the string data, it is expected to be used in
00038   /// situations where the character data resides in some other buffer, whose
00039   /// lifetime extends past that of the StringRef. For this reason, it is not in
00040   /// general safe to store a StringRef.
00041   class StringRef {
00042   public:
00043     typedef const char *iterator;
00044     typedef const char *const_iterator;
00045     static const size_t npos = ~size_t(0);
00046     typedef size_t size_type;
00047 
00048   private:
00049     /// The start of the string, in an external buffer.
00050     const char *Data;
00051 
00052     /// The length of the string.
00053     size_t Length;
00054 
00055     // Workaround PR5482: nearly all gcc 4.x miscompile StringRef and std::min()
00056     // Changing the arg of min to be an integer, instead of a reference to an
00057     // integer works around this bug.
00058     static size_t min(size_t a, size_t b) { return a < b ? a : b; }
00059     static size_t max(size_t a, size_t b) { return a > b ? a : b; }
00060 
00061     // Workaround memcmp issue with null pointers (undefined behavior)
00062     // by providing a specialized version
00063     static int compareMemory(const char *Lhs, const char *Rhs, size_t Length) {
00064       if (Length == 0) { return 0; }
00065       return ::memcmp(Lhs,Rhs,Length);
00066     }
00067 
00068   public:
00069     /// @name Constructors
00070     /// @{
00071 
00072     /// Construct an empty string ref.
00073     /*implicit*/ StringRef() : Data(nullptr), Length(0) {}
00074 
00075     /// Construct a string ref from a cstring.
00076     /*implicit*/ StringRef(const char *Str)
00077       : Data(Str) {
00078         assert(Str && "StringRef cannot be built from a NULL argument");
00079         Length = ::strlen(Str); // invoking strlen(NULL) is undefined behavior
00080       }
00081 
00082     /// Construct a string ref from a pointer and length.
00083     /*implicit*/ StringRef(const char *data, size_t length)
00084       : Data(data), Length(length) {
00085         assert((data || length == 0) &&
00086         "StringRef cannot be built from a NULL argument with non-null length");
00087       }
00088 
00089     /// Construct a string ref from an std::string.
00090     /*implicit*/ StringRef(const std::string &Str)
00091       : Data(Str.data()), Length(Str.length()) {}
00092 
00093     /// @}
00094     /// @name Iterators
00095     /// @{
00096 
00097     iterator begin() const { return Data; }
00098 
00099     iterator end() const { return Data + Length; }
00100 
00101     /// @}
00102     /// @name String Operations
00103     /// @{
00104 
00105     /// data - Get a pointer to the start of the string (which may not be null
00106     /// terminated).
00107     const char *data() const { return Data; }
00108 
00109     /// empty - Check if the string is empty.
00110     bool empty() const { return Length == 0; }
00111 
00112     /// size - Get the string size.
00113     size_t size() const { return Length; }
00114 
00115     /// front - Get the first character in the string.
00116     char front() const {
00117       assert(!empty());
00118       return Data[0];
00119     }
00120 
00121     /// back - Get the last character in the string.
00122     char back() const {
00123       assert(!empty());
00124       return Data[Length-1];
00125     }
00126 
00127     // copy - Allocate copy in BumpPtrAllocator and return StringRef to it.
00128     StringRef copy(BumpPtrAllocator &Allocator) {
00129       char *S = Allocator.Allocate<char>(Length);
00130       std::copy(begin(), end(), S);
00131       return StringRef(S, Length);
00132     }
00133 
00134     /// equals - Check for string equality, this is more efficient than
00135     /// compare() when the relative ordering of inequal strings isn't needed.
00136     bool equals(StringRef RHS) const {
00137       return (Length == RHS.Length &&
00138               compareMemory(Data, RHS.Data, RHS.Length) == 0);
00139     }
00140 
00141     /// equals_lower - Check for string equality, ignoring case.
00142     bool equals_lower(StringRef RHS) const {
00143       return Length == RHS.Length && compare_lower(RHS) == 0;
00144     }
00145 
00146     /// compare - Compare two strings; the result is -1, 0, or 1 if this string
00147     /// is lexicographically less than, equal to, or greater than the \p RHS.
00148     int compare(StringRef RHS) const {
00149       // Check the prefix for a mismatch.
00150       if (int Res = compareMemory(Data, RHS.Data, min(Length, RHS.Length)))
00151         return Res < 0 ? -1 : 1;
00152 
00153       // Otherwise the prefixes match, so we only need to check the lengths.
00154       if (Length == RHS.Length)
00155         return 0;
00156       return Length < RHS.Length ? -1 : 1;
00157     }
00158 
00159     /// compare_lower - Compare two strings, ignoring case.
00160     int compare_lower(StringRef RHS) const;
00161 
00162     /// compare_numeric - Compare two strings, treating sequences of digits as
00163     /// numbers.
00164     int compare_numeric(StringRef RHS) const;
00165 
00166     /// \brief Determine the edit distance between this string and another
00167     /// string.
00168     ///
00169     /// \param Other the string to compare this string against.
00170     ///
00171     /// \param AllowReplacements whether to allow character
00172     /// replacements (change one character into another) as a single
00173     /// operation, rather than as two operations (an insertion and a
00174     /// removal).
00175     ///
00176     /// \param MaxEditDistance If non-zero, the maximum edit distance that
00177     /// this routine is allowed to compute. If the edit distance will exceed
00178     /// that maximum, returns \c MaxEditDistance+1.
00179     ///
00180     /// \returns the minimum number of character insertions, removals,
00181     /// or (if \p AllowReplacements is \c true) replacements needed to
00182     /// transform one of the given strings into the other. If zero,
00183     /// the strings are identical.
00184     unsigned edit_distance(StringRef Other, bool AllowReplacements = true,
00185                            unsigned MaxEditDistance = 0) const;
00186 
00187     /// str - Get the contents as an std::string.
00188     std::string str() const {
00189       if (!Data) return std::string();
00190       return std::string(Data, Length);
00191     }
00192 
00193     /// @}
00194     /// @name Operator Overloads
00195     /// @{
00196 
00197     char operator[](size_t Index) const {
00198       assert(Index < Length && "Invalid index!");
00199       return Data[Index];
00200     }
00201 
00202     /// @}
00203     /// @name Type Conversions
00204     /// @{
00205 
00206     operator std::string() const {
00207       return str();
00208     }
00209 
00210     /// @}
00211     /// @name String Predicates
00212     /// @{
00213 
00214     /// Check if this string starts with the given \p Prefix.
00215     bool startswith(StringRef Prefix) const {
00216       return Length >= Prefix.Length &&
00217              compareMemory(Data, Prefix.Data, Prefix.Length) == 0;
00218     }
00219 
00220     /// Check if this string starts with the given \p Prefix, ignoring case.
00221     bool startswith_lower(StringRef Prefix) const;
00222 
00223     /// Check if this string ends with the given \p Suffix.
00224     bool endswith(StringRef Suffix) const {
00225       return Length >= Suffix.Length &&
00226         compareMemory(end() - Suffix.Length, Suffix.Data, Suffix.Length) == 0;
00227     }
00228 
00229     /// Check if this string ends with the given \p Suffix, ignoring case.
00230     bool endswith_lower(StringRef Suffix) const;
00231 
00232     /// @}
00233     /// @name String Searching
00234     /// @{
00235 
00236     /// Search for the first character \p C in the string.
00237     ///
00238     /// \returns The index of the first occurrence of \p C, or npos if not
00239     /// found.
00240     size_t find(char C, size_t From = 0) const {
00241       for (size_t i = min(From, Length), e = Length; i != e; ++i)
00242         if (Data[i] == C)
00243           return i;
00244       return npos;
00245     }
00246 
00247     /// Search for the first string \p Str in the string.
00248     ///
00249     /// \returns The index of the first occurrence of \p Str, or npos if not
00250     /// found.
00251     size_t find(StringRef Str, size_t From = 0) const;
00252 
00253     /// Search for the last character \p C in the string.
00254     ///
00255     /// \returns The index of the last occurrence of \p C, or npos if not
00256     /// found.
00257     size_t rfind(char C, size_t From = npos) const {
00258       From = min(From, Length);
00259       size_t i = From;
00260       while (i != 0) {
00261         --i;
00262         if (Data[i] == C)
00263           return i;
00264       }
00265       return npos;
00266     }
00267 
00268     /// Search for the last string \p Str in the string.
00269     ///
00270     /// \returns The index of the last occurrence of \p Str, or npos if not
00271     /// found.
00272     size_t rfind(StringRef Str) const;
00273 
00274     /// Find the first character in the string that is \p C, or npos if not
00275     /// found. Same as find.
00276     size_t find_first_of(char C, size_t From = 0) const {
00277       return find(C, From);
00278     }
00279 
00280     /// Find the first character in the string that is in \p Chars, or npos if
00281     /// not found.
00282     ///
00283     /// Complexity: O(size() + Chars.size())
00284     size_t find_first_of(StringRef Chars, size_t From = 0) const;
00285 
00286     /// Find the first character in the string that is not \p C or npos if not
00287     /// found.
00288     size_t find_first_not_of(char C, size_t From = 0) const;
00289 
00290     /// Find the first character in the string that is not in the string
00291     /// \p Chars, or npos if not found.
00292     ///
00293     /// Complexity: O(size() + Chars.size())
00294     size_t find_first_not_of(StringRef Chars, size_t From = 0) const;
00295 
00296     /// Find the last character in the string that is \p C, or npos if not
00297     /// found.
00298     size_t find_last_of(char C, size_t From = npos) const {
00299       return rfind(C, From);
00300     }
00301 
00302     /// Find the last character in the string that is in \p C, or npos if not
00303     /// found.
00304     ///
00305     /// Complexity: O(size() + Chars.size())
00306     size_t find_last_of(StringRef Chars, size_t From = npos) const;
00307 
00308     /// Find the last character in the string that is not \p C, or npos if not
00309     /// found.
00310     size_t find_last_not_of(char C, size_t From = npos) const;
00311 
00312     /// Find the last character in the string that is not in \p Chars, or
00313     /// npos if not found.
00314     ///
00315     /// Complexity: O(size() + Chars.size())
00316     size_t find_last_not_of(StringRef Chars, size_t From = npos) const;
00317 
00318     /// @}
00319     /// @name Helpful Algorithms
00320     /// @{
00321 
00322     /// Return the number of occurrences of \p C in the string.
00323     size_t count(char C) const {
00324       size_t Count = 0;
00325       for (size_t i = 0, e = Length; i != e; ++i)
00326         if (Data[i] == C)
00327           ++Count;
00328       return Count;
00329     }
00330 
00331     /// Return the number of non-overlapped occurrences of \p Str in
00332     /// the string.
00333     size_t count(StringRef Str) const;
00334 
00335     /// Parse the current string as an integer of the specified radix.  If
00336     /// \p Radix is specified as zero, this does radix autosensing using
00337     /// extended C rules: 0 is octal, 0x is hex, 0b is binary.
00338     ///
00339     /// If the string is invalid or if only a subset of the string is valid,
00340     /// this returns true to signify the error.  The string is considered
00341     /// erroneous if empty or if it overflows T.
00342     template <typename T>
00343     typename std::enable_if<std::numeric_limits<T>::is_signed, bool>::type
00344     getAsInteger(unsigned Radix, T &Result) const {
00345       long long LLVal;
00346       if (getAsSignedInteger(*this, Radix, LLVal) ||
00347             static_cast<T>(LLVal) != LLVal)
00348         return true;
00349       Result = LLVal;
00350       return false;
00351     }
00352 
00353     template <typename T>
00354     typename std::enable_if<!std::numeric_limits<T>::is_signed, bool>::type
00355     getAsInteger(unsigned Radix, T &Result) const {
00356       unsigned long long ULLVal;
00357       if (getAsUnsignedInteger(*this, Radix, ULLVal) ||
00358             static_cast<T>(ULLVal) != ULLVal)
00359         return true;
00360       Result = ULLVal;
00361       return false;
00362     }
00363 
00364     /// Parse the current string as an integer of the specified \p Radix, or of
00365     /// an autosensed radix if the \p Radix given is 0.  The current value in
00366     /// \p Result is discarded, and the storage is changed to be wide enough to
00367     /// store the parsed integer.
00368     ///
00369     /// \returns true if the string does not solely consist of a valid
00370     /// non-empty number in the appropriate base.
00371     ///
00372     /// APInt::fromString is superficially similar but assumes the
00373     /// string is well-formed in the given radix.
00374     bool getAsInteger(unsigned Radix, APInt &Result) const;
00375 
00376     /// @}
00377     /// @name String Operations
00378     /// @{
00379 
00380     // Convert the given ASCII string to lowercase.
00381     std::string lower() const;
00382 
00383     /// Convert the given ASCII string to uppercase.
00384     std::string upper() const;
00385 
00386     /// @}
00387     /// @name Substring Operations
00388     /// @{
00389 
00390     /// Return a reference to the substring from [Start, Start + N).
00391     ///
00392     /// \param Start The index of the starting character in the substring; if
00393     /// the index is npos or greater than the length of the string then the
00394     /// empty substring will be returned.
00395     ///
00396     /// \param N The number of characters to included in the substring. If N
00397     /// exceeds the number of characters remaining in the string, the string
00398     /// suffix (starting with \p Start) will be returned.
00399     StringRef substr(size_t Start, size_t N = npos) const {
00400       Start = min(Start, Length);
00401       return StringRef(Data + Start, min(N, Length - Start));
00402     }
00403 
00404     /// Return a StringRef equal to 'this' but with the first \p N elements
00405     /// dropped.
00406     StringRef drop_front(size_t N = 1) const {
00407       assert(size() >= N && "Dropping more elements than exist");
00408       return substr(N);
00409     }
00410 
00411     /// Return a StringRef equal to 'this' but with the last \p N elements
00412     /// dropped.
00413     StringRef drop_back(size_t N = 1) const {
00414       assert(size() >= N && "Dropping more elements than exist");
00415       return substr(0, size()-N);
00416     }
00417 
00418     /// Return a reference to the substring from [Start, End).
00419     ///
00420     /// \param Start The index of the starting character in the substring; if
00421     /// the index is npos or greater than the length of the string then the
00422     /// empty substring will be returned.
00423     ///
00424     /// \param End The index following the last character to include in the
00425     /// substring. If this is npos, or less than \p Start, or exceeds the
00426     /// number of characters remaining in the string, the string suffix
00427     /// (starting with \p Start) will be returned.
00428     StringRef slice(size_t Start, size_t End) const {
00429       Start = min(Start, Length);
00430       End = min(max(Start, End), Length);
00431       return StringRef(Data + Start, End - Start);
00432     }
00433 
00434     /// Split into two substrings around the first occurrence of a separator
00435     /// character.
00436     ///
00437     /// If \p Separator is in the string, then the result is a pair (LHS, RHS)
00438     /// such that (*this == LHS + Separator + RHS) is true and RHS is
00439     /// maximal. If \p Separator is not in the string, then the result is a
00440     /// pair (LHS, RHS) where (*this == LHS) and (RHS == "").
00441     ///
00442     /// \param Separator The character to split on.
00443     /// \returns The split substrings.
00444     std::pair<StringRef, StringRef> split(char Separator) const {
00445       size_t Idx = find(Separator);
00446       if (Idx == npos)
00447         return std::make_pair(*this, StringRef());
00448       return std::make_pair(slice(0, Idx), slice(Idx+1, npos));
00449     }
00450 
00451     /// Split into two substrings around the first occurrence of a separator
00452     /// string.
00453     ///
00454     /// If \p Separator is in the string, then the result is a pair (LHS, RHS)
00455     /// such that (*this == LHS + Separator + RHS) is true and RHS is
00456     /// maximal. If \p Separator is not in the string, then the result is a
00457     /// pair (LHS, RHS) where (*this == LHS) and (RHS == "").
00458     ///
00459     /// \param Separator - The string to split on.
00460     /// \return - The split substrings.
00461     std::pair<StringRef, StringRef> split(StringRef Separator) const {
00462       size_t Idx = find(Separator);
00463       if (Idx == npos)
00464         return std::make_pair(*this, StringRef());
00465       return std::make_pair(slice(0, Idx), slice(Idx + Separator.size(), npos));
00466     }
00467 
00468     /// Split into substrings around the occurrences of a separator string.
00469     ///
00470     /// Each substring is stored in \p A. If \p MaxSplit is >= 0, at most
00471     /// \p MaxSplit splits are done and consequently <= \p MaxSplit
00472     /// elements are added to A.
00473     /// If \p KeepEmpty is false, empty strings are not added to \p A. They
00474     /// still count when considering \p MaxSplit
00475     /// An useful invariant is that
00476     /// Separator.join(A) == *this if MaxSplit == -1 and KeepEmpty == true
00477     ///
00478     /// \param A - Where to put the substrings.
00479     /// \param Separator - The string to split on.
00480     /// \param MaxSplit - The maximum number of times the string is split.
00481     /// \param KeepEmpty - True if empty substring should be added.
00482     void split(SmallVectorImpl<StringRef> &A,
00483                StringRef Separator, int MaxSplit = -1,
00484                bool KeepEmpty = true) const;
00485 
00486     /// Split into two substrings around the last occurrence of a separator
00487     /// character.
00488     ///
00489     /// If \p Separator is in the string, then the result is a pair (LHS, RHS)
00490     /// such that (*this == LHS + Separator + RHS) is true and RHS is
00491     /// minimal. If \p Separator is not in the string, then the result is a
00492     /// pair (LHS, RHS) where (*this == LHS) and (RHS == "").
00493     ///
00494     /// \param Separator - The character to split on.
00495     /// \return - The split substrings.
00496     std::pair<StringRef, StringRef> rsplit(char Separator) const {
00497       size_t Idx = rfind(Separator);
00498       if (Idx == npos)
00499         return std::make_pair(*this, StringRef());
00500       return std::make_pair(slice(0, Idx), slice(Idx+1, npos));
00501     }
00502 
00503     /// Return string with consecutive characters in \p Chars starting from
00504     /// the left removed.
00505     StringRef ltrim(StringRef Chars = " \t\n\v\f\r") const {
00506       return drop_front(std::min(Length, find_first_not_of(Chars)));
00507     }
00508 
00509     /// Return string with consecutive characters in \p Chars starting from
00510     /// the right removed.
00511     StringRef rtrim(StringRef Chars = " \t\n\v\f\r") const {
00512       return drop_back(Length - std::min(Length, find_last_not_of(Chars) + 1));
00513     }
00514 
00515     /// Return string with consecutive characters in \p Chars starting from
00516     /// the left and right removed.
00517     StringRef trim(StringRef Chars = " \t\n\v\f\r") const {
00518       return ltrim(Chars).rtrim(Chars);
00519     }
00520 
00521     /// @}
00522   };
00523 
00524   /// @name StringRef Comparison Operators
00525   /// @{
00526 
00527   inline bool operator==(StringRef LHS, StringRef RHS) {
00528     return LHS.equals(RHS);
00529   }
00530 
00531   inline bool operator!=(StringRef LHS, StringRef RHS) {
00532     return !(LHS == RHS);
00533   }
00534 
00535   inline bool operator<(StringRef LHS, StringRef RHS) {
00536     return LHS.compare(RHS) == -1;
00537   }
00538 
00539   inline bool operator<=(StringRef LHS, StringRef RHS) {
00540     return LHS.compare(RHS) != 1;
00541   }
00542 
00543   inline bool operator>(StringRef LHS, StringRef RHS) {
00544     return LHS.compare(RHS) == 1;
00545   }
00546 
00547   inline bool operator>=(StringRef LHS, StringRef RHS) {
00548     return LHS.compare(RHS) != -1;
00549   }
00550 
00551   inline std::string &operator+=(std::string &buffer, StringRef string) {
00552     return buffer.append(string.data(), string.size());
00553   }
00554 
00555   /// @}
00556 
00557   /// \brief Compute a hash_code for a StringRef.
00558   hash_code hash_value(StringRef S);
00559 
00560   // StringRefs can be treated like a POD type.
00561   template <typename T> struct isPodLike;
00562   template <> struct isPodLike<StringRef> { static const bool value = true; };
00563 }
00564 
00565 #endif