Home | History | Annotate | Download | only in ADT
      1 //===--- StringRef.h - Constant String Reference Wrapper --------*- C++ -*-===//
      2 //
      3 //                     The LLVM Compiler Infrastructure
      4 //
      5 // This file is distributed under the University of Illinois Open Source
      6 // License. See LICENSE.TXT for details.
      7 //
      8 //===----------------------------------------------------------------------===//
      9 
     10 #ifndef LLVM_ADT_STRINGREF_H
     11 #define LLVM_ADT_STRINGREF_H
     12 
     13 #include <cassert>
     14 #include <cstring>
     15 #include <utility>
     16 #include <string>
     17 
     18 namespace llvm {
     19   template<typename T>
     20   class SmallVectorImpl;
     21   class APInt;
     22 
     23   /// StringRef - Represent a constant reference to a string, i.e. a character
     24   /// array and a length, which need not be null terminated.
     25   ///
     26   /// This class does not own the string data, it is expected to be used in
     27   /// situations where the character data resides in some other buffer, whose
     28   /// lifetime extends past that of the StringRef. For this reason, it is not in
     29   /// general safe to store a StringRef.
     30   class StringRef {
     31   public:
     32     typedef const char *iterator;
     33     typedef const char *const_iterator;
     34     static const size_t npos = ~size_t(0);
     35     typedef size_t size_type;
     36 
     37   private:
     38     /// The start of the string, in an external buffer.
     39     const char *Data;
     40 
     41     /// The length of the string.
     42     size_t Length;
     43 
     44     // Workaround PR5482: nearly all gcc 4.x miscompile StringRef and std::min()
     45     // Changing the arg of min to be an integer, instead of a reference to an
     46     // integer works around this bug.
     47     static size_t min(size_t a, size_t b) { return a < b ? a : b; }
     48     static size_t max(size_t a, size_t b) { return a > b ? a : b; }
     49 
     50     // Workaround memcmp issue with null pointers (undefined behavior)
     51     // by providing a specialized version
     52     static int compareMemory(const char *Lhs, const char *Rhs, size_t Length) {
     53       if (Length == 0) { return 0; }
     54       return ::memcmp(Lhs,Rhs,Length);
     55     }
     56 
     57   public:
     58     /// @name Constructors
     59     /// @{
     60 
     61     /// Construct an empty string ref.
     62     /*implicit*/ StringRef() : Data(0), Length(0) {}
     63 
     64     /// Construct a string ref from a cstring.
     65     /*implicit*/ StringRef(const char *Str)
     66       : Data(Str) {
     67         assert(Str && "StringRef cannot be built from a NULL argument");
     68         Length = ::strlen(Str); // invoking strlen(NULL) is undefined behavior
     69       }
     70 
     71     /// Construct a string ref from a pointer and length.
     72     /*implicit*/ StringRef(const char *data, size_t length)
     73       : Data(data), Length(length) {
     74         assert((data || length == 0) &&
     75         "StringRef cannot be built from a NULL argument with non-null length");
     76       }
     77 
     78     /// Construct a string ref from an std::string.
     79     /*implicit*/ StringRef(const std::string &Str)
     80       : Data(Str.data()), Length(Str.length()) {}
     81 
     82     /// @}
     83     /// @name Iterators
     84     /// @{
     85 
     86     iterator begin() const { return Data; }
     87 
     88     iterator end() const { return Data + Length; }
     89 
     90     /// @}
     91     /// @name String Operations
     92     /// @{
     93 
     94     /// data - Get a pointer to the start of the string (which may not be null
     95     /// terminated).
     96     const char *data() const { return Data; }
     97 
     98     /// empty - Check if the string is empty.
     99     bool empty() const { return Length == 0; }
    100 
    101     /// size - Get the string size.
    102     size_t size() const { return Length; }
    103 
    104     /// front - Get the first character in the string.
    105     char front() const {
    106       assert(!empty());
    107       return Data[0];
    108     }
    109 
    110     /// back - Get the last character in the string.
    111     char back() const {
    112       assert(!empty());
    113       return Data[Length-1];
    114     }
    115 
    116     /// equals - Check for string equality, this is more efficient than
    117     /// compare() when the relative ordering of inequal strings isn't needed.
    118     bool equals(StringRef RHS) const {
    119       return (Length == RHS.Length &&
    120               compareMemory(Data, RHS.Data, RHS.Length) == 0);
    121     }
    122 
    123     /// equals_lower - Check for string equality, ignoring case.
    124     bool equals_lower(StringRef RHS) const {
    125       return Length == RHS.Length && compare_lower(RHS) == 0;
    126     }
    127 
    128     /// compare - Compare two strings; the result is -1, 0, or 1 if this string
    129     /// is lexicographically less than, equal to, or greater than the \arg RHS.
    130     int compare(StringRef RHS) const {
    131       // Check the prefix for a mismatch.
    132       if (int Res = compareMemory(Data, RHS.Data, min(Length, RHS.Length)))
    133         return Res < 0 ? -1 : 1;
    134 
    135       // Otherwise the prefixes match, so we only need to check the lengths.
    136       if (Length == RHS.Length)
    137         return 0;
    138       return Length < RHS.Length ? -1 : 1;
    139     }
    140 
    141     /// compare_lower - Compare two strings, ignoring case.
    142     int compare_lower(StringRef RHS) const;
    143 
    144     /// compare_numeric - Compare two strings, treating sequences of digits as
    145     /// numbers.
    146     int compare_numeric(StringRef RHS) const;
    147 
    148     /// \brief Determine the edit distance between this string and another
    149     /// string.
    150     ///
    151     /// \param Other the string to compare this string against.
    152     ///
    153     /// \param AllowReplacements whether to allow character
    154     /// replacements (change one character into another) as a single
    155     /// operation, rather than as two operations (an insertion and a
    156     /// removal).
    157     ///
    158     /// \param MaxEditDistance If non-zero, the maximum edit distance that
    159     /// this routine is allowed to compute. If the edit distance will exceed
    160     /// that maximum, returns \c MaxEditDistance+1.
    161     ///
    162     /// \returns the minimum number of character insertions, removals,
    163     /// or (if \p AllowReplacements is \c true) replacements needed to
    164     /// transform one of the given strings into the other. If zero,
    165     /// the strings are identical.
    166     unsigned edit_distance(StringRef Other, bool AllowReplacements = true,
    167                            unsigned MaxEditDistance = 0);
    168 
    169     /// str - Get the contents as an std::string.
    170     std::string str() const {
    171       if (Data == 0) return std::string();
    172       return std::string(Data, Length);
    173     }
    174 
    175     /// @}
    176     /// @name Operator Overloads
    177     /// @{
    178 
    179     char operator[](size_t Index) const {
    180       assert(Index < Length && "Invalid index!");
    181       return Data[Index];
    182     }
    183 
    184     /// @}
    185     /// @name Type Conversions
    186     /// @{
    187 
    188     operator std::string() const {
    189       return str();
    190     }
    191 
    192     /// @}
    193     /// @name String Predicates
    194     /// @{
    195 
    196     /// startswith - Check if this string starts with the given \arg Prefix.
    197     bool startswith(StringRef Prefix) const {
    198       return Length >= Prefix.Length &&
    199              compareMemory(Data, Prefix.Data, Prefix.Length) == 0;
    200     }
    201 
    202     /// endswith - Check if this string ends with the given \arg Suffix.
    203     bool endswith(StringRef Suffix) const {
    204       return Length >= Suffix.Length &&
    205         compareMemory(end() - Suffix.Length, Suffix.Data, Suffix.Length) == 0;
    206     }
    207 
    208     /// @}
    209     /// @name String Searching
    210     /// @{
    211 
    212     /// find - Search for the first character \arg C in the string.
    213     ///
    214     /// \return - The index of the first occurrence of \arg C, or npos if not
    215     /// found.
    216     size_t find(char C, size_t From = 0) const {
    217       for (size_t i = min(From, Length), e = Length; i != e; ++i)
    218         if (Data[i] == C)
    219           return i;
    220       return npos;
    221     }
    222 
    223     /// find - Search for the first string \arg Str in the string.
    224     ///
    225     /// \return - The index of the first occurrence of \arg Str, or npos if not
    226     /// found.
    227     size_t find(StringRef Str, size_t From = 0) const;
    228 
    229     /// rfind - Search for the last character \arg C in the string.
    230     ///
    231     /// \return - The index of the last occurrence of \arg C, or npos if not
    232     /// found.
    233     size_t rfind(char C, size_t From = npos) const {
    234       From = min(From, Length);
    235       size_t i = From;
    236       while (i != 0) {
    237         --i;
    238         if (Data[i] == C)
    239           return i;
    240       }
    241       return npos;
    242     }
    243 
    244     /// rfind - Search for the last string \arg Str in the string.
    245     ///
    246     /// \return - The index of the last occurrence of \arg Str, or npos if not
    247     /// found.
    248     size_t rfind(StringRef Str) const;
    249 
    250     /// find_first_of - Find the first character in the string that is \arg C,
    251     /// or npos if not found. Same as find.
    252     size_type find_first_of(char C, size_t From = 0) const {
    253       return find(C, From);
    254     }
    255 
    256     /// find_first_of - Find the first character in the string that is in \arg
    257     /// Chars, or npos if not found.
    258     ///
    259     /// Note: O(size() + Chars.size())
    260     size_type find_first_of(StringRef Chars, size_t From = 0) const;
    261 
    262     /// find_first_not_of - Find the first character in the string that is not
    263     /// \arg C or npos if not found.
    264     size_type find_first_not_of(char C, size_t From = 0) const;
    265 
    266     /// find_first_not_of - Find the first character in the string that is not
    267     /// in the string \arg Chars, or npos if not found.
    268     ///
    269     /// Note: O(size() + Chars.size())
    270     size_type find_first_not_of(StringRef Chars, size_t From = 0) const;
    271 
    272     /// find_last_of - Find the last character in the string that is \arg C, or
    273     /// npos if not found.
    274     size_type find_last_of(char C, size_t From = npos) const {
    275       return rfind(C, From);
    276     }
    277 
    278     /// find_last_of - Find the last character in the string that is in \arg C,
    279     /// or npos if not found.
    280     ///
    281     /// Note: O(size() + Chars.size())
    282     size_type find_last_of(StringRef Chars, size_t From = npos) const;
    283 
    284     /// @}
    285     /// @name Helpful Algorithms
    286     /// @{
    287 
    288     /// count - Return the number of occurrences of \arg C in the string.
    289     size_t count(char C) const {
    290       size_t Count = 0;
    291       for (size_t i = 0, e = Length; i != e; ++i)
    292         if (Data[i] == C)
    293           ++Count;
    294       return Count;
    295     }
    296 
    297     /// count - Return the number of non-overlapped occurrences of \arg Str in
    298     /// the string.
    299     size_t count(StringRef Str) const;
    300 
    301     /// getAsInteger - Parse the current string as an integer of the specified
    302     /// radix.  If Radix is specified as zero, this does radix autosensing using
    303     /// extended C rules: 0 is octal, 0x is hex, 0b is binary.
    304     ///
    305     /// If the string is invalid or if only a subset of the string is valid,
    306     /// this returns true to signify the error.  The string is considered
    307     /// erroneous if empty.
    308     ///
    309     bool getAsInteger(unsigned Radix, long long &Result) const;
    310     bool getAsInteger(unsigned Radix, unsigned long long &Result) const;
    311     bool getAsInteger(unsigned Radix, int &Result) const;
    312     bool getAsInteger(unsigned Radix, unsigned &Result) const;
    313 
    314     // TODO: Provide overloads for int/unsigned that check for overflow.
    315 
    316     /// getAsInteger - Parse the current string as an integer of the
    317     /// specified radix, or of an autosensed radix if the radix given
    318     /// is 0.  The current value in Result is discarded, and the
    319     /// storage is changed to be wide enough to store the parsed
    320     /// integer.
    321     ///
    322     /// Returns true if the string does not solely consist of a valid
    323     /// non-empty number in the appropriate base.
    324     ///
    325     /// APInt::fromString is superficially similar but assumes the
    326     /// string is well-formed in the given radix.
    327     bool getAsInteger(unsigned Radix, APInt &Result) const;
    328 
    329     /// @}
    330     /// @name Substring Operations
    331     /// @{
    332 
    333     /// substr - Return a reference to the substring from [Start, Start + N).
    334     ///
    335     /// \param Start - The index of the starting character in the substring; if
    336     /// the index is npos or greater than the length of the string then the
    337     /// empty substring will be returned.
    338     ///
    339     /// \param N - The number of characters to included in the substring. If N
    340     /// exceeds the number of characters remaining in the string, the string
    341     /// suffix (starting with \arg Start) will be returned.
    342     StringRef substr(size_t Start, size_t N = npos) const {
    343       Start = min(Start, Length);
    344       return StringRef(Data + Start, min(N, Length - Start));
    345     }
    346 
    347     /// slice - Return a reference to the substring from [Start, End).
    348     ///
    349     /// \param Start - The index of the starting character in the substring; if
    350     /// the index is npos or greater than the length of the string then the
    351     /// empty substring will be returned.
    352     ///
    353     /// \param End - The index following the last character to include in the
    354     /// substring. If this is npos, or less than \arg Start, or exceeds the
    355     /// number of characters remaining in the string, the string suffix
    356     /// (starting with \arg Start) will be returned.
    357     StringRef slice(size_t Start, size_t End) const {
    358       Start = min(Start, Length);
    359       End = min(max(Start, End), Length);
    360       return StringRef(Data + Start, End - Start);
    361     }
    362 
    363     /// split - Split into two substrings around the first occurrence of a
    364     /// separator character.
    365     ///
    366     /// If \arg Separator is in the string, then the result is a pair (LHS, RHS)
    367     /// such that (*this == LHS + Separator + RHS) is true and RHS is
    368     /// maximal. If \arg Separator is not in the string, then the result is a
    369     /// pair (LHS, RHS) where (*this == LHS) and (RHS == "").
    370     ///
    371     /// \param Separator - The character to split on.
    372     /// \return - The split substrings.
    373     std::pair<StringRef, StringRef> split(char Separator) const {
    374       size_t Idx = find(Separator);
    375       if (Idx == npos)
    376         return std::make_pair(*this, StringRef());
    377       return std::make_pair(slice(0, Idx), slice(Idx+1, npos));
    378     }
    379 
    380     /// split - Split into two substrings around the first occurrence of a
    381     /// separator string.
    382     ///
    383     /// If \arg Separator is in the string, then the result is a pair (LHS, RHS)
    384     /// such that (*this == LHS + Separator + RHS) is true and RHS is
    385     /// maximal. If \arg Separator is not in the string, then the result is a
    386     /// pair (LHS, RHS) where (*this == LHS) and (RHS == "").
    387     ///
    388     /// \param Separator - The string to split on.
    389     /// \return - The split substrings.
    390     std::pair<StringRef, StringRef> split(StringRef Separator) const {
    391       size_t Idx = find(Separator);
    392       if (Idx == npos)
    393         return std::make_pair(*this, StringRef());
    394       return std::make_pair(slice(0, Idx), slice(Idx + Separator.size(), npos));
    395     }
    396 
    397     /// split - Split into substrings around the occurrences of a separator
    398     /// string.
    399     ///
    400     /// Each substring is stored in \arg A. If \arg MaxSplit is >= 0, at most
    401     /// \arg MaxSplit splits are done and consequently <= \arg MaxSplit
    402     /// elements are added to A.
    403     /// If \arg KeepEmpty is false, empty strings are not added to \arg A. They
    404     /// still count when considering \arg MaxSplit
    405     /// An useful invariant is that
    406     /// Separator.join(A) == *this if MaxSplit == -1 and KeepEmpty == true
    407     ///
    408     /// \param A - Where to put the substrings.
    409     /// \param Separator - The string to split on.
    410     /// \param MaxSplit - The maximum number of times the string is split.
    411     /// \param KeepEmpty - True if empty substring should be added.
    412     void split(SmallVectorImpl<StringRef> &A,
    413                StringRef Separator, int MaxSplit = -1,
    414                bool KeepEmpty = true) const;
    415 
    416     /// rsplit - Split into two substrings around the last occurrence of a
    417     /// separator character.
    418     ///
    419     /// If \arg Separator is in the string, then the result is a pair (LHS, RHS)
    420     /// such that (*this == LHS + Separator + RHS) is true and RHS is
    421     /// minimal. If \arg Separator is not in the string, then the result is a
    422     /// pair (LHS, RHS) where (*this == LHS) and (RHS == "").
    423     ///
    424     /// \param Separator - The character to split on.
    425     /// \return - The split substrings.
    426     std::pair<StringRef, StringRef> rsplit(char Separator) const {
    427       size_t Idx = rfind(Separator);
    428       if (Idx == npos)
    429         return std::make_pair(*this, StringRef());
    430       return std::make_pair(slice(0, Idx), slice(Idx+1, npos));
    431     }
    432 
    433     /// @}
    434   };
    435 
    436   /// @name StringRef Comparison Operators
    437   /// @{
    438 
    439   inline bool operator==(StringRef LHS, StringRef RHS) {
    440     return LHS.equals(RHS);
    441   }
    442 
    443   inline bool operator!=(StringRef LHS, StringRef RHS) {
    444     return !(LHS == RHS);
    445   }
    446 
    447   inline bool operator<(StringRef LHS, StringRef RHS) {
    448     return LHS.compare(RHS) == -1;
    449   }
    450 
    451   inline bool operator<=(StringRef LHS, StringRef RHS) {
    452     return LHS.compare(RHS) != 1;
    453   }
    454 
    455   inline bool operator>(StringRef LHS, StringRef RHS) {
    456     return LHS.compare(RHS) == 1;
    457   }
    458 
    459   inline bool operator>=(StringRef LHS, StringRef RHS) {
    460     return LHS.compare(RHS) != -1;
    461   }
    462 
    463   inline std::string &operator+=(std::string &buffer, llvm::StringRef string) {
    464     return buffer.append(string.data(), string.size());
    465   }
    466 
    467   /// @}
    468 
    469   // StringRefs can be treated like a POD type.
    470   template <typename T> struct isPodLike;
    471   template <> struct isPodLike<StringRef> { static const bool value = true; };
    472 
    473 }
    474 
    475 #endif
    476