-
Notifications
You must be signed in to change notification settings - Fork 20
/
text.h
98 lines (79 loc) · 2.59 KB
/
text.h
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
#pragma once
#include "switch.h"
struct size_repr
{
const uint64_t v;
size_repr(const uint64_t value)
: v{value}
{
}
strwlen8_t Get(char *const p) const
{
static const std::pair<const uint64_t, const char *> bases[] =
{
{1024ULL * 1024ULL * 1024ULL * 1024ULL, "tb"},
{1024UL * 1024UL * 1024UL, "gb"},
{1024 * 1024, "mb"},
{1024, "kb"},
};
for (const auto &it : bases)
{
const auto r = double(v) / it.first;
if (r >= 1)
{
const auto repr = it.second;
uint8_t len = sprintf(p, "%.2lf", r);
while (len && p[len - 1] == '0')
--len;
if (len && p[len - 1] == '.')
--len;
p[len] = *repr;
p[len + 1] = repr[1];
return strwlen8_t(p, len + 2);
}
}
return strwlen8_t(p, sprintf(p, "%ub", uint32_t(v)));
}
};
static inline void PrintImpl(Buffer &out, const size_repr &s)
{
out.reserve(32);
out.advance_size(s.Get(out.end()).len);
}
struct dotnotation_repr
{
const uint64_t value;
const char sep;
dotnotation_repr(const uint64_t v, const char separator = ',')
: value{v}, sep{separator}
{
}
strwlen8_t Get(char *const out) const
{
uint16_t t[8];
uint8_t n{0};
auto r = value;
char *o;
do
{
t[n++] = r % 1000;
r /= 1000;
} while (r);
for (o = out + sprintf(out, "%u", t[--n]); n;)
{
*o++ = sep;
o += sprintf(o, "%03u", t[--n]);
}
return {out, uint8_t(o - out)};
}
};
namespace Text
{
uint8_t ToBase(uint64_t input, const uint32_t toBase, char *out);
uint64_t FromBase(const char *const input, const uint32_t len, const uint8_t base);
}
static inline void PrintImpl(Buffer &out, const dotnotation_repr &r)
{
out.reserve(32);
out.advance_size(r.Get(out.end()).len);
}