LCOV - code coverage report
Current view: top level - include/llvm/ADT - StringExtras.h (source / functions) Hit Total Coverage
Test: llvm-toolchain.info Lines: 98 99 99.0 %
Date: 2018-02-23 05:02:05 Functions: 46 48 95.8 %
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    45579038 :   const char HexChar = LowerCase ? 'a' : 'A';
      39    45848696 :   return X < 10 ? '0' + X : HexChar + X - 10;
      40             : }
      41             : 
      42             : /// Construct a string ref from a boolean.
      43     1350585 : inline StringRef toStringRef(bool B) { return StringRef(B ? "true" : "false"); }
      44             : 
      45             : /// Construct a string ref from an array ref of unsigned chars.
      46             : inline StringRef toStringRef(ArrayRef<uint8_t> Input) {
      47             :   return StringRef(reinterpret_cast<const char *>(Input.begin()), Input.size());
      48             : }
      49             : 
      50             : /// Construct a string ref from an array ref of unsigned chars.
      51             : inline ArrayRef<uint8_t> arrayRefFromStringRef(StringRef Input) {
      52             :   return {Input.bytes_begin(), Input.bytes_end()};
      53             : }
      54             : 
      55             : /// Interpret the given character \p C as a hexadecimal digit and return its
      56             : /// value.
      57             : ///
      58             : /// If \p C is not a valid hex digit, -1U is returned.
      59             : inline unsigned hexDigitValue(char C) {
      60     1998889 :   if (C >= '0' && C <= '9') return C-'0';
      61      687656 :   if (C >= 'a' && C <= 'f') return C-'a'+10U;
      62      623524 :   if (C >= 'A' && C <= 'F') return C-'A'+10U;
      63             :   return -1U;
      64             : }
      65             : 
      66             : /// Checks if character \p C is one of the 10 decimal digits.
      67    12771903 : inline bool isDigit(char C) { return C >= '0' && C <= '9'; }
      68             : 
      69             : /// Checks if character \p C is a hexadecimal numeric character.
      70       29872 : inline bool isHexDigit(char C) { return hexDigitValue(C) != -1U; }
      71             : 
      72             : /// Checks if character \p C is a valid letter as classified by "C" locale.
      73             : inline bool isAlpha(char C) {
      74    34257266 :   return ('a' <= C && C <= 'z') || ('A' <= C && C <= 'Z');
      75             : }
      76             : 
      77             : /// Checks whether character \p C is either a decimal digit or an uppercase or
      78             : /// lowercase letter as classified by "C" locale.
      79    39161378 : inline bool isAlnum(char C) { return isAlpha(C) || isDigit(C); }
      80             : 
      81             : /// Returns the corresponding lowercase character if \p x is uppercase.
      82             : inline char toLower(char x) {
      83   143411060 :   if (x >= 'A' && x <= 'Z')
      84    58419742 :     return x - 'A' + 'a';
      85             :   return x;
      86             : }
      87             : 
      88             : /// Returns the corresponding uppercase character if \p x is lowercase.
      89             : inline char toUpper(char x) {
      90     1736651 :   if (x >= 'a' && x <= 'z')
      91     1237443 :     return x - 'a' + 'A';
      92             :   return x;
      93             : }
      94             : 
      95        4933 : inline std::string utohexstr(uint64_t X, bool LowerCase = false) {
      96             :   char Buffer[17];
      97             :   char *BufPtr = std::end(Buffer);
      98             : 
      99        4933 :   if (X == 0) *--BufPtr = '0';
     100             : 
     101       48345 :   while (X) {
     102       21706 :     unsigned char Mod = static_cast<unsigned char>(X) & 15;
     103       43412 :     *--BufPtr = hexdigit(Mod, LowerCase);
     104       21706 :     X >>= 4;
     105             :   }
     106             : 
     107        4933 :   return std::string(BufPtr, std::end(Buffer));
     108             : }
     109             : 
     110             : /// Convert buffer \p Input to its hexadecimal representation.
     111             : /// The returned string is double the size of \p Input.
     112         460 : inline std::string toHex(StringRef Input) {
     113             :   static const char *const LUT = "0123456789ABCDEF";
     114             :   size_t Length = Input.size();
     115             : 
     116             :   std::string Output;
     117         460 :   Output.reserve(2 * Length);
     118       16006 :   for (size_t i = 0; i < Length; ++i) {
     119       15546 :     const unsigned char c = Input[i];
     120        7773 :     Output.push_back(LUT[c >> 4]);
     121        7773 :     Output.push_back(LUT[c & 15]);
     122             :   }
     123         460 :   return Output;
     124             : }
     125             : 
     126             : inline std::string toHex(ArrayRef<uint8_t> Input) {
     127         356 :   return toHex(toStringRef(Input));
     128             : }
     129             : 
     130        2143 : inline uint8_t hexFromNibbles(char MSB, char LSB) {
     131        2143 :   unsigned U1 = hexDigitValue(MSB);
     132        2143 :   unsigned U2 = hexDigitValue(LSB);
     133             :   assert(U1 != -1U && U2 != -1U);
     134             : 
     135        2143 :   return static_cast<uint8_t>((U1 << 4) | U2);
     136             : }
     137             : 
     138             : /// Convert hexadecimal string \p Input to its binary representation.
     139             : /// The return string is half the size of \p Input.
     140         153 : inline std::string fromHex(StringRef Input) {
     141         153 :   if (Input.empty())
     142             :     return std::string();
     143             : 
     144             :   std::string Output;
     145         135 :   Output.reserve((Input.size() + 1) / 2);
     146         135 :   if (Input.size() % 2 == 1) {
     147           3 :     Output.push_back(hexFromNibbles('0', Input.front()));
     148           1 :     Input = Input.drop_front();
     149             :   }
     150             : 
     151             :   assert(Input.size() % 2 == 0);
     152        4421 :   while (!Input.empty()) {
     153        6429 :     uint8_t Hex = hexFromNibbles(Input[0], Input[1]);
     154        2143 :     Output.push_back(Hex);
     155        2143 :     Input = Input.drop_front(2);
     156             :   }
     157             :   return Output;
     158             : }
     159             : 
     160             : /// \brief Convert the string \p S to an integer of the specified type using
     161             : /// the radix \p Base.  If \p Base is 0, auto-detects the radix.
     162             : /// Returns true if the number was successfully converted, false otherwise.
     163         550 : template <typename N> bool to_integer(StringRef S, N &Num, unsigned Base = 0) {
     164         550 :   return !S.getAsInteger(Base, Num);
     165             : }
     166             : 
     167             : namespace detail {
     168             : template <typename N>
     169          47 : inline bool to_float(const Twine &T, N &Num, N (*StrTo)(const char *, char **)) {
     170             :   SmallString<32> Storage;
     171          47 :   StringRef S = T.toNullTerminatedStringRef(Storage);
     172             :   char *End;
     173          47 :   N Temp = StrTo(S.data(), &End);
     174          47 :   if (*End != '\0')
     175             :     return false;
     176          43 :   Num = Temp;
     177          43 :   return true;
     178             : }
     179             : }
     180             : 
     181             : inline bool to_float(const Twine &T, float &Num) {
     182          11 :   return detail::to_float(T, Num, strtof);
     183             : }
     184             : 
     185             : inline bool to_float(const Twine &T, double &Num) {
     186          35 :   return detail::to_float(T, Num, strtod);
     187             : }
     188             : 
     189             : inline bool to_float(const Twine &T, long double &Num) {
     190           1 :   return detail::to_float(T, Num, strtold);
     191             : }
     192             : 
     193     4223035 : inline std::string utostr(uint64_t X, bool isNeg = false) {
     194             :   char Buffer[21];
     195             :   char *BufPtr = std::end(Buffer);
     196             : 
     197     4223035 :   if (X == 0) *--BufPtr = '0';  // Handle special case...
     198             : 
     199    18360507 :   while (X) {
     200     7068736 :     *--BufPtr = '0' + char(X % 10);
     201     7068736 :     X /= 10;
     202             :   }
     203             : 
     204     4223035 :   if (isNeg) *--BufPtr = '-';   // Add negative sign...
     205     4223035 :   return std::string(BufPtr, std::end(Buffer));
     206             : }
     207             : 
     208     1265187 : inline std::string itostr(int64_t X) {
     209     1265187 :   if (X < 0)
     210      120770 :     return utostr(static_cast<uint64_t>(-X), true);
     211             :   else
     212     1145576 :     return utostr(static_cast<uint64_t>(X));
     213             : }
     214             : 
     215             : /// StrInStrNoCase - Portable version of strcasestr.  Locates the first
     216             : /// occurrence of string 's1' in string 's2', ignoring case.  Returns
     217             : /// the offset of s2 in s1 or npos if s2 cannot be found.
     218             : StringRef::size_type StrInStrNoCase(StringRef s1, StringRef s2);
     219             : 
     220             : /// getToken - This function extracts one token from source, ignoring any
     221             : /// leading characters that appear in the Delimiters string, and ending the
     222             : /// token at any of the characters that appear in the Delimiters string.  If
     223             : /// there are no tokens in the source string, an empty string is returned.
     224             : /// The function returns a pair containing the extracted token and the
     225             : /// remaining tail string.
     226             : std::pair<StringRef, StringRef> getToken(StringRef Source,
     227             :                                          StringRef Delimiters = " \t\n\v\f\r");
     228             : 
     229             : /// SplitString - Split up the specified string according to the specified
     230             : /// delimiters, appending the result fragments to the output list.
     231             : void SplitString(StringRef Source,
     232             :                  SmallVectorImpl<StringRef> &OutFragments,
     233             :                  StringRef Delimiters = " \t\n\v\f\r");
     234             : 
     235             : /// HashString - Hash function for strings.
     236             : ///
     237             : /// This is the Bernstein hash function.
     238             : //
     239             : // FIXME: Investigate whether a modified bernstein hash function performs
     240             : // better: http://eternallyconfuzzled.com/tuts/algorithms/jsw_tut_hashing.aspx
     241             : //   X*33+c -> X*33^c
     242             : inline unsigned HashString(StringRef Str, unsigned Result = 0) {
     243 16304106452 :   for (StringRef::size_type i = 0, e = Str.size(); i != e; ++i)
     244 15699655996 :     Result = Result * 33 + (unsigned char)Str[i];
     245             :   return Result;
     246             : }
     247             : 
     248             : /// Returns the English suffix for an ordinal integer (-st, -nd, -rd, -th).
     249        5765 : inline StringRef getOrdinalSuffix(unsigned Val) {
     250             :   // It is critically important that we do this perfectly for
     251             :   // user-written sequences with over 100 elements.
     252        5765 :   switch (Val % 100) {
     253             :   case 11:
     254             :   case 12:
     255             :   case 13:
     256           0 :     return "th";
     257        5765 :   default:
     258        5765 :     switch (Val % 10) {
     259        5438 :       case 1: return "st";
     260         205 :       case 2: return "nd";
     261         107 :       case 3: return "rd";
     262          15 :       default: return "th";
     263             :     }
     264             :   }
     265             : }
     266             : 
     267             : /// PrintEscapedString - Print each character of the specified string, escaping
     268             : /// it if it is not printable or if it is an escape char.
     269             : void PrintEscapedString(StringRef Name, raw_ostream &Out);
     270             : 
     271             : /// printLowerCase - Print each character as lowercase if it is uppercase.
     272             : void printLowerCase(StringRef String, raw_ostream &Out);
     273             : 
     274             : namespace detail {
     275             : 
     276             : template <typename IteratorT>
     277             : inline std::string join_impl(IteratorT Begin, IteratorT End,
     278             :                              StringRef Separator, std::input_iterator_tag) {
     279             :   std::string S;
     280             :   if (Begin == End)
     281             :     return S;
     282             : 
     283             :   S += (*Begin);
     284             :   while (++Begin != End) {
     285             :     S += Separator;
     286             :     S += (*Begin);
     287             :   }
     288             :   return S;
     289             : }
     290             : 
     291             : template <typename IteratorT>
     292      309612 : inline std::string join_impl(IteratorT Begin, IteratorT End,
     293             :                              StringRef Separator, std::forward_iterator_tag) {
     294             :   std::string S;
     295      309612 :   if (Begin == End)
     296             :     return S;
     297             : 
     298      288982 :   size_t Len = (std::distance(Begin, End) - 1) * Separator.size();
     299     1868026 :   for (IteratorT I = Begin; I != End; ++I)
     300     1572527 :     Len += (*Begin).size();
     301      288982 :   S.reserve(Len);
     302             :   S += (*Begin);
     303     1572527 :   while (++Begin != End) {
     304             :     S += Separator;
     305             :     S += (*Begin);
     306             :   }
     307             :   return S;
     308             : }
     309             : 
     310             : template <typename Sep>
     311             : inline void join_items_impl(std::string &Result, Sep Separator) {}
     312             : 
     313             : template <typename Sep, typename Arg>
     314             : inline void join_items_impl(std::string &Result, Sep Separator,
     315             :                             const Arg &Item) {
     316           3 :   Result += Item;
     317             : }
     318             : 
     319             : template <typename Sep, typename Arg1, typename... Args>
     320          12 : inline void join_items_impl(std::string &Result, Sep Separator, const Arg1 &A1,
     321             :                             Args &&... Items) {
     322           6 :   Result += A1;
     323           6 :   Result += Separator;
     324           7 :   join_items_impl(Result, Separator, std::forward<Args>(Items)...);
     325          12 : }
     326             : 
     327             : inline size_t join_one_item_size(char C) { return 1; }
     328          11 : inline size_t join_one_item_size(const char *S) { return S ? ::strlen(S) : 0; }
     329             : 
     330             : template <typename T> inline size_t join_one_item_size(const T &Str) {
     331           6 :   return Str.size();
     332             : }
     333             : 
     334             : inline size_t join_items_size() { return 0; }
     335             : 
     336             : template <typename A1> inline size_t join_items_size(const A1 &A) {
     337           2 :   return join_one_item_size(A);
     338             : }
     339             : template <typename A1, typename... Args>
     340             : inline size_t join_items_size(const A1 &A, Args &&... Items) {
     341           6 :   return join_one_item_size(A) + join_items_size(std::forward<Args>(Items)...);
     342             : }
     343             : 
     344             : } // end namespace detail
     345             : 
     346             : /// Joins the strings in the range [Begin, End), adding Separator between
     347             : /// the elements.
     348             : template <typename IteratorT>
     349             : inline std::string join(IteratorT Begin, IteratorT End, StringRef Separator) {
     350             :   using tag = typename std::iterator_traits<IteratorT>::iterator_category;
     351      309612 :   return detail::join_impl(Begin, End, Separator, tag());
     352             : }
     353             : 
     354             : /// Joins the strings in the range [R.begin(), R.end()), adding Separator
     355             : /// between the elements.
     356             : template <typename Range>
     357             : inline std::string join(Range &&R, StringRef Separator) {
     358             :   return join(R.begin(), R.end(), Separator);
     359             : }
     360             : 
     361             : /// Joins the strings in the parameter pack \p Items, adding \p Separator
     362             : /// between the elements.  All arguments must be implicitly convertible to
     363             : /// std::string, or there should be an overload of std::string::operator+=()
     364             : /// that accepts the argument explicitly.
     365             : template <typename Sep, typename... Args>
     366           8 : inline std::string join_items(Sep Separator, Args &&... Items) {
     367             :   std::string Result;
     368             :   if (sizeof...(Items) == 0)
     369             :     return Result;
     370             : 
     371           3 :   size_t NS = detail::join_one_item_size(Separator);
     372           8 :   size_t NI = detail::join_items_size(std::forward<Args>(Items)...);
     373           8 :   Result.reserve(NI + (sizeof...(Items) - 1) * NS + 1);
     374           7 :   detail::join_items_impl(Result, Separator, std::forward<Args>(Items)...);
     375             :   return Result;
     376             : }
     377             : 
     378             : } // end namespace llvm
     379             : 
     380             : #endif // LLVM_ADT_STRINGEXTRAS_H

Generated by: LCOV version 1.13