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 
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 \arg 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     /// startswith - Check if this string starts with the given \arg Prefix.
00208     bool startswith(StringRef Prefix) const {
00209       return Length >= Prefix.Length &&
00210              compareMemory(Data, Prefix.Data, Prefix.Length) == 0;
00211     }
00212 
00213     /// endswith - Check if this string ends with the given \arg 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     /// find - Search for the first character \arg C in the string.
00224     ///
00225     /// \return - The index of the first occurrence of \arg 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     /// find - Search for the first string \arg Str in the string.
00235     ///
00236     /// \return - The index of the first occurrence of \arg Str, or npos if not
00237     /// found.
00238     size_t find(StringRef Str, size_t From = 0) const;
00239 
00240     /// rfind - Search for the last character \arg C in the string.
00241     ///
00242     /// \return - The index of the last occurrence of \arg 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     /// rfind - Search for the last string \arg Str in the string.
00256     ///
00257     /// \return - The index of the last occurrence of \arg Str, or npos if not
00258     /// found.
00259     size_t rfind(StringRef Str) const;
00260 
00261     /// find_first_of - Find the first character in the string that is \arg C,
00262     /// or npos if not found. Same as find.
00263     size_type find_first_of(char C, size_t From = 0) const {
00264       return find(C, From);
00265     }
00266 
00267     /// find_first_of - Find the first character in the string that is in \arg
00268     /// Chars, or npos if not found.
00269     ///
00270     /// Note: O(size() + Chars.size())
00271     size_type find_first_of(StringRef Chars, size_t From = 0) const;
00272 
00273     /// find_first_not_of - Find the first character in the string that is not
00274     /// \arg C or npos if not found.
00275     size_type find_first_not_of(char C, size_t From = 0) const;
00276 
00277     /// find_first_not_of - Find the first character in the string that is not
00278     /// in the string \arg Chars, or npos if not found.
00279     ///
00280     /// Note: O(size() + Chars.size())
00281     size_type find_first_not_of(StringRef Chars, size_t From = 0) const;
00282 
00283     /// find_last_of - Find the last character in the string that is \arg C, or
00284     /// npos if not found.
00285     size_type find_last_of(char C, size_t From = npos) const {
00286       return rfind(C, From);
00287     }
00288 
00289     /// find_last_of - Find the last character in the string that is in \arg C,
00290     /// or npos if not found.
00291     ///
00292     /// Note: O(size() + Chars.size())
00293     size_type find_last_of(StringRef Chars, size_t From = npos) const;
00294 
00295     /// find_last_not_of - Find the last character in the string that is not
00296     /// \arg C, or npos if not found.
00297     size_type find_last_not_of(char C, size_t From = npos) const;
00298 
00299     /// find_last_not_of - Find the last character in the string that is not in
00300     /// \arg Chars, or npos if not found.
00301     ///
00302     /// Note: O(size() + Chars.size())
00303     size_type find_last_not_of(StringRef Chars, size_t From = npos) const;
00304 
00305     /// @}
00306     /// @name Helpful Algorithms
00307     /// @{
00308 
00309     /// count - Return the number of occurrences of \arg 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     /// count - Return the number of non-overlapped occurrences of \arg Str in
00319     /// the string.
00320     size_t count(StringRef Str) const;
00321 
00322     /// getAsInteger - Parse the current string as an integer of the specified
00323     /// radix.  If 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     ///
00330     template <typename T>
00331     typename enable_if_c<std::numeric_limits<T>::is_signed, bool>::type
00332     getAsInteger(unsigned Radix, T &Result) const {
00333       long long LLVal;
00334       if (getAsSignedInteger(*this, Radix, LLVal) ||
00335             static_cast<T>(LLVal) != LLVal)
00336         return true;
00337       Result = LLVal;
00338       return false;
00339     }
00340 
00341     template <typename T>
00342     typename enable_if_c<!std::numeric_limits<T>::is_signed, bool>::type
00343     getAsInteger(unsigned Radix, T &Result) const {
00344       unsigned long long ULLVal;
00345       if (getAsUnsignedInteger(*this, Radix, ULLVal) ||
00346             static_cast<T>(ULLVal) != ULLVal)
00347         return true;
00348       Result = ULLVal;
00349       return false;
00350     }
00351 
00352     /// getAsInteger - Parse the current string as an integer of the
00353     /// specified radix, or of an autosensed radix if the radix given
00354     /// is 0.  The current value in Result is discarded, and the
00355     /// storage is changed to be wide enough to store the parsed
00356     /// integer.
00357     ///
00358     /// Returns true if the string does not solely consist of a valid
00359     /// non-empty number in the appropriate base.
00360     ///
00361     /// APInt::fromString is superficially similar but assumes the
00362     /// string is well-formed in the given radix.
00363     bool getAsInteger(unsigned Radix, APInt &Result) const;
00364 
00365     /// @}
00366     /// @name String Operations
00367     /// @{
00368 
00369     // lower - Convert the given ASCII string to lowercase.
00370     std::string lower() const;
00371 
00372     /// upper - Convert the given ASCII string to uppercase.
00373     std::string upper() const;
00374 
00375     /// @}
00376     /// @name Substring Operations
00377     /// @{
00378 
00379     /// substr - Return a reference to the substring from [Start, Start + N).
00380     ///
00381     /// \param Start - The index of the starting character in the substring; if
00382     /// the index is npos or greater than the length of the string then the
00383     /// empty substring will be returned.
00384     ///
00385     /// \param N - The number of characters to included in the substring. If N
00386     /// exceeds the number of characters remaining in the string, the string
00387     /// suffix (starting with \arg Start) will be returned.
00388     StringRef substr(size_t Start, size_t N = npos) const {
00389       Start = min(Start, Length);
00390       return StringRef(Data + Start, min(N, Length - Start));
00391     }
00392     
00393     /// drop_front - Return a StringRef equal to 'this' but with the first
00394     /// elements dropped.
00395     StringRef drop_front(unsigned N = 1) const {
00396       assert(size() >= N && "Dropping more elements than exist");
00397       return substr(N);
00398     }
00399 
00400     /// drop_back - Return a StringRef equal to 'this' but with the last
00401     /// elements dropped.
00402     StringRef drop_back(unsigned N = 1) const {
00403       assert(size() >= N && "Dropping more elements than exist");
00404       return substr(0, size()-N);
00405     }
00406 
00407     /// slice - Return a reference to the substring from [Start, End).
00408     ///
00409     /// \param Start - The index of the starting character in the substring; if
00410     /// the index is npos or greater than the length of the string then the
00411     /// empty substring will be returned.
00412     ///
00413     /// \param End - The index following the last character to include in the
00414     /// substring. If this is npos, or less than \arg Start, or exceeds the
00415     /// number of characters remaining in the string, the string suffix
00416     /// (starting with \arg Start) will be returned.
00417     StringRef slice(size_t Start, size_t End) const {
00418       Start = min(Start, Length);
00419       End = min(max(Start, End), Length);
00420       return StringRef(Data + Start, End - Start);
00421     }
00422 
00423     /// split - Split into two substrings around the first occurrence of a
00424     /// separator character.
00425     ///
00426     /// If \arg Separator is in the string, then the result is a pair (LHS, RHS)
00427     /// such that (*this == LHS + Separator + RHS) is true and RHS is
00428     /// maximal. If \arg Separator is not in the string, then the result is a
00429     /// pair (LHS, RHS) where (*this == LHS) and (RHS == "").
00430     ///
00431     /// \param Separator - The character to split on.
00432     /// \return - The split substrings.
00433     std::pair<StringRef, StringRef> split(char Separator) const {
00434       size_t Idx = find(Separator);
00435       if (Idx == npos)
00436         return std::make_pair(*this, StringRef());
00437       return std::make_pair(slice(0, Idx), slice(Idx+1, npos));
00438     }
00439 
00440     /// split - Split into two substrings around the first occurrence of a
00441     /// separator string.
00442     ///
00443     /// If \arg Separator is in the string, then the result is a pair (LHS, RHS)
00444     /// such that (*this == LHS + Separator + RHS) is true and RHS is
00445     /// maximal. If \arg Separator is not in the string, then the result is a
00446     /// pair (LHS, RHS) where (*this == LHS) and (RHS == "").
00447     ///
00448     /// \param Separator - The string to split on.
00449     /// \return - The split substrings.
00450     std::pair<StringRef, StringRef> split(StringRef Separator) const {
00451       size_t Idx = find(Separator);
00452       if (Idx == npos)
00453         return std::make_pair(*this, StringRef());
00454       return std::make_pair(slice(0, Idx), slice(Idx + Separator.size(), npos));
00455     }
00456 
00457     /// split - Split into substrings around the occurrences of a separator
00458     /// string.
00459     ///
00460     /// Each substring is stored in \arg A. If \arg MaxSplit is >= 0, at most
00461     /// \arg MaxSplit splits are done and consequently <= \arg MaxSplit
00462     /// elements are added to A.
00463     /// If \arg KeepEmpty is false, empty strings are not added to \arg A. They
00464     /// still count when considering \arg MaxSplit
00465     /// An useful invariant is that
00466     /// Separator.join(A) == *this if MaxSplit == -1 and KeepEmpty == true
00467     ///
00468     /// \param A - Where to put the substrings.
00469     /// \param Separator - The string to split on.
00470     /// \param MaxSplit - The maximum number of times the string is split.
00471     /// \param KeepEmpty - True if empty substring should be added.
00472     void split(SmallVectorImpl<StringRef> &A,
00473                StringRef Separator, int MaxSplit = -1,
00474                bool KeepEmpty = true) const;
00475 
00476     /// rsplit - Split into two substrings around the last occurrence of a
00477     /// separator character.
00478     ///
00479     /// If \arg Separator is in the string, then the result is a pair (LHS, RHS)
00480     /// such that (*this == LHS + Separator + RHS) is true and RHS is
00481     /// minimal. If \arg Separator is not in the string, then the result is a
00482     /// pair (LHS, RHS) where (*this == LHS) and (RHS == "").
00483     ///
00484     /// \param Separator - The character to split on.
00485     /// \return - The split substrings.
00486     std::pair<StringRef, StringRef> rsplit(char Separator) const {
00487       size_t Idx = rfind(Separator);
00488       if (Idx == npos)
00489         return std::make_pair(*this, StringRef());
00490       return std::make_pair(slice(0, Idx), slice(Idx+1, npos));
00491     }
00492 
00493     /// ltrim - Return string with consecutive characters in \arg Chars starting
00494     /// from the left removed.
00495     StringRef ltrim(StringRef Chars = " \t\n\v\f\r") const {
00496       return drop_front(std::min(Length, find_first_not_of(Chars)));
00497     }
00498 
00499     /// rtrim - Return string with consecutive characters in \arg Chars starting
00500     /// from the right removed.
00501     StringRef rtrim(StringRef Chars = " \t\n\v\f\r") const {
00502       return drop_back(Length - std::min(Length, find_last_not_of(Chars) + 1));
00503     }
00504 
00505     /// trim - Return string with consecutive characters in \arg Chars starting
00506     /// from the left and right removed.
00507     StringRef trim(StringRef Chars = " \t\n\v\f\r") const {
00508       return ltrim(Chars).rtrim(Chars);
00509     }
00510 
00511     /// @}
00512   };
00513 
00514   /// @name StringRef Comparison Operators
00515   /// @{
00516 
00517   inline bool operator==(StringRef LHS, StringRef RHS) {
00518     return LHS.equals(RHS);
00519   }
00520 
00521   inline bool operator!=(StringRef LHS, StringRef RHS) {
00522     return !(LHS == RHS);
00523   }
00524 
00525   inline bool operator<(StringRef LHS, StringRef RHS) {
00526     return LHS.compare(RHS) == -1;
00527   }
00528 
00529   inline bool operator<=(StringRef LHS, StringRef RHS) {
00530     return LHS.compare(RHS) != 1;
00531   }
00532 
00533   inline bool operator>(StringRef LHS, StringRef RHS) {
00534     return LHS.compare(RHS) == 1;
00535   }
00536 
00537   inline bool operator>=(StringRef LHS, StringRef RHS) {
00538     return LHS.compare(RHS) != -1;
00539   }
00540 
00541   inline std::string &operator+=(std::string &buffer, llvm::StringRef string) {
00542     return buffer.append(string.data(), string.size());
00543   }
00544 
00545   /// @}
00546 
00547   /// \brief Compute a hash_code for a StringRef.
00548   hash_code hash_value(StringRef S);
00549 
00550   // StringRefs can be treated like a POD type.
00551   template <typename T> struct isPodLike;
00552   template <> struct isPodLike<StringRef> { static const bool value = true; };
00553 
00554 }
00555 
00556 #endif