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 <algorithm>
00014 #include <cassert>
00015 #include <cstring>
00016 #include <limits>
00017 #include <string>
00018 #include <utility>
00019 
00020 namespace llvm {
00021   template <typename T>
00022   class SmallVectorImpl;
00023   class APInt;
00024   class hash_code;
00025   class StringRef;
00026 
00027   /// Helper functions for StringRef::getAsInteger.
00028   bool getAsUnsignedInteger(StringRef Str, unsigned Radix,
00029                             unsigned long long &Result);
00030 
00031   bool getAsSignedInteger(StringRef Str, unsigned Radix, long long &Result);
00032 
00033   /// StringRef - Represent a constant reference to a string, i.e. a character
00034   /// array and a length, which need not be null terminated.
00035   ///
00036   /// This class does not own the string data, it is expected to be used in
00037   /// situations where the character data resides in some other buffer, whose
00038   /// lifetime extends past that of the StringRef. For this reason, it is not in
00039   /// general safe to store a StringRef.
00040   class StringRef {
00041   public:
00042     typedef const char *iterator;
00043     typedef const char *const_iterator;
00044     static const size_t npos = ~size_t(0);
00045     typedef size_t size_type;
00046 
00047   private:
00048     /// The start of the string, in an external buffer.
00049     const char *Data;
00050 
00051     /// The length of the string.
00052     size_t Length;
00053 
00054     // Workaround memcmp issue with null pointers (undefined behavior)
00055     // by providing a specialized version
00056     static int compareMemory(const char *Lhs, const char *Rhs, size_t Length) {
00057       if (Length == 0) { return 0; }
00058       return ::memcmp(Lhs,Rhs,Length);
00059     }
00060 
00061   public:
00062     /// @name Constructors
00063     /// @{
00064 
00065     /// Construct an empty string ref.
00066     /*implicit*/ StringRef() : Data(nullptr), Length(0) {}
00067 
00068     /// Construct a string ref from a cstring.
00069     /*implicit*/ StringRef(const char *Str)
00070       : Data(Str) {
00071         assert(Str && "StringRef cannot be built from a NULL argument");
00072         Length = ::strlen(Str); // invoking strlen(NULL) is undefined behavior
00073       }
00074 
00075     /// Construct a string ref from a pointer and length.
00076     /*implicit*/ StringRef(const char *data, size_t length)
00077       : Data(data), Length(length) {
00078         assert((data || length == 0) &&
00079         "StringRef cannot be built from a NULL argument with non-null length");
00080       }
00081 
00082     /// Construct a string ref from an std::string.
00083     /*implicit*/ StringRef(const std::string &Str)
00084       : Data(Str.data()), Length(Str.length()) {}
00085 
00086     /// @}
00087     /// @name Iterators
00088     /// @{
00089 
00090     iterator begin() const { return Data; }
00091 
00092     iterator end() const { return Data + Length; }
00093 
00094     const unsigned char *bytes_begin() const {
00095       return reinterpret_cast<const unsigned char *>(begin());
00096     }
00097     const unsigned char *bytes_end() const {
00098       return reinterpret_cast<const unsigned char *>(end());
00099     }
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 Allocator and return StringRef to it.
00128     template <typename Allocator> StringRef copy(Allocator &A) const {
00129       char *S = A.template 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, std::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 = std::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 = std::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       // The additional cast to unsigned long long is required to avoid the
00358       // Visual C++ warning C4805: '!=' : unsafe mix of type 'bool' and type
00359       // 'unsigned __int64' when instantiating getAsInteger with T = bool.
00360       if (getAsUnsignedInteger(*this, Radix, ULLVal) ||
00361           static_cast<unsigned long long>(static_cast<T>(ULLVal)) != ULLVal)
00362         return true;
00363       Result = ULLVal;
00364       return false;
00365     }
00366 
00367     /// Parse the current string as an integer of the specified \p Radix, or of
00368     /// an autosensed radix if the \p Radix given is 0.  The current value in
00369     /// \p Result is discarded, and the storage is changed to be wide enough to
00370     /// store the parsed integer.
00371     ///
00372     /// \returns true if the string does not solely consist of a valid
00373     /// non-empty number in the appropriate base.
00374     ///
00375     /// APInt::fromString is superficially similar but assumes the
00376     /// string is well-formed in the given radix.
00377     bool getAsInteger(unsigned Radix, APInt &Result) const;
00378 
00379     /// @}
00380     /// @name String Operations
00381     /// @{
00382 
00383     // Convert the given ASCII string to lowercase.
00384     std::string lower() const;
00385 
00386     /// Convert the given ASCII string to uppercase.
00387     std::string upper() const;
00388 
00389     /// @}
00390     /// @name Substring Operations
00391     /// @{
00392 
00393     /// Return a reference to the substring from [Start, Start + N).
00394     ///
00395     /// \param Start The index of the starting character in the substring; if
00396     /// the index is npos or greater than the length of the string then the
00397     /// empty substring will be returned.
00398     ///
00399     /// \param N The number of characters to included in the substring. If N
00400     /// exceeds the number of characters remaining in the string, the string
00401     /// suffix (starting with \p Start) will be returned.
00402     StringRef substr(size_t Start, size_t N = npos) const {
00403       Start = std::min(Start, Length);
00404       return StringRef(Data + Start, std::min(N, Length - Start));
00405     }
00406 
00407     /// Return a StringRef equal to 'this' but with the first \p N elements
00408     /// dropped.
00409     StringRef drop_front(size_t N = 1) const {
00410       assert(size() >= N && "Dropping more elements than exist");
00411       return substr(N);
00412     }
00413 
00414     /// Return a StringRef equal to 'this' but with the last \p N elements
00415     /// dropped.
00416     StringRef drop_back(size_t N = 1) const {
00417       assert(size() >= N && "Dropping more elements than exist");
00418       return substr(0, size()-N);
00419     }
00420 
00421     /// Return a reference to the substring from [Start, End).
00422     ///
00423     /// \param Start The index of the starting character in the substring; if
00424     /// the index is npos or greater than the length of the string then the
00425     /// empty substring will be returned.
00426     ///
00427     /// \param End The index following the last character to include in the
00428     /// substring. If this is npos, or less than \p Start, or exceeds the
00429     /// number of characters remaining in the string, the string suffix
00430     /// (starting with \p Start) will be returned.
00431     StringRef slice(size_t Start, size_t End) const {
00432       Start = std::min(Start, Length);
00433       End = std::min(std::max(Start, End), Length);
00434       return StringRef(Data + Start, End - Start);
00435     }
00436 
00437     /// Split into two substrings around the first occurrence of a separator
00438     /// character.
00439     ///
00440     /// If \p Separator is in the string, then the result is a pair (LHS, RHS)
00441     /// such that (*this == LHS + Separator + RHS) is true and RHS is
00442     /// maximal. If \p Separator is not in the string, then the result is a
00443     /// pair (LHS, RHS) where (*this == LHS) and (RHS == "").
00444     ///
00445     /// \param Separator The character to split on.
00446     /// \returns The split substrings.
00447     std::pair<StringRef, StringRef> split(char Separator) const {
00448       size_t Idx = find(Separator);
00449       if (Idx == npos)
00450         return std::make_pair(*this, StringRef());
00451       return std::make_pair(slice(0, Idx), slice(Idx+1, npos));
00452     }
00453 
00454     /// Split into two substrings around the first occurrence of a separator
00455     /// string.
00456     ///
00457     /// If \p Separator is in the string, then the result is a pair (LHS, RHS)
00458     /// such that (*this == LHS + Separator + RHS) is true and RHS is
00459     /// maximal. If \p Separator is not in the string, then the result is a
00460     /// pair (LHS, RHS) where (*this == LHS) and (RHS == "").
00461     ///
00462     /// \param Separator - The string to split on.
00463     /// \return - The split substrings.
00464     std::pair<StringRef, StringRef> split(StringRef Separator) const {
00465       size_t Idx = find(Separator);
00466       if (Idx == npos)
00467         return std::make_pair(*this, StringRef());
00468       return std::make_pair(slice(0, Idx), slice(Idx + Separator.size(), npos));
00469     }
00470 
00471     /// Split into substrings around the occurrences of a separator string.
00472     ///
00473     /// Each substring is stored in \p A. If \p MaxSplit is >= 0, at most
00474     /// \p MaxSplit splits are done and consequently <= \p MaxSplit
00475     /// elements are added to A.
00476     /// If \p KeepEmpty is false, empty strings are not added to \p A. They
00477     /// still count when considering \p MaxSplit
00478     /// An useful invariant is that
00479     /// Separator.join(A) == *this if MaxSplit == -1 and KeepEmpty == true
00480     ///
00481     /// \param A - Where to put the substrings.
00482     /// \param Separator - The string to split on.
00483     /// \param MaxSplit - The maximum number of times the string is split.
00484     /// \param KeepEmpty - True if empty substring should be added.
00485     void split(SmallVectorImpl<StringRef> &A,
00486                StringRef Separator, int MaxSplit = -1,
00487                bool KeepEmpty = true) const;
00488 
00489     /// Split into two substrings around the last occurrence of a separator
00490     /// character.
00491     ///
00492     /// If \p Separator is in the string, then the result is a pair (LHS, RHS)
00493     /// such that (*this == LHS + Separator + RHS) is true and RHS is
00494     /// minimal. If \p Separator is not in the string, then the result is a
00495     /// pair (LHS, RHS) where (*this == LHS) and (RHS == "").
00496     ///
00497     /// \param Separator - The character to split on.
00498     /// \return - The split substrings.
00499     std::pair<StringRef, StringRef> rsplit(char Separator) const {
00500       size_t Idx = rfind(Separator);
00501       if (Idx == npos)
00502         return std::make_pair(*this, StringRef());
00503       return std::make_pair(slice(0, Idx), slice(Idx+1, npos));
00504     }
00505 
00506     /// Return string with consecutive characters in \p Chars starting from
00507     /// the left removed.
00508     StringRef ltrim(StringRef Chars = " \t\n\v\f\r") const {
00509       return drop_front(std::min(Length, find_first_not_of(Chars)));
00510     }
00511 
00512     /// Return string with consecutive characters in \p Chars starting from
00513     /// the right removed.
00514     StringRef rtrim(StringRef Chars = " \t\n\v\f\r") const {
00515       return drop_back(Length - std::min(Length, find_last_not_of(Chars) + 1));
00516     }
00517 
00518     /// Return string with consecutive characters in \p Chars starting from
00519     /// the left and right removed.
00520     StringRef trim(StringRef Chars = " \t\n\v\f\r") const {
00521       return ltrim(Chars).rtrim(Chars);
00522     }
00523 
00524     /// @}
00525   };
00526 
00527   /// @name StringRef Comparison Operators
00528   /// @{
00529 
00530   inline bool operator==(StringRef LHS, StringRef RHS) {
00531     return LHS.equals(RHS);
00532   }
00533 
00534   inline bool operator!=(StringRef LHS, StringRef RHS) {
00535     return !(LHS == RHS);
00536   }
00537 
00538   inline bool operator<(StringRef LHS, StringRef RHS) {
00539     return LHS.compare(RHS) == -1;
00540   }
00541 
00542   inline bool operator<=(StringRef LHS, StringRef RHS) {
00543     return LHS.compare(RHS) != 1;
00544   }
00545 
00546   inline bool operator>(StringRef LHS, StringRef RHS) {
00547     return LHS.compare(RHS) == 1;
00548   }
00549 
00550   inline bool operator>=(StringRef LHS, StringRef RHS) {
00551     return LHS.compare(RHS) != -1;
00552   }
00553 
00554   inline std::string &operator+=(std::string &buffer, StringRef string) {
00555     return buffer.append(string.data(), string.size());
00556   }
00557 
00558   /// @}
00559 
00560   /// \brief Compute a hash_code for a StringRef.
00561   hash_code hash_value(StringRef S);
00562 
00563   // StringRefs can be treated like a POD type.
00564   template <typename T> struct isPodLike;
00565   template <> struct isPodLike<StringRef> { static const bool value = true; };
00566 }
00567 
00568 #endif