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/type_traits.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(0), 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     /// equals - Check for string equality, this is more efficient than
00128     /// compare() when the relative ordering of inequal strings isn't needed.
00129     bool equals(StringRef RHS) const {
00130       return (Length == RHS.Length &&
00131               compareMemory(Data, RHS.Data, RHS.Length) == 0);
00132     }
00133 
00134     /// equals_lower - Check for string equality, ignoring case.
00135     bool equals_lower(StringRef RHS) const {
00136       return Length == RHS.Length && compare_lower(RHS) == 0;
00137     }
00138 
00139     /// compare - Compare two strings; the result is -1, 0, or 1 if this string
00140     /// is lexicographically less than, equal to, or greater than the \p RHS.
00141     int compare(StringRef RHS) const {
00142       // Check the prefix for a mismatch.
00143       if (int Res = compareMemory(Data, RHS.Data, min(Length, RHS.Length)))
00144         return Res < 0 ? -1 : 1;
00145 
00146       // Otherwise the prefixes match, so we only need to check the lengths.
00147       if (Length == RHS.Length)
00148         return 0;
00149       return Length < RHS.Length ? -1 : 1;
00150     }
00151 
00152     /// compare_lower - Compare two strings, ignoring case.
00153     int compare_lower(StringRef RHS) const;
00154 
00155     /// compare_numeric - Compare two strings, treating sequences of digits as
00156     /// numbers.
00157     int compare_numeric(StringRef RHS) const;
00158 
00159     /// \brief Determine the edit distance between this string and another
00160     /// string.
00161     ///
00162     /// \param Other the string to compare this string against.
00163     ///
00164     /// \param AllowReplacements whether to allow character
00165     /// replacements (change one character into another) as a single
00166     /// operation, rather than as two operations (an insertion and a
00167     /// removal).
00168     ///
00169     /// \param MaxEditDistance If non-zero, the maximum edit distance that
00170     /// this routine is allowed to compute. If the edit distance will exceed
00171     /// that maximum, returns \c MaxEditDistance+1.
00172     ///
00173     /// \returns the minimum number of character insertions, removals,
00174     /// or (if \p AllowReplacements is \c true) replacements needed to
00175     /// transform one of the given strings into the other. If zero,
00176     /// the strings are identical.
00177     unsigned edit_distance(StringRef Other, bool AllowReplacements = true,
00178                            unsigned MaxEditDistance = 0);
00179 
00180     /// str - Get the contents as an std::string.
00181     std::string str() const {
00182       if (Data == 0) return std::string();
00183       return std::string(Data, Length);
00184     }
00185 
00186     /// @}
00187     /// @name Operator Overloads
00188     /// @{
00189 
00190     char operator[](size_t Index) const {
00191       assert(Index < Length && "Invalid index!");
00192       return Data[Index];
00193     }
00194 
00195     /// @}
00196     /// @name Type Conversions
00197     /// @{
00198 
00199     operator std::string() const {
00200       return str();
00201     }
00202 
00203     /// @}
00204     /// @name String Predicates
00205     /// @{
00206 
00207     /// Check if this string starts with the given \p Prefix.
00208     bool startswith(StringRef Prefix) const {
00209       return Length >= Prefix.Length &&
00210              compareMemory(Data, Prefix.Data, Prefix.Length) == 0;
00211     }
00212 
00213     /// Check if this string ends with the given \p Suffix.
00214     bool endswith(StringRef Suffix) const {
00215       return Length >= Suffix.Length &&
00216         compareMemory(end() - Suffix.Length, Suffix.Data, Suffix.Length) == 0;
00217     }
00218 
00219     /// @}
00220     /// @name String Searching
00221     /// @{
00222 
00223     /// Search for the first character \p C in the string.
00224     ///
00225     /// \returns The index of the first occurrence of \p C, or npos if not
00226     /// found.
00227     size_t find(char C, size_t From = 0) const {
00228       for (size_t i = min(From, Length), e = Length; i != e; ++i)
00229         if (Data[i] == C)
00230           return i;
00231       return npos;
00232     }
00233 
00234     /// Search for the first string \p Str in the string.
00235     ///
00236     /// \returns The index of the first occurrence of \p Str, or npos if not
00237     /// found.
00238     size_t find(StringRef Str, size_t From = 0) const;
00239 
00240     /// Search for the last character \p C in the string.
00241     ///
00242     /// \returns The index of the last occurrence of \p C, or npos if not
00243     /// found.
00244     size_t rfind(char C, size_t From = npos) const {
00245       From = min(From, Length);
00246       size_t i = From;
00247       while (i != 0) {
00248         --i;
00249         if (Data[i] == C)
00250           return i;
00251       }
00252       return npos;
00253     }
00254 
00255     /// Search for the last string \p Str in the string.
00256     ///
00257     /// \returns The index of the last occurrence of \p Str, or npos if not
00258     /// found.
00259     size_t rfind(StringRef Str) const;
00260 
00261     /// Find the first character in the string that is \p C, or npos if not
00262     /// found. Same as find.
00263     size_t find_first_of(char C, size_t From = 0) const {
00264       return find(C, From);
00265     }
00266 
00267     /// Find the first character in the string that is in \p Chars, or npos if
00268     /// not found.
00269     ///
00270     /// Complexity: O(size() + Chars.size())
00271     size_t find_first_of(StringRef Chars, size_t From = 0) const;
00272 
00273     /// Find the first character in the string that is not \p C or npos if not
00274     /// found.
00275     size_t find_first_not_of(char C, size_t From = 0) const;
00276 
00277     /// Find the first character in the string that is not in the string
00278     /// \p Chars, or npos if not found.
00279     ///
00280     /// Complexity: O(size() + Chars.size())
00281     size_t find_first_not_of(StringRef Chars, size_t From = 0) const;
00282 
00283     /// Find the last character in the string that is \p C, or npos if not
00284     /// found.
00285     size_t find_last_of(char C, size_t From = npos) const {
00286       return rfind(C, From);
00287     }
00288 
00289     /// Find the last character in the string that is in \p C, or npos if not
00290     /// found.
00291     ///
00292     /// Complexity: O(size() + Chars.size())
00293     size_t find_last_of(StringRef Chars, size_t From = npos) const;
00294 
00295     /// Find the last character in the string that is not \p C, or npos if not
00296     /// found.
00297     size_t find_last_not_of(char C, size_t From = npos) const;
00298 
00299     /// Find the last character in the string that is not in \p Chars, or
00300     /// npos if not found.
00301     ///
00302     /// Complexity: O(size() + Chars.size())
00303     size_t find_last_not_of(StringRef Chars, size_t From = npos) const;
00304 
00305     /// @}
00306     /// @name Helpful Algorithms
00307     /// @{
00308 
00309     /// Return the number of occurrences of \p C in the string.
00310     size_t count(char C) const {
00311       size_t Count = 0;
00312       for (size_t i = 0, e = Length; i != e; ++i)
00313         if (Data[i] == C)
00314           ++Count;
00315       return Count;
00316     }
00317 
00318     /// Return the number of non-overlapped occurrences of \p Str in
00319     /// the string.
00320     size_t count(StringRef Str) const;
00321 
00322     /// Parse the current string as an integer of the specified radix.  If
00323     /// \p Radix is specified as zero, this does radix autosensing using
00324     /// extended C rules: 0 is octal, 0x is hex, 0b is binary.
00325     ///
00326     /// If the string is invalid or if only a subset of the string is valid,
00327     /// this returns true to signify the error.  The string is considered
00328     /// erroneous if empty or if it overflows T.
00329     template <typename T>
00330     typename enable_if_c<std::numeric_limits<T>::is_signed, bool>::type
00331     getAsInteger(unsigned Radix, T &Result) const {
00332       long long LLVal;
00333       if (getAsSignedInteger(*this, Radix, LLVal) ||
00334             static_cast<T>(LLVal) != LLVal)
00335         return true;
00336       Result = LLVal;
00337       return false;
00338     }
00339 
00340     template <typename T>
00341     typename enable_if_c<!std::numeric_limits<T>::is_signed, bool>::type
00342     getAsInteger(unsigned Radix, T &Result) const {
00343       unsigned long long ULLVal;
00344       if (getAsUnsignedInteger(*this, Radix, ULLVal) ||
00345             static_cast<T>(ULLVal) != ULLVal)
00346         return true;
00347       Result = ULLVal;
00348       return false;
00349     }
00350 
00351     /// Parse the current string as an integer of the specified \p Radix, or of
00352     /// an autosensed radix if the \p Radix given is 0.  The current value in
00353     /// \p Result is discarded, and the storage is changed to be wide enough to
00354     /// store the parsed integer.
00355     ///
00356     /// \returns true if the string does not solely consist of a valid
00357     /// non-empty number in the appropriate base.
00358     ///
00359     /// APInt::fromString is superficially similar but assumes the
00360     /// string is well-formed in the given radix.
00361     bool getAsInteger(unsigned Radix, APInt &Result) const;
00362 
00363     /// @}
00364     /// @name String Operations
00365     /// @{
00366 
00367     // Convert the given ASCII string to lowercase.
00368     std::string lower() const;
00369 
00370     /// Convert the given ASCII string to uppercase.
00371     std::string upper() const;
00372 
00373     /// @}
00374     /// @name Substring Operations
00375     /// @{
00376 
00377     /// Return a reference to the substring from [Start, Start + N).
00378     ///
00379     /// \param Start The index of the starting character in the substring; if
00380     /// the index is npos or greater than the length of the string then the
00381     /// empty substring will be returned.
00382     ///
00383     /// \param N The number of characters to included in the substring. If N
00384     /// exceeds the number of characters remaining in the string, the string
00385     /// suffix (starting with \p Start) will be returned.
00386     StringRef substr(size_t Start, size_t N = npos) const {
00387       Start = min(Start, Length);
00388       return StringRef(Data + Start, min(N, Length - Start));
00389     }
00390 
00391     /// Return a StringRef equal to 'this' but with the first \p N elements
00392     /// dropped.
00393     StringRef drop_front(size_t N = 1) const {
00394       assert(size() >= N && "Dropping more elements than exist");
00395       return substr(N);
00396     }
00397 
00398     /// Return a StringRef equal to 'this' but with the last \p N elements
00399     /// dropped.
00400     StringRef drop_back(size_t N = 1) const {
00401       assert(size() >= N && "Dropping more elements than exist");
00402       return substr(0, size()-N);
00403     }
00404 
00405     /// Return a reference to the substring from [Start, End).
00406     ///
00407     /// \param Start The index of the starting character in the substring; if
00408     /// the index is npos or greater than the length of the string then the
00409     /// empty substring will be returned.
00410     ///
00411     /// \param End The index following the last character to include in the
00412     /// substring. If this is npos, or less than \p Start, or exceeds the
00413     /// number of characters remaining in the string, the string suffix
00414     /// (starting with \p Start) will be returned.
00415     StringRef slice(size_t Start, size_t End) const {
00416       Start = min(Start, Length);
00417       End = min(max(Start, End), Length);
00418       return StringRef(Data + Start, End - Start);
00419     }
00420 
00421     /// Split into two substrings around the first occurrence of a separator
00422     /// character.
00423     ///
00424     /// If \p Separator is in the string, then the result is a pair (LHS, RHS)
00425     /// such that (*this == LHS + Separator + RHS) is true and RHS is
00426     /// maximal. If \p Separator is not in the string, then the result is a
00427     /// pair (LHS, RHS) where (*this == LHS) and (RHS == "").
00428     ///
00429     /// \param Separator The character to split on.
00430     /// \returns The split substrings.
00431     std::pair<StringRef, StringRef> split(char Separator) const {
00432       size_t Idx = find(Separator);
00433       if (Idx == npos)
00434         return std::make_pair(*this, StringRef());
00435       return std::make_pair(slice(0, Idx), slice(Idx+1, npos));
00436     }
00437 
00438     /// Split into two substrings around the first occurrence of a separator
00439     /// string.
00440     ///
00441     /// If \p Separator is in the string, then the result is a pair (LHS, RHS)
00442     /// such that (*this == LHS + Separator + RHS) is true and RHS is
00443     /// maximal. If \p Separator is not in the string, then the result is a
00444     /// pair (LHS, RHS) where (*this == LHS) and (RHS == "").
00445     ///
00446     /// \param Separator - The string to split on.
00447     /// \return - The split substrings.
00448     std::pair<StringRef, StringRef> split(StringRef Separator) const {
00449       size_t Idx = find(Separator);
00450       if (Idx == npos)
00451         return std::make_pair(*this, StringRef());
00452       return std::make_pair(slice(0, Idx), slice(Idx + Separator.size(), npos));
00453     }
00454 
00455     /// Split into substrings around the occurrences of a separator string.
00456     ///
00457     /// Each substring is stored in \p A. If \p MaxSplit is >= 0, at most
00458     /// \p MaxSplit splits are done and consequently <= \p MaxSplit
00459     /// elements are added to A.
00460     /// If \p KeepEmpty is false, empty strings are not added to \p A. They
00461     /// still count when considering \p MaxSplit
00462     /// An useful invariant is that
00463     /// Separator.join(A) == *this if MaxSplit == -1 and KeepEmpty == true
00464     ///
00465     /// \param A - Where to put the substrings.
00466     /// \param Separator - The string to split on.
00467     /// \param MaxSplit - The maximum number of times the string is split.
00468     /// \param KeepEmpty - True if empty substring should be added.
00469     void split(SmallVectorImpl<StringRef> &A,
00470                StringRef Separator, int MaxSplit = -1,
00471                bool KeepEmpty = true) const;
00472 
00473     /// Split into two substrings around the last occurrence of a separator
00474     /// character.
00475     ///
00476     /// If \p Separator is in the string, then the result is a pair (LHS, RHS)
00477     /// such that (*this == LHS + Separator + RHS) is true and RHS is
00478     /// minimal. If \p Separator is not in the string, then the result is a
00479     /// pair (LHS, RHS) where (*this == LHS) and (RHS == "").
00480     ///
00481     /// \param Separator - The character to split on.
00482     /// \return - The split substrings.
00483     std::pair<StringRef, StringRef> rsplit(char Separator) const {
00484       size_t Idx = rfind(Separator);
00485       if (Idx == npos)
00486         return std::make_pair(*this, StringRef());
00487       return std::make_pair(slice(0, Idx), slice(Idx+1, npos));
00488     }
00489 
00490     /// Return string with consecutive characters in \p Chars starting from
00491     /// the left removed.
00492     StringRef ltrim(StringRef Chars = " \t\n\v\f\r") const {
00493       return drop_front(std::min(Length, find_first_not_of(Chars)));
00494     }
00495 
00496     /// Return string with consecutive characters in \p Chars starting from
00497     /// the right removed.
00498     StringRef rtrim(StringRef Chars = " \t\n\v\f\r") const {
00499       return drop_back(Length - std::min(Length, find_last_not_of(Chars) + 1));
00500     }
00501 
00502     /// Return string with consecutive characters in \p Chars starting from
00503     /// the left and right removed.
00504     StringRef trim(StringRef Chars = " \t\n\v\f\r") const {
00505       return ltrim(Chars).rtrim(Chars);
00506     }
00507 
00508     /// @}
00509   };
00510 
00511   /// @name StringRef Comparison Operators
00512   /// @{
00513 
00514   inline bool operator==(StringRef LHS, StringRef RHS) {
00515     return LHS.equals(RHS);
00516   }
00517 
00518   inline bool operator!=(StringRef LHS, StringRef RHS) {
00519     return !(LHS == RHS);
00520   }
00521 
00522   inline bool operator<(StringRef LHS, StringRef RHS) {
00523     return LHS.compare(RHS) == -1;
00524   }
00525 
00526   inline bool operator<=(StringRef LHS, StringRef RHS) {
00527     return LHS.compare(RHS) != 1;
00528   }
00529 
00530   inline bool operator>(StringRef LHS, StringRef RHS) {
00531     return LHS.compare(RHS) == 1;
00532   }
00533 
00534   inline bool operator>=(StringRef LHS, StringRef RHS) {
00535     return LHS.compare(RHS) != -1;
00536   }
00537 
00538   inline std::string &operator+=(std::string &buffer, StringRef string) {
00539     return buffer.append(string.data(), string.size());
00540   }
00541 
00542   /// @}
00543 
00544   /// \brief Compute a hash_code for a StringRef.
00545   hash_code hash_value(StringRef S);
00546 
00547   // StringRefs can be treated like a POD type.
00548   template <typename T> struct isPodLike;
00549   template <> struct isPodLike<StringRef> { static const bool value = true; };
00550 
00551 }
00552 
00553 #endif