StringExtras.h revision 0b64ca3cbde361729f357dfc230a1d9dce1717dc
1//===-- Support/StringExtras.h - Useful string functions --------*- C++ -*-===// 2// 3// The LLVM Compiler Infrastructure 4// 5// This file was developed by the LLVM research group and is distributed under 6// the University of Illinois Open Source 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 SUPPORT_STRINGEXTRAS_H 15#define SUPPORT_STRINGEXTRAS_H 16 17#include "Support/DataTypes.h" 18#include <string> 19#include <stdio.h> 20 21static inline std::string utohexstr(uint64_t X) { 22 char Buffer[40]; 23 char *BufPtr = Buffer+39; 24 25 *BufPtr = 0; // Null terminate buffer... 26 if (X == 0) *--BufPtr = '0'; // Handle special case... 27 28 while (X) { 29 unsigned Mod = X & 15; 30 if (Mod < 10) 31 *--BufPtr = '0' + Mod; 32 else 33 *--BufPtr = 'A' + Mod-10; 34 X >>= 4; 35 } 36 return std::string(BufPtr); 37} 38 39static inline std::string utostr(unsigned long long X, bool isNeg = false) { 40 char Buffer[40]; 41 char *BufPtr = Buffer+39; 42 43 *BufPtr = 0; // Null terminate buffer... 44 if (X == 0) *--BufPtr = '0'; // Handle special case... 45 46 while (X) { 47 *--BufPtr = '0' + (X % 10); 48 X /= 10; 49 } 50 51 if (isNeg) *--BufPtr = '-'; // Add negative sign... 52 53 return std::string(BufPtr); 54} 55 56static inline std::string itostr(int64_t X) { 57 if (X < 0) 58 return utostr((uint64_t)-X, true); 59 else 60 return utostr((uint64_t)X); 61} 62 63 64static inline std::string utostr(unsigned long X, bool isNeg = false) { 65 return utostr((unsigned long long)X, isNeg); 66} 67 68static inline std::string utostr(unsigned X, bool isNeg = false) { 69 char Buffer[20]; 70 char *BufPtr = Buffer+19; 71 72 *BufPtr = 0; // Null terminate buffer... 73 if (X == 0) *--BufPtr = '0'; // Handle special case... 74 75 while (X) { 76 *--BufPtr = '0' + (X % 10); 77 X /= 10; 78 } 79 80 if (isNeg) *--BufPtr = '-'; // Add negative sign... 81 82 return std::string(BufPtr); 83} 84 85static inline std::string itostr(int X) { 86 if (X < 0) 87 return utostr((unsigned)-X, true); 88 else 89 return utostr((unsigned)X); 90} 91 92static inline std::string ftostr(double V) { 93 char Buffer[200]; 94 snprintf(Buffer, 200, "%20.6e", V); 95 return Buffer; 96} 97 98#endif 99