LCOV - code coverage report
Current view: top level - include/llvm/ADT - StringExtras.h (source / functions) Hit Total Coverage
Test: llvm-toolchain.info Lines: 102 103 99.0 %
Date: 2018-07-13 00:08:38 Functions: 47 49 95.9 %
Legend: Lines: hit not hit

          Line data    Source code
       1             : //===- llvm/ADT/StringExtras.h - Useful string functions --------*- 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             : // This file contains some functions that are useful when dealing with strings.
      11             : //
      12             : //===----------------------------------------------------------------------===//
      13             : 
      14             : #ifndef LLVM_ADT_STRINGEXTRAS_H
      15             : #define LLVM_ADT_STRINGEXTRAS_H
      16             : 
      17             : #include "llvm/ADT/ArrayRef.h"
      18             : #include "llvm/ADT/SmallString.h"
      19             : #include "llvm/ADT/StringRef.h"
      20             : #include "llvm/ADT/Twine.h"
      21             : #include <cassert>
      22             : #include <cstddef>
      23             : #include <cstdint>
      24             : #include <cstdlib>
      25             : #include <cstring>
      26             : #include <iterator>
      27             : #include <string>
      28             : #include <utility>
      29             : 
      30             : namespace llvm {
      31             : 
      32             : template<typename T> class SmallVectorImpl;
      33             : class raw_ostream;
      34             : 
      35             : /// hexdigit - Return the hexadecimal character for the
      36             : /// given number \p X (which should be less than 16).
      37             : inline char hexdigit(unsigned X, bool LowerCase = false) {
      38    46099528 :   const char HexChar = LowerCase ? 'a' : 'A';
      39    46458098 :   return X < 10 ? '0' + X : HexChar + X - 10;
      40             : }
      41             : 
      42             : /// Given an array of c-style strings terminated by a null pointer, construct
      43             : /// a vector of StringRefs representing the same strings without the terminating
      44             : /// null string.
      45        5468 : inline std::vector<StringRef> toStringRefArray(const char *const *Strings) {
      46             :   std::vector<StringRef> Result;
      47      675142 :   while (*Strings)
      48      669674 :     Result.push_back(*Strings++);
      49        5468 :   return Result;
      50             : }
      51             : 
      52             : /// Construct a string ref from a boolean.
      53     1758361 : inline StringRef toStringRef(bool B) { return StringRef(B ? "true" : "false"); }
      54             : 
      55             : /// Construct a string ref from an array ref of unsigned chars.
      56             : inline StringRef toStringRef(ArrayRef<uint8_t> Input) {
      57             :   return StringRef(reinterpret_cast<const char *>(Input.begin()), Input.size());
      58             : }
      59             : 
      60             : /// Construct a string ref from an array ref of unsigned chars.
      61             : inline ArrayRef<uint8_t> arrayRefFromStringRef(StringRef Input) {
      62             :   return {Input.bytes_begin(), Input.bytes_end()};
      63             : }
      64             : 
      65             : /// Interpret the given character \p C as a hexadecimal digit and return its
      66             : /// value.
      67             : ///
      68             : /// If \p C is not a valid hex digit, -1U is returned.
      69             : inline unsigned hexDigitValue(char C) {
      70     7851263 :   if (C >= '0' && C <= '9') return C-'0';
      71      822340 :   if (C >= 'a' && C <= 'f') return C-'a'+10U;
      72      745697 :   if (C >= 'A' && C <= 'F') return C-'A'+10U;
      73             :   return -1U;
      74             : }
      75             : 
      76             : /// Checks if character \p C is one of the 10 decimal digits.
      77    18080791 : inline bool isDigit(char C) { return C >= '0' && C <= '9'; }
      78             : 
      79             : /// Checks if character \p C is a hexadecimal numeric character.
      80       36848 : inline bool isHexDigit(char C) { return hexDigitValue(C) != -1U; }
      81             : 
      82             : /// Checks if character \p C is a valid letter as classified by "C" locale.
      83             : inline bool isAlpha(char C) {
      84    37188728 :   return ('a' <= C && C <= 'z') || ('A' <= C && C <= 'Z');
      85             : }
      86             : 
      87             : /// Checks whether character \p C is either a decimal digit or an uppercase or
      88             : /// lowercase letter as classified by "C" locale.
      89    43289157 : inline bool isAlnum(char C) { return isAlpha(C) || isDigit(C); }
      90             : 
      91             : /// Checks whether character \p C is valid ASCII (high bit is zero).
      92             : inline bool isASCII(char C) { return static_cast<unsigned char>(C) <= 127; }
      93             : 
      94             : /// Checks whether all characters in S are ASCII.
      95             : inline bool isASCII(llvm::StringRef S) {
      96      198662 :   for (char C : S)
      97       66265 :     if (LLVM_UNLIKELY(!isASCII(C)))
      98             :       return false;
      99             :   return true;
     100             : }
     101             : 
     102             : /// Returns the corresponding lowercase character if \p x is uppercase.
     103             : inline char toLower(char x) {
     104   174082467 :   if (x >= 'A' && x <= 'Z')
     105    73087772 :     return x - 'A' + 'a';
     106             :   return x;
     107             : }
     108             : 
     109             : /// Returns the corresponding uppercase character if \p x is lowercase.
     110             : inline char toUpper(char x) {
     111     1798580 :   if (x >= 'a' && x <= 'z')
     112     1253396 :     return x - 'a' + 'A';
     113             :   return x;
     114             : }
     115             : 
     116       15933 : inline std::string utohexstr(uint64_t X, bool LowerCase = false) {
     117             :   char Buffer[17];
     118             :   char *BufPtr = std::end(Buffer);
     119             : 
     120       15933 :   if (X == 0) *--BufPtr = '0';
     121             : 
     122       85223 :   while (X) {
     123       34645 :     unsigned char Mod = static_cast<unsigned char>(X) & 15;
     124       69290 :     *--BufPtr = hexdigit(Mod, LowerCase);
     125       34645 :     X >>= 4;
     126             :   }
     127             : 
     128       15933 :   return std::string(BufPtr, std::end(Buffer));
     129             : }
     130             : 
     131             : /// Convert buffer \p Input to its hexadecimal representation.
     132             : /// The returned string is double the size of \p Input.
     133         589 : inline std::string toHex(StringRef Input) {
     134             :   static const char *const LUT = "0123456789ABCDEF";
     135             :   size_t Length = Input.size();
     136             : 
     137             :   std::string Output;
     138         589 :   Output.reserve(2 * Length);
     139       21159 :   for (size_t i = 0; i < Length; ++i) {
     140       20570 :     const unsigned char c = Input[i];
     141       10285 :     Output.push_back(LUT[c >> 4]);
     142       10285 :     Output.push_back(LUT[c & 15]);
     143             :   }
     144         589 :   return Output;
     145             : }
     146             : 
     147             : inline std::string toHex(ArrayRef<uint8_t> Input) {
     148         361 :   return toHex(toStringRef(Input));
     149             : }
     150             : 
     151        2450 : inline uint8_t hexFromNibbles(char MSB, char LSB) {
     152        2450 :   unsigned U1 = hexDigitValue(MSB);
     153        2450 :   unsigned U2 = hexDigitValue(LSB);
     154             :   assert(U1 != -1U && U2 != -1U);
     155             : 
     156        2450 :   return static_cast<uint8_t>((U1 << 4) | U2);
     157             : }
     158             : 
     159             : /// Convert hexadecimal string \p Input to its binary representation.
     160             : /// The return string is half the size of \p Input.
     161         174 : inline std::string fromHex(StringRef Input) {
     162         174 :   if (Input.empty())
     163             :     return std::string();
     164             : 
     165             :   std::string Output;
     166         154 :   Output.reserve((Input.size() + 1) / 2);
     167         154 :   if (Input.size() % 2 == 1) {
     168           3 :     Output.push_back(hexFromNibbles('0', Input.front()));
     169           1 :     Input = Input.drop_front();
     170             :   }
     171             : 
     172             :   assert(Input.size() % 2 == 0);
     173        5054 :   while (!Input.empty()) {
     174        7350 :     uint8_t Hex = hexFromNibbles(Input[0], Input[1]);
     175        2450 :     Output.push_back(Hex);
     176        2450 :     Input = Input.drop_front(2);
     177             :   }
     178             :   return Output;
     179             : }
     180             : 
     181             : /// Convert the string \p S to an integer of the specified type using
     182             : /// the radix \p Base.  If \p Base is 0, auto-detects the radix.
     183             : /// Returns true if the number was successfully converted, false otherwise.
     184        1261 : template <typename N> bool to_integer(StringRef S, N &Num, unsigned Base = 0) {
     185        1261 :   return !S.getAsInteger(Base, Num);
     186             : }
     187             : 
     188             : namespace detail {
     189             : template <typename N>
     190          50 : inline bool to_float(const Twine &T, N &Num, N (*StrTo)(const char *, char **)) {
     191             :   SmallString<32> Storage;
     192          50 :   StringRef S = T.toNullTerminatedStringRef(Storage);
     193             :   char *End;
     194          50 :   N Temp = StrTo(S.data(), &End);
     195          50 :   if (*End != '\0')
     196             :     return false;
     197          46 :   Num = Temp;
     198          46 :   return true;
     199             : }
     200             : }
     201             : 
     202             : inline bool to_float(const Twine &T, float &Num) {
     203          11 :   return detail::to_float(T, Num, strtof);
     204             : }
     205             : 
     206             : inline bool to_float(const Twine &T, double &Num) {
     207          38 :   return detail::to_float(T, Num, strtod);
     208             : }
     209             : 
     210             : inline bool to_float(const Twine &T, long double &Num) {
     211           1 :   return detail::to_float(T, Num, strtold);
     212             : }
     213             : 
     214     4671997 : inline std::string utostr(uint64_t X, bool isNeg = false) {
     215             :   char Buffer[21];
     216             :   char *BufPtr = std::end(Buffer);
     217             : 
     218     4671997 :   if (X == 0) *--BufPtr = '0';  // Handle special case...
     219             : 
     220    19958859 :   while (X) {
     221     7643431 :     *--BufPtr = '0' + char(X % 10);
     222     7643431 :     X /= 10;
     223             :   }
     224             : 
     225     4671997 :   if (isNeg) *--BufPtr = '-';   // Add negative sign...
     226     4671997 :   return std::string(BufPtr, std::end(Buffer));
     227             : }
     228             : 
     229     1223723 : inline std::string itostr(int64_t X) {
     230     1223723 :   if (X < 0)
     231      123940 :     return utostr(static_cast<uint64_t>(-X), true);
     232             :   else
     233     1100937 :     return utostr(static_cast<uint64_t>(X));
     234             : }
     235             : 
     236             : /// StrInStrNoCase - Portable version of strcasestr.  Locates the first
     237             : /// occurrence of string 's1' in string 's2', ignoring case.  Returns
     238             : /// the offset of s2 in s1 or npos if s2 cannot be found.
     239             : StringRef::size_type StrInStrNoCase(StringRef s1, StringRef s2);
     240             : 
     241             : /// getToken - This function extracts one token from source, ignoring any
     242             : /// leading characters that appear in the Delimiters string, and ending the
     243             : /// token at any of the characters that appear in the Delimiters string.  If
     244             : /// there are no tokens in the source string, an empty string is returned.
     245             : /// The function returns a pair containing the extracted token and the
     246             : /// remaining tail string.
     247             : std::pair<StringRef, StringRef> getToken(StringRef Source,
     248             :                                          StringRef Delimiters = " \t\n\v\f\r");
     249             : 
     250             : /// SplitString - Split up the specified string according to the specified
     251             : /// delimiters, appending the result fragments to the output list.
     252             : void SplitString(StringRef Source,
     253             :                  SmallVectorImpl<StringRef> &OutFragments,
     254             :                  StringRef Delimiters = " \t\n\v\f\r");
     255             : 
     256             : /// Returns the English suffix for an ordinal integer (-st, -nd, -rd, -th).
     257        5783 : inline StringRef getOrdinalSuffix(unsigned Val) {
     258             :   // It is critically important that we do this perfectly for
     259             :   // user-written sequences with over 100 elements.
     260        5783 :   switch (Val % 100) {
     261             :   case 11:
     262             :   case 12:
     263             :   case 13:
     264           0 :     return "th";
     265        5783 :   default:
     266        5783 :     switch (Val % 10) {
     267        5395 :       case 1: return "st";
     268         266 :       case 2: return "nd";
     269         107 :       case 3: return "rd";
     270          15 :       default: return "th";
     271             :     }
     272             :   }
     273             : }
     274             : 
     275             : /// Print each character of the specified string, escaping it if it is not
     276             : /// printable or if it is an escape char.
     277             : void printEscapedString(StringRef Name, raw_ostream &Out);
     278             : 
     279             : /// Print each character of the specified string, escaping HTML special
     280             : /// characters.
     281             : void printHTMLEscaped(StringRef String, raw_ostream &Out);
     282             : 
     283             : /// printLowerCase - Print each character as lowercase if it is uppercase.
     284             : void printLowerCase(StringRef String, raw_ostream &Out);
     285             : 
     286             : namespace detail {
     287             : 
     288             : template <typename IteratorT>
     289             : inline std::string join_impl(IteratorT Begin, IteratorT End,
     290             :                              StringRef Separator, std::input_iterator_tag) {
     291             :   std::string S;
     292             :   if (Begin == End)
     293             :     return S;
     294             : 
     295             :   S += (*Begin);
     296             :   while (++Begin != End) {
     297             :     S += Separator;
     298             :     S += (*Begin);
     299             :   }
     300             :   return S;
     301             : }
     302             : 
     303             : template <typename IteratorT>
     304      399284 : inline std::string join_impl(IteratorT Begin, IteratorT End,
     305             :                              StringRef Separator, std::forward_iterator_tag) {
     306             :   std::string S;
     307      399284 :   if (Begin == End)
     308             :     return S;
     309             : 
     310      375840 :   size_t Len = (std::distance(Begin, End) - 1) * Separator.size();
     311     2396137 :   for (IteratorT I = Begin; I != End; ++I)
     312     2010871 :     Len += (*Begin).size();
     313      375840 :   S.reserve(Len);
     314             :   S += (*Begin);
     315     2010871 :   while (++Begin != End) {
     316             :     S += Separator;
     317             :     S += (*Begin);
     318             :   }
     319             :   return S;
     320             : }
     321             : 
     322             : template <typename Sep>
     323             : inline void join_items_impl(std::string &Result, Sep Separator) {}
     324             : 
     325             : template <typename Sep, typename Arg>
     326             : inline void join_items_impl(std::string &Result, Sep Separator,
     327             :                             const Arg &Item) {
     328           3 :   Result += Item;
     329             : }
     330             : 
     331             : template <typename Sep, typename Arg1, typename... Args>
     332          12 : inline void join_items_impl(std::string &Result, Sep Separator, const Arg1 &A1,
     333             :                             Args &&... Items) {
     334           6 :   Result += A1;
     335           6 :   Result += Separator;
     336           7 :   join_items_impl(Result, Separator, std::forward<Args>(Items)...);
     337          12 : }
     338             : 
     339             : inline size_t join_one_item_size(char C) { return 1; }
     340          11 : inline size_t join_one_item_size(const char *S) { return S ? ::strlen(S) : 0; }
     341             : 
     342             : template <typename T> inline size_t join_one_item_size(const T &Str) {
     343           6 :   return Str.size();
     344             : }
     345             : 
     346             : inline size_t join_items_size() { return 0; }
     347             : 
     348             : template <typename A1> inline size_t join_items_size(const A1 &A) {
     349           2 :   return join_one_item_size(A);
     350             : }
     351             : template <typename A1, typename... Args>
     352             : inline size_t join_items_size(const A1 &A, Args &&... Items) {
     353           6 :   return join_one_item_size(A) + join_items_size(std::forward<Args>(Items)...);
     354             : }
     355             : 
     356             : } // end namespace detail
     357             : 
     358             : /// Joins the strings in the range [Begin, End), adding Separator between
     359             : /// the elements.
     360             : template <typename IteratorT>
     361             : inline std::string join(IteratorT Begin, IteratorT End, StringRef Separator) {
     362             :   using tag = typename std::iterator_traits<IteratorT>::iterator_category;
     363      399284 :   return detail::join_impl(Begin, End, Separator, tag());
     364             : }
     365             : 
     366             : /// Joins the strings in the range [R.begin(), R.end()), adding Separator
     367             : /// between the elements.
     368             : template <typename Range>
     369             : inline std::string join(Range &&R, StringRef Separator) {
     370             :   return join(R.begin(), R.end(), Separator);
     371             : }
     372             : 
     373             : /// Joins the strings in the parameter pack \p Items, adding \p Separator
     374             : /// between the elements.  All arguments must be implicitly convertible to
     375             : /// std::string, or there should be an overload of std::string::operator+=()
     376             : /// that accepts the argument explicitly.
     377             : template <typename Sep, typename... Args>
     378           8 : inline std::string join_items(Sep Separator, Args &&... Items) {
     379             :   std::string Result;
     380             :   if (sizeof...(Items) == 0)
     381             :     return Result;
     382             : 
     383           3 :   size_t NS = detail::join_one_item_size(Separator);
     384           8 :   size_t NI = detail::join_items_size(std::forward<Args>(Items)...);
     385           8 :   Result.reserve(NI + (sizeof...(Items) - 1) * NS + 1);
     386           7 :   detail::join_items_impl(Result, Separator, std::forward<Args>(Items)...);
     387             :   return Result;
     388             : }
     389             : 
     390             : } // end namespace llvm
     391             : 
     392             : #endif // LLVM_ADT_STRINGEXTRAS_H

Generated by: LCOV version 1.13