StringExtras.h revision b2109ce97881269a610fa4afbcbca350e975174d
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(uint64_t 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 X, bool isNeg = false) {
65  char Buffer[20];
66  char *BufPtr = Buffer+19;
67
68  *BufPtr = 0;                  // Null terminate buffer...
69  if (X == 0) *--BufPtr = '0';  // Handle special case...
70
71  while (X) {
72    *--BufPtr = '0' + (X % 10);
73    X /= 10;
74  }
75
76  if (isNeg) *--BufPtr = '-';   // Add negative sign...
77
78  return std::string(BufPtr);
79}
80
81static inline std::string itostr(int X) {
82  if (X < 0)
83    return utostr((unsigned)-X, true);
84  else
85    return utostr((unsigned)X);
86}
87
88static inline std::string ftostr(double V) {
89  char Buffer[200];
90  snprintf(Buffer, 200, "%20.6e", V);
91  return Buffer;
92}
93
94#endif
95