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     /// @}
00095     /// @name String Operations
00096     /// @{
00097 
00098     /// data - Get a pointer to the start of the string (which may not be null
00099     /// terminated).
00100     const char *data() const { return Data; }
00101 
00102     /// empty - Check if the string is empty.
00103     bool empty() const { return Length == 0; }
00104 
00105     /// size - Get the string size.
00106     size_t size() const { return Length; }
00107 
00108     /// front - Get the first character in the string.
00109     char front() const {
00110       assert(!empty());
00111       return Data[0];
00112     }
00113 
00114     /// back - Get the last character in the string.
00115     char back() const {
00116       assert(!empty());
00117       return Data[Length-1];
00118     }
00119 
00120     // copy - Allocate copy in Allocator and return StringRef to it.
00121     template <typename Allocator> StringRef copy(Allocator &A) const {
00122       char *S = A.template Allocate<char>(Length);
00123       std::copy(begin(), end(), S);
00124       return StringRef(S, Length);
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, std::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) const;
00179 
00180     /// str - Get the contents as an std::string.
00181     std::string str() const {
00182       if (!Data) 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 starts with the given \p Prefix, ignoring case.
00214     bool startswith_lower(StringRef Prefix) const;
00215 
00216     /// Check if this string ends with the given \p Suffix.
00217     bool endswith(StringRef Suffix) const {
00218       return Length >= Suffix.Length &&
00219         compareMemory(end() - Suffix.Length, Suffix.Data, Suffix.Length) == 0;
00220     }
00221 
00222     /// Check if this string ends with the given \p Suffix, ignoring case.
00223     bool endswith_lower(StringRef Suffix) const;
00224 
00225     /// @}
00226     /// @name String Searching
00227     /// @{
00228 
00229     /// Search for the first character \p C in the string.
00230     ///
00231     /// \returns The index of the first occurrence of \p C, or npos if not
00232     /// found.
00233     size_t find(char C, size_t From = 0) const {
00234       for (size_t i = std::min(From, Length), e = Length; i != e; ++i)
00235         if (Data[i] == C)
00236           return i;
00237       return npos;
00238     }
00239 
00240     /// Search for the first string \p Str in the string.
00241     ///
00242     /// \returns The index of the first occurrence of \p Str, or npos if not
00243     /// found.
00244     size_t find(StringRef Str, size_t From = 0) const;
00245 
00246     /// Search for the last character \p C in the string.
00247     ///
00248     /// \returns The index of the last occurrence of \p C, or npos if not
00249     /// found.
00250     size_t rfind(char C, size_t From = npos) const {
00251       From = std::min(From, Length);
00252       size_t i = From;
00253       while (i != 0) {
00254         --i;
00255         if (Data[i] == C)
00256           return i;
00257       }
00258       return npos;
00259     }
00260 
00261     /// Search for the last string \p Str in the string.
00262     ///
00263     /// \returns The index of the last occurrence of \p Str, or npos if not
00264     /// found.
00265     size_t rfind(StringRef Str) const;
00266 
00267     /// Find the first character in the string that is \p C, or npos if not
00268     /// found. Same as find.
00269     size_t find_first_of(char C, size_t From = 0) const {
00270       return find(C, From);
00271     }
00272 
00273     /// Find the first character in the string that is in \p Chars, or npos if
00274     /// not found.
00275     ///
00276     /// Complexity: O(size() + Chars.size())
00277     size_t find_first_of(StringRef Chars, size_t From = 0) const;
00278 
00279     /// Find the first character in the string that is not \p C or npos if not
00280     /// found.
00281     size_t find_first_not_of(char C, size_t From = 0) const;
00282 
00283     /// Find the first character in the string that is not in the string
00284     /// \p Chars, or npos if not found.
00285     ///
00286     /// Complexity: O(size() + Chars.size())
00287     size_t find_first_not_of(StringRef Chars, size_t From = 0) const;
00288 
00289     /// Find the last character in the string that is \p C, or npos if not
00290     /// found.
00291     size_t find_last_of(char C, size_t From = npos) const {
00292       return rfind(C, From);
00293     }
00294 
00295     /// Find the last character in the string that is in \p C, or npos if not
00296     /// found.
00297     ///
00298     /// Complexity: O(size() + Chars.size())
00299     size_t find_last_of(StringRef Chars, size_t From = npos) const;
00300 
00301     /// Find the last character in the string that is not \p C, or npos if not
00302     /// found.
00303     size_t find_last_not_of(char C, size_t From = npos) const;
00304 
00305     /// Find the last character in the string that is not in \p Chars, or
00306     /// npos if not found.
00307     ///
00308     /// Complexity: O(size() + Chars.size())
00309     size_t find_last_not_of(StringRef Chars, size_t From = npos) const;
00310 
00311     /// @}
00312     /// @name Helpful Algorithms
00313     /// @{
00314 
00315     /// Return the number of occurrences of \p C in the string.
00316     size_t count(char C) const {
00317       size_t Count = 0;
00318       for (size_t i = 0, e = Length; i != e; ++i)
00319         if (Data[i] == C)
00320           ++Count;
00321       return Count;
00322     }
00323 
00324     /// Return the number of non-overlapped occurrences of \p Str in
00325     /// the string.
00326     size_t count(StringRef Str) const;
00327 
00328     /// Parse the current string as an integer of the specified radix.  If
00329     /// \p Radix is specified as zero, this does radix autosensing using
00330     /// extended C rules: 0 is octal, 0x is hex, 0b is binary.
00331     ///
00332     /// If the string is invalid or if only a subset of the string is valid,
00333     /// this returns true to signify the error.  The string is considered
00334     /// erroneous if empty or if it overflows T.
00335     template <typename T>
00336     typename std::enable_if<std::numeric_limits<T>::is_signed, bool>::type
00337     getAsInteger(unsigned Radix, T &Result) const {
00338       long long LLVal;
00339       if (getAsSignedInteger(*this, Radix, LLVal) ||
00340             static_cast<T>(LLVal) != LLVal)
00341         return true;
00342       Result = LLVal;
00343       return false;
00344     }
00345 
00346     template <typename T>
00347     typename std::enable_if<!std::numeric_limits<T>::is_signed, bool>::type
00348     getAsInteger(unsigned Radix, T &Result) const {
00349       unsigned long long ULLVal;
00350       // The additional cast to unsigned long long is required to avoid the
00351       // Visual C++ warning C4805: '!=' : unsafe mix of type 'bool' and type
00352       // 'unsigned __int64' when instantiating getAsInteger with T = bool.
00353       if (getAsUnsignedInteger(*this, Radix, ULLVal) ||
00354           static_cast<unsigned long long>(static_cast<T>(ULLVal)) != ULLVal)
00355         return true;
00356       Result = ULLVal;
00357       return false;
00358     }
00359 
00360     /// Parse the current string as an integer of the specified \p Radix, or of
00361     /// an autosensed radix if the \p Radix given is 0.  The current value in
00362     /// \p Result is discarded, and the storage is changed to be wide enough to
00363     /// store the parsed integer.
00364     ///
00365     /// \returns true if the string does not solely consist of a valid
00366     /// non-empty number in the appropriate base.
00367     ///
00368     /// APInt::fromString is superficially similar but assumes the
00369     /// string is well-formed in the given radix.
00370     bool getAsInteger(unsigned Radix, APInt &Result) const;
00371 
00372     /// @}
00373     /// @name String Operations
00374     /// @{
00375 
00376     // Convert the given ASCII string to lowercase.
00377     std::string lower() const;
00378 
00379     /// Convert the given ASCII string to uppercase.
00380     std::string upper() const;
00381 
00382     /// @}
00383     /// @name Substring Operations
00384     /// @{
00385 
00386     /// Return a reference to the substring from [Start, Start + N).
00387     ///
00388     /// \param Start The index of the starting character in the substring; if
00389     /// the index is npos or greater than the length of the string then the
00390     /// empty substring will be returned.
00391     ///
00392     /// \param N The number of characters to included in the substring. If N
00393     /// exceeds the number of characters remaining in the string, the string
00394     /// suffix (starting with \p Start) will be returned.
00395     StringRef substr(size_t Start, size_t N = npos) const {
00396       Start = std::min(Start, Length);
00397       return StringRef(Data + Start, std::min(N, Length - Start));
00398     }
00399 
00400     /// Return a StringRef equal to 'this' but with the first \p N elements
00401     /// dropped.
00402     StringRef drop_front(size_t N = 1) const {
00403       assert(size() >= N && "Dropping more elements than exist");
00404       return substr(N);
00405     }
00406 
00407     /// Return a StringRef equal to 'this' but with the last \p N elements
00408     /// dropped.
00409     StringRef drop_back(size_t N = 1) const {
00410       assert(size() >= N && "Dropping more elements than exist");
00411       return substr(0, size()-N);
00412     }
00413 
00414     /// Return a reference to the substring from [Start, End).
00415     ///
00416     /// \param Start The index of the starting character in the substring; if
00417     /// the index is npos or greater than the length of the string then the
00418     /// empty substring will be returned.
00419     ///
00420     /// \param End The index following the last character to include in the
00421     /// substring. If this is npos, or less than \p Start, or exceeds the
00422     /// number of characters remaining in the string, the string suffix
00423     /// (starting with \p Start) will be returned.
00424     StringRef slice(size_t Start, size_t End) const {
00425       Start = std::min(Start, Length);
00426       End = std::min(std::max(Start, End), Length);
00427       return StringRef(Data + Start, End - Start);
00428     }
00429 
00430     /// Split into two substrings around the first occurrence of a separator
00431     /// character.
00432     ///
00433     /// If \p Separator is in the string, then the result is a pair (LHS, RHS)
00434     /// such that (*this == LHS + Separator + RHS) is true and RHS is
00435     /// maximal. If \p Separator is not in the string, then the result is a
00436     /// pair (LHS, RHS) where (*this == LHS) and (RHS == "").
00437     ///
00438     /// \param Separator The character to split on.
00439     /// \returns The split substrings.
00440     std::pair<StringRef, StringRef> split(char Separator) const {
00441       size_t Idx = find(Separator);
00442       if (Idx == npos)
00443         return std::make_pair(*this, StringRef());
00444       return std::make_pair(slice(0, Idx), slice(Idx+1, npos));
00445     }
00446 
00447     /// Split into two substrings around the first occurrence of a separator
00448     /// string.
00449     ///
00450     /// If \p Separator is in the string, then the result is a pair (LHS, RHS)
00451     /// such that (*this == LHS + Separator + RHS) is true and RHS is
00452     /// maximal. If \p Separator is not in the string, then the result is a
00453     /// pair (LHS, RHS) where (*this == LHS) and (RHS == "").
00454     ///
00455     /// \param Separator - The string to split on.
00456     /// \return - The split substrings.
00457     std::pair<StringRef, StringRef> split(StringRef Separator) const {
00458       size_t Idx = find(Separator);
00459       if (Idx == npos)
00460         return std::make_pair(*this, StringRef());
00461       return std::make_pair(slice(0, Idx), slice(Idx + Separator.size(), npos));
00462     }
00463 
00464     /// Split into substrings around the occurrences of a separator string.
00465     ///
00466     /// Each substring is stored in \p A. If \p MaxSplit is >= 0, at most
00467     /// \p MaxSplit splits are done and consequently <= \p MaxSplit
00468     /// elements are added to A.
00469     /// If \p KeepEmpty is false, empty strings are not added to \p A. They
00470     /// still count when considering \p MaxSplit
00471     /// An useful invariant is that
00472     /// Separator.join(A) == *this if MaxSplit == -1 and KeepEmpty == true
00473     ///
00474     /// \param A - Where to put the substrings.
00475     /// \param Separator - The string to split on.
00476     /// \param MaxSplit - The maximum number of times the string is split.
00477     /// \param KeepEmpty - True if empty substring should be added.
00478     void split(SmallVectorImpl<StringRef> &A,
00479                StringRef Separator, int MaxSplit = -1,
00480                bool KeepEmpty = true) const;
00481 
00482     /// Split into two substrings around the last occurrence of a separator
00483     /// character.
00484     ///
00485     /// If \p Separator is in the string, then the result is a pair (LHS, RHS)
00486     /// such that (*this == LHS + Separator + RHS) is true and RHS is
00487     /// minimal. If \p Separator is not in the string, then the result is a
00488     /// pair (LHS, RHS) where (*this == LHS) and (RHS == "").
00489     ///
00490     /// \param Separator - The character to split on.
00491     /// \return - The split substrings.
00492     std::pair<StringRef, StringRef> rsplit(char Separator) const {
00493       size_t Idx = rfind(Separator);
00494       if (Idx == npos)
00495         return std::make_pair(*this, StringRef());
00496       return std::make_pair(slice(0, Idx), slice(Idx+1, npos));
00497     }
00498 
00499     /// Return string with consecutive characters in \p Chars starting from
00500     /// the left removed.
00501     StringRef ltrim(StringRef Chars = " \t\n\v\f\r") const {
00502       return drop_front(std::min(Length, find_first_not_of(Chars)));
00503     }
00504 
00505     /// Return string with consecutive characters in \p Chars starting from
00506     /// the right removed.
00507     StringRef rtrim(StringRef Chars = " \t\n\v\f\r") const {
00508       return drop_back(Length - std::min(Length, find_last_not_of(Chars) + 1));
00509     }
00510 
00511     /// Return string with consecutive characters in \p Chars starting from
00512     /// the left and right removed.
00513     StringRef trim(StringRef Chars = " \t\n\v\f\r") const {
00514       return ltrim(Chars).rtrim(Chars);
00515     }
00516 
00517     /// @}
00518   };
00519 
00520   /// @name StringRef Comparison Operators
00521   /// @{
00522 
00523   inline bool operator==(StringRef LHS, StringRef RHS) {
00524     return LHS.equals(RHS);
00525   }
00526 
00527   inline bool operator!=(StringRef LHS, StringRef RHS) {
00528     return !(LHS == RHS);
00529   }
00530 
00531   inline bool operator<(StringRef LHS, StringRef RHS) {
00532     return LHS.compare(RHS) == -1;
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 std::string &operator+=(std::string &buffer, StringRef string) {
00548     return buffer.append(string.data(), string.size());
00549   }
00550 
00551   /// @}
00552 
00553   /// \brief Compute a hash_code for a StringRef.
00554   hash_code hash_value(StringRef S);
00555 
00556   // StringRefs can be treated like a POD type.
00557   template <typename T> struct isPodLike;
00558   template <> struct isPodLike<StringRef> { static const bool value = true; };
00559 }
00560 
00561 #endif