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       if (getAsUnsignedInteger(*this, Radix, ULLVal) ||
00351             static_cast<T>(ULLVal) != ULLVal)
00352         return true;
00353       Result = ULLVal;
00354       return false;
00355     }
00356 
00357     /// Parse the current string as an integer of the specified \p Radix, or of
00358     /// an autosensed radix if the \p Radix given is 0.  The current value in
00359     /// \p Result is discarded, and the storage is changed to be wide enough to
00360     /// store the parsed integer.
00361     ///
00362     /// \returns true if the string does not solely consist of a valid
00363     /// non-empty number in the appropriate base.
00364     ///
00365     /// APInt::fromString is superficially similar but assumes the
00366     /// string is well-formed in the given radix.
00367     bool getAsInteger(unsigned Radix, APInt &Result) const;
00368 
00369     /// @}
00370     /// @name String Operations
00371     /// @{
00372 
00373     // Convert the given ASCII string to lowercase.
00374     std::string lower() const;
00375 
00376     /// Convert the given ASCII string to uppercase.
00377     std::string upper() const;
00378 
00379     /// @}
00380     /// @name Substring Operations
00381     /// @{
00382 
00383     /// Return a reference to the substring from [Start, Start + N).
00384     ///
00385     /// \param Start The index of the starting character in the substring; if
00386     /// the index is npos or greater than the length of the string then the
00387     /// empty substring will be returned.
00388     ///
00389     /// \param N The number of characters to included in the substring. If N
00390     /// exceeds the number of characters remaining in the string, the string
00391     /// suffix (starting with \p Start) will be returned.
00392     StringRef substr(size_t Start, size_t N = npos) const {
00393       Start = std::min(Start, Length);
00394       return StringRef(Data + Start, std::min(N, Length - Start));
00395     }
00396 
00397     /// Return a StringRef equal to 'this' but with the first \p N elements
00398     /// dropped.
00399     StringRef drop_front(size_t N = 1) const {
00400       assert(size() >= N && "Dropping more elements than exist");
00401       return substr(N);
00402     }
00403 
00404     /// Return a StringRef equal to 'this' but with the last \p N elements
00405     /// dropped.
00406     StringRef drop_back(size_t N = 1) const {
00407       assert(size() >= N && "Dropping more elements than exist");
00408       return substr(0, size()-N);
00409     }
00410 
00411     /// Return a reference to the substring from [Start, End).
00412     ///
00413     /// \param Start The index of the starting character in the substring; if
00414     /// the index is npos or greater than the length of the string then the
00415     /// empty substring will be returned.
00416     ///
00417     /// \param End The index following the last character to include in the
00418     /// substring. If this is npos, or less than \p Start, or exceeds the
00419     /// number of characters remaining in the string, the string suffix
00420     /// (starting with \p Start) will be returned.
00421     StringRef slice(size_t Start, size_t End) const {
00422       Start = std::min(Start, Length);
00423       End = std::min(std::max(Start, End), Length);
00424       return StringRef(Data + Start, End - Start);
00425     }
00426 
00427     /// Split into two substrings around the first occurrence of a separator
00428     /// character.
00429     ///
00430     /// If \p Separator is in the string, then the result is a pair (LHS, RHS)
00431     /// such that (*this == LHS + Separator + RHS) is true and RHS is
00432     /// maximal. If \p Separator is not in the string, then the result is a
00433     /// pair (LHS, RHS) where (*this == LHS) and (RHS == "").
00434     ///
00435     /// \param Separator The character to split on.
00436     /// \returns The split substrings.
00437     std::pair<StringRef, StringRef> split(char Separator) const {
00438       size_t Idx = find(Separator);
00439       if (Idx == npos)
00440         return std::make_pair(*this, StringRef());
00441       return std::make_pair(slice(0, Idx), slice(Idx+1, npos));
00442     }
00443 
00444     /// Split into two substrings around the first occurrence of a separator
00445     /// string.
00446     ///
00447     /// If \p Separator is in the string, then the result is a pair (LHS, RHS)
00448     /// such that (*this == LHS + Separator + RHS) is true and RHS is
00449     /// maximal. If \p Separator is not in the string, then the result is a
00450     /// pair (LHS, RHS) where (*this == LHS) and (RHS == "").
00451     ///
00452     /// \param Separator - The string to split on.
00453     /// \return - The split substrings.
00454     std::pair<StringRef, StringRef> split(StringRef Separator) const {
00455       size_t Idx = find(Separator);
00456       if (Idx == npos)
00457         return std::make_pair(*this, StringRef());
00458       return std::make_pair(slice(0, Idx), slice(Idx + Separator.size(), npos));
00459     }
00460 
00461     /// Split into substrings around the occurrences of a separator string.
00462     ///
00463     /// Each substring is stored in \p A. If \p MaxSplit is >= 0, at most
00464     /// \p MaxSplit splits are done and consequently <= \p MaxSplit
00465     /// elements are added to A.
00466     /// If \p KeepEmpty is false, empty strings are not added to \p A. They
00467     /// still count when considering \p MaxSplit
00468     /// An useful invariant is that
00469     /// Separator.join(A) == *this if MaxSplit == -1 and KeepEmpty == true
00470     ///
00471     /// \param A - Where to put the substrings.
00472     /// \param Separator - The string to split on.
00473     /// \param MaxSplit - The maximum number of times the string is split.
00474     /// \param KeepEmpty - True if empty substring should be added.
00475     void split(SmallVectorImpl<StringRef> &A,
00476                StringRef Separator, int MaxSplit = -1,
00477                bool KeepEmpty = true) const;
00478 
00479     /// Split into two substrings around the last occurrence of a separator
00480     /// character.
00481     ///
00482     /// If \p Separator is in the string, then the result is a pair (LHS, RHS)
00483     /// such that (*this == LHS + Separator + RHS) is true and RHS is
00484     /// minimal. If \p Separator is not in the string, then the result is a
00485     /// pair (LHS, RHS) where (*this == LHS) and (RHS == "").
00486     ///
00487     /// \param Separator - The character to split on.
00488     /// \return - The split substrings.
00489     std::pair<StringRef, StringRef> rsplit(char Separator) const {
00490       size_t Idx = rfind(Separator);
00491       if (Idx == npos)
00492         return std::make_pair(*this, StringRef());
00493       return std::make_pair(slice(0, Idx), slice(Idx+1, npos));
00494     }
00495 
00496     /// Return string with consecutive characters in \p Chars starting from
00497     /// the left removed.
00498     StringRef ltrim(StringRef Chars = " \t\n\v\f\r") const {
00499       return drop_front(std::min(Length, find_first_not_of(Chars)));
00500     }
00501 
00502     /// Return string with consecutive characters in \p Chars starting from
00503     /// the right removed.
00504     StringRef rtrim(StringRef Chars = " \t\n\v\f\r") const {
00505       return drop_back(Length - std::min(Length, find_last_not_of(Chars) + 1));
00506     }
00507 
00508     /// Return string with consecutive characters in \p Chars starting from
00509     /// the left and right removed.
00510     StringRef trim(StringRef Chars = " \t\n\v\f\r") const {
00511       return ltrim(Chars).rtrim(Chars);
00512     }
00513 
00514     /// @}
00515   };
00516 
00517   /// @name StringRef Comparison Operators
00518   /// @{
00519 
00520   inline bool operator==(StringRef LHS, StringRef RHS) {
00521     return LHS.equals(RHS);
00522   }
00523 
00524   inline bool operator!=(StringRef LHS, StringRef RHS) {
00525     return !(LHS == RHS);
00526   }
00527 
00528   inline bool operator<(StringRef LHS, StringRef RHS) {
00529     return LHS.compare(RHS) == -1;
00530   }
00531 
00532   inline bool operator<=(StringRef LHS, StringRef RHS) {
00533     return LHS.compare(RHS) != 1;
00534   }
00535 
00536   inline bool operator>(StringRef LHS, StringRef RHS) {
00537     return LHS.compare(RHS) == 1;
00538   }
00539 
00540   inline bool operator>=(StringRef LHS, StringRef RHS) {
00541     return LHS.compare(RHS) != -1;
00542   }
00543 
00544   inline std::string &operator+=(std::string &buffer, StringRef string) {
00545     return buffer.append(string.data(), string.size());
00546   }
00547 
00548   /// @}
00549 
00550   /// \brief Compute a hash_code for a StringRef.
00551   hash_code hash_value(StringRef S);
00552 
00553   // StringRefs can be treated like a POD type.
00554   template <typename T> struct isPodLike;
00555   template <> struct isPodLike<StringRef> { static const bool value = true; };
00556 }
00557 
00558 #endif