LCOV - code coverage report
Current view: top level - include/llvm/ADT - StringExtras.h (source / functions) Hit Total Coverage
Test: llvm-toolchain.info Lines: 104 106 98.1 %
Date: 2017-09-14 15:23:50 Functions: 43 43 100.0 %
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 <cassert>
      21             : #include <cstddef>
      22             : #include <cstdint>
      23             : #include <cstdlib>
      24             : #include <cstring>
      25             : #include <iterator>
      26             : #include <string>
      27             : #include <utility>
      28             : 
      29             : namespace llvm {
      30             : 
      31             : template<typename T> class SmallVectorImpl;
      32             : class raw_ostream;
      33             : 
      34             : /// hexdigit - Return the hexadecimal character for the
      35             : /// given number \p X (which should be less than 16).
      36             : static inline char hexdigit(unsigned X, bool LowerCase = false) {
      37    45455831 :   const char HexChar = LowerCase ? 'a' : 'A';
      38    45455801 :   return X < 10 ? '0' + X : HexChar + X - 10;
      39             : }
      40             : 
      41             : /// Construct a string ref from a boolean.
      42             : static inline StringRef toStringRef(bool B) {
      43     2230728 :   return StringRef(B ? "true" : "false");
      44             : }
      45             : 
      46             : /// Construct a string ref from an array ref of unsigned chars.
      47             : static inline StringRef toStringRef(ArrayRef<uint8_t> Input) {
      48        2157 :   return StringRef(reinterpret_cast<const char *>(Input.begin()), Input.size());
      49             : }
      50             : 
      51             : /// Interpret the given character \p C as a hexadecimal digit and return its
      52             : /// value.
      53             : ///
      54             : /// If \p C is not a valid hex digit, -1U is returned.
      55             : static inline unsigned hexDigitValue(char C) {
      56     1513771 :   if (C >= '0' && C <= '9') return C-'0';
      57       89388 :   if (C >= 'a' && C <= 'f') return C-'a'+10U;
      58       70357 :   if (C >= 'A' && C <= 'F') return C-'A'+10U;
      59             :   return -1U;
      60             : }
      61             : 
      62       49564 : static inline std::string utohexstr(uint64_t X, bool LowerCase = false) {
      63             :   char Buffer[17];
      64       49564 :   char *BufPtr = std::end(Buffer);
      65             : 
      66       49564 :   if (X == 0) *--BufPtr = '0';
      67             : 
      68      458250 :   while (X) {
      69      204343 :     unsigned char Mod = static_cast<unsigned char>(X) & 15;
      70      408686 :     *--BufPtr = hexdigit(Mod, LowerCase);
      71      204343 :     X >>= 4;
      72             :   }
      73             : 
      74      198256 :   return std::string(BufPtr, std::end(Buffer));
      75             : }
      76             : 
      77             : /// Convert buffer \p Input to its hexadecimal representation.
      78             : /// The returned string is double the size of \p Input.
      79         398 : inline std::string toHex(StringRef Input) {
      80             :   static const char *const LUT = "0123456789ABCDEF";
      81         398 :   size_t Length = Input.size();
      82             : 
      83         398 :   std::string Output;
      84         398 :   Output.reserve(2 * Length);
      85        7015 :   for (size_t i = 0; i < Length; ++i) {
      86       13238 :     const unsigned char c = Input[i];
      87        6619 :     Output.push_back(LUT[c >> 4]);
      88        6613 :     Output.push_back(LUT[c & 15]);
      89             :   }
      90         398 :   return Output;
      91             : }
      92             : 
      93             : inline std::string toHex(ArrayRef<uint8_t> Input) {
      94         322 :   return toHex(toStringRef(Input));
      95             : }
      96             : 
      97         457 : static inline uint8_t hexFromNibbles(char MSB, char LSB) {
      98         915 :   unsigned U1 = hexDigitValue(MSB);
      99         915 :   unsigned U2 = hexDigitValue(LSB);
     100             :   assert(U1 != -1U && U2 != -1U);
     101             : 
     102         457 :   return static_cast<uint8_t>((U1 << 4) | U2);
     103             : }
     104             : 
     105             : /// Convert hexadecimal string \p Input to its binary representation.
     106             : /// The return string is half the size of \p Input.
     107          32 : static inline std::string fromHex(StringRef Input) {
     108          32 :   if (Input.empty())
     109             :     return std::string();
     110             : 
     111          30 :   std::string Output;
     112          30 :   Output.reserve((Input.size() + 1) / 2);
     113          30 :   if (Input.size() % 2 == 1) {
     114           3 :     Output.push_back(hexFromNibbles('0', Input.front()));
     115           1 :     Input = Input.drop_front();
     116             :   }
     117             : 
     118             :   assert(Input.size() % 2 == 0);
     119         944 :   while (!Input.empty()) {
     120        1371 :     uint8_t Hex = hexFromNibbles(Input[0], Input[1]);
     121         457 :     Output.push_back(Hex);
     122         457 :     Input = Input.drop_front(2);
     123             :   }
     124          30 :   return Output;
     125             : }
     126             : 
     127             : /// \brief Convert the string \p S to an integer of the specified type using
     128             : /// the radix \p Base.  If \p Base is 0, auto-detects the radix.
     129             : /// Returns true if the number was successfully converted, false otherwise.
     130          17 : template <typename N> bool to_integer(StringRef S, N &Num, unsigned Base = 0) {
     131        1348 :   return !S.getAsInteger(Base, Num);
     132             : }
     133             : 
     134             : namespace detail {
     135             : template <typename N>
     136          48 : inline bool to_float(const Twine &T, N &Num, N (*StrTo)(const char *, char **)) {
     137          96 :   SmallString<32> Storage;
     138          48 :   StringRef S = T.toNullTerminatedStringRef(Storage);
     139             :   char *End;
     140          48 :   N Temp = StrTo(S.data(), &End);
     141          48 :   if (*End != '\0')
     142             :     return false;
     143          44 :   Num = Temp;
     144          44 :   return true;
     145             : }
     146             : }
     147             : 
     148             : inline bool to_float(const Twine &T, float &Num) {
     149          11 :   return detail::to_float(T, Num, strtof);
     150             : }
     151             : 
     152             : inline bool to_float(const Twine &T, double &Num) {
     153          36 :   return detail::to_float(T, Num, strtod);
     154             : }
     155             : 
     156             : inline bool to_float(const Twine &T, long double &Num) {
     157           1 :   return detail::to_float(T, Num, strtold);
     158             : }
     159             : 
     160     4068730 : static inline std::string utostr(uint64_t X, bool isNeg = false) {
     161             :   char Buffer[21];
     162     4068730 :   char *BufPtr = std::end(Buffer);
     163             : 
     164     4068730 :   if (X == 0) *--BufPtr = '0';  // Handle special case...
     165             : 
     166    17129462 :   while (X) {
     167     6530366 :     *--BufPtr = '0' + char(X % 10);
     168     6530366 :     X /= 10;
     169             :   }
     170             : 
     171     4068730 :   if (isNeg) *--BufPtr = '-';   // Add negative sign...
     172    16274920 :   return std::string(BufPtr, std::end(Buffer));
     173             : }
     174             : 
     175     1554470 : static inline std::string itostr(int64_t X) {
     176     1554470 :   if (X < 0)
     177      118262 :     return utostr(static_cast<uint64_t>(-X), true);
     178             :   else
     179     1437308 :     return utostr(static_cast<uint64_t>(X));
     180             : }
     181             : 
     182             : /// StrInStrNoCase - Portable version of strcasestr.  Locates the first
     183             : /// occurrence of string 's1' in string 's2', ignoring case.  Returns
     184             : /// the offset of s2 in s1 or npos if s2 cannot be found.
     185             : StringRef::size_type StrInStrNoCase(StringRef s1, StringRef s2);
     186             : 
     187             : /// getToken - This function extracts one token from source, ignoring any
     188             : /// leading characters that appear in the Delimiters string, and ending the
     189             : /// token at any of the characters that appear in the Delimiters string.  If
     190             : /// there are no tokens in the source string, an empty string is returned.
     191             : /// The function returns a pair containing the extracted token and the
     192             : /// remaining tail string.
     193             : std::pair<StringRef, StringRef> getToken(StringRef Source,
     194             :                                          StringRef Delimiters = " \t\n\v\f\r");
     195             : 
     196             : /// SplitString - Split up the specified string according to the specified
     197             : /// delimiters, appending the result fragments to the output list.
     198             : void SplitString(StringRef Source,
     199             :                  SmallVectorImpl<StringRef> &OutFragments,
     200             :                  StringRef Delimiters = " \t\n\v\f\r");
     201             : 
     202             : /// HashString - Hash function for strings.
     203             : ///
     204             : /// This is the Bernstein hash function.
     205             : //
     206             : // FIXME: Investigate whether a modified bernstein hash function performs
     207             : // better: http://eternallyconfuzzled.com/tuts/algorithms/jsw_tut_hashing.aspx
     208             : //   X*33+c -> X*33^c
     209             : static inline unsigned HashString(StringRef Str, unsigned Result = 0) {
     210  7001100979 :   for (StringRef::size_type i = 0, e = Str.size(); i != e; ++i)
     211 13010410602 :     Result = Result * 33 + (unsigned char)Str[i];
     212             :   return Result;
     213             : }
     214             : 
     215             : /// Returns the English suffix for an ordinal integer (-st, -nd, -rd, -th).
     216        4712 : static inline StringRef getOrdinalSuffix(unsigned Val) {
     217             :   // It is critically important that we do this perfectly for
     218             :   // user-written sequences with over 100 elements.
     219        4712 :   switch (Val % 100) {
     220           0 :   case 11:
     221             :   case 12:
     222             :   case 13:
     223           0 :     return "th";
     224        4712 :   default:
     225        4712 :     switch (Val % 10) {
     226        4424 :       case 1: return "st";
     227         166 :       case 2: return "nd";
     228         107 :       case 3: return "rd";
     229          15 :       default: return "th";
     230             :     }
     231             :   }
     232             : }
     233             : 
     234             : /// PrintEscapedString - Print each character of the specified string, escaping
     235             : /// it if it is not printable or if it is an escape char.
     236             : void PrintEscapedString(StringRef Name, raw_ostream &Out);
     237             : 
     238             : namespace detail {
     239             : 
     240             : template <typename IteratorT>
     241             : inline std::string join_impl(IteratorT Begin, IteratorT End,
     242             :                              StringRef Separator, std::input_iterator_tag) {
     243             :   std::string S;
     244             :   if (Begin == End)
     245             :     return S;
     246             : 
     247             :   S += (*Begin);
     248             :   while (++Begin != End) {
     249             :     S += Separator;
     250             :     S += (*Begin);
     251             :   }
     252             :   return S;
     253             : }
     254             : 
     255             : template <typename IteratorT>
     256      149561 : inline std::string join_impl(IteratorT Begin, IteratorT End,
     257             :                              StringRef Separator, std::forward_iterator_tag) {
     258      149561 :   std::string S;
     259      149561 :   if (Begin == End)
     260             :     return S;
     261             : 
     262      131699 :   size_t Len = (std::distance(Begin, End) - 1) * Separator.size();
     263      932545 :   for (IteratorT I = Begin; I != End; ++I)
     264      672670 :     Len += (*Begin).size();
     265      131699 :   S.reserve(Len);
     266      128194 :   S += (*Begin);
     267     1340652 :   while (++Begin != End) {
     268      540953 :     S += Separator;
     269      539806 :     S += (*Begin);
     270             :   }
     271             :   return S;
     272             : }
     273             : 
     274             : template <typename Sep>
     275             : inline void join_items_impl(std::string &Result, Sep Separator) {}
     276             : 
     277             : template <typename Sep, typename Arg>
     278             : inline void join_items_impl(std::string &Result, Sep Separator,
     279             :                             const Arg &Item) {
     280          12 :   Result += Item;
     281             : }
     282             : 
     283             : template <typename Sep, typename Arg1, typename... Args>
     284          12 : inline void join_items_impl(std::string &Result, Sep Separator, const Arg1 &A1,
     285             :                             Args &&... Items) {
     286          18 :   Result += A1;
     287          18 :   Result += Separator;
     288          18 :   join_items_impl(Result, Separator, std::forward<Args>(Items)...);
     289          12 : }
     290             : 
     291             : inline size_t join_one_item_size(char C) { return 1; }
     292          11 : inline size_t join_one_item_size(const char *S) { return S ? ::strlen(S) : 0; }
     293             : 
     294             : template <typename T> inline size_t join_one_item_size(const T &Str) {
     295           4 :   return Str.size();
     296             : }
     297             : 
     298             : inline size_t join_items_size() { return 0; }
     299             : 
     300             : template <typename A1> inline size_t join_items_size(const A1 &A) {
     301           8 :   return join_one_item_size(A);
     302             : }
     303             : template <typename A1, typename... Args>
     304             : inline size_t join_items_size(const A1 &A, Args &&... Items) {
     305          20 :   return join_one_item_size(A) + join_items_size(std::forward<Args>(Items)...);
     306             : }
     307             : 
     308             : } // end namespace detail
     309             : 
     310             : /// Joins the strings in the range [Begin, End), adding Separator between
     311             : /// the elements.
     312             : template <typename IteratorT>
     313             : inline std::string join(IteratorT Begin, IteratorT End, StringRef Separator) {
     314             :   using tag = typename std::iterator_traits<IteratorT>::iterator_category;
     315      149561 :   return detail::join_impl(Begin, End, Separator, tag());
     316             : }
     317             : 
     318             : /// Joins the strings in the range [R.begin(), R.end()), adding Separator
     319             : /// between the elements.
     320             : template <typename Range>
     321             : inline std::string join(Range &&R, StringRef Separator) {
     322        1338 :   return join(R.begin(), R.end(), Separator);
     323             : }
     324             : 
     325             : /// Joins the strings in the parameter pack \p Items, adding \p Separator
     326             : /// between the elements.  All arguments must be implicitly convertible to
     327             : /// std::string, or there should be an overload of std::string::operator+=()
     328             : /// that accepts the argument explicitly.
     329             : template <typename Sep, typename... Args>
     330           8 : inline std::string join_items(Sep Separator, Args &&... Items) {
     331          10 :   std::string Result;
     332             :   if (sizeof...(Items) == 0)
     333             :     return Result;
     334             : 
     335           8 :   size_t NS = detail::join_one_item_size(Separator);
     336          16 :   size_t NI = detail::join_items_size(std::forward<Args>(Items)...);
     337           8 :   Result.reserve(NI + (sizeof...(Items) - 1) * NS + 1);
     338          10 :   detail::join_items_impl(Result, Separator, std::forward<Args>(Items)...);
     339             :   return Result;
     340             : }
     341             : 
     342             : } // end namespace llvm
     343             : 
     344             : #endif // LLVM_ADT_STRINGEXTRAS_H

Generated by: LCOV version 1.13