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