Skip to content

Commit 3542bbd

Browse files
committed
create util::format namespace for string prettifying
1 parent cce171b commit 3542bbd

File tree

2 files changed

+38
-26
lines changed

2 files changed

+38
-26
lines changed

api/util/pretty.hpp

Lines changed: 35 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,35 @@
1+
#ifndef UTIL_PRETTY_HPP
2+
#define UTIL_PRETTY_HPP
3+
4+
#include <format>
5+
#include <string>
6+
7+
namespace util::format {
8+
inline std::string to_human_size(std::size_t bytes) {
9+
constexpr std::string_view size_suffixes[] = {
10+
"B", "KiB", "MiB", "GiB", "TiB", "PiB"
11+
};
12+
double value = static_cast<double>(bytes);
13+
std::size_t exponent = 0;
14+
15+
while (value >= 1024.0 && exponent + 1 < std::size(size_suffixes)) {
16+
value /= 1024.0;
17+
exponent++;
18+
}
19+
20+
if (exponent == 0)
21+
return std::format("{} {}", static_cast<std::uint64_t>(value), size_suffixes[exponent]);
22+
else
23+
return std::format("{:.2f} {}", value, size_suffixes[exponent]);
24+
}
25+
26+
inline std::string with_thousands_sep(uint64_t value, char sep = '_', char every = 3) {
27+
std::string s = std::to_string(value);
28+
for (int i = s.size() - every; i > 0; i -= every)
29+
s.insert(i, 1, sep);
30+
return s;
31+
}
32+
} // namespace util
33+
34+
#endif // UTIL_PRETTY_HPP
35+

src/kernel/profile.cpp

Lines changed: 3 additions & 26 deletions
Original file line numberDiff line numberDiff line change
@@ -22,6 +22,7 @@
2222
#include <kernel/elf.hpp>
2323
#include <os.hpp>
2424
#include <util/fixed_vector.hpp>
25+
#include <util/pretty.hpp>
2526
#include <unordered_map>
2627
#include <cassert>
2728
#include <algorithm>
@@ -203,33 +204,9 @@ void StackSampler::set_mask(bool mask)
203204
get().discard = mask;
204205
}
205206

206-
207-
inline std::string to_human_size(std::uint64_t bytes) {
208-
constexpr std::string_view size_suffixes[] = {
209-
"B", "KiB", "MiB", "GiB", "TiB", "PiB"
210-
};
211-
double value = static_cast<double>(bytes);
212-
std::size_t exponent = 0;
213-
214-
while (value >= 1024.0 && exponent + 1 < std::size(size_suffixes)) {
215-
value /= 1024.0;
216-
exponent++;
217-
}
218-
219-
if (exponent == 0)
220-
return std::format("{} {}", static_cast<std::uint64_t>(value), size_suffixes[exponent]);
221-
else
222-
return std::format("{:.2f} {}", value, size_suffixes[exponent]);
223-
}
224-
225-
inline std::string with_thousands_sep(uint64_t value, char sep = '_', char every = 3) {
226-
std::string s = std::to_string(value);
227-
for (int i = s.size() - every; i > 0; i -= every)
228-
s.insert(i, 1, sep);
229-
return s;
230-
}
231-
232207
std::string HeapDiag::to_string() {
208+
using namespace util::format;
209+
233210
// TODO: check if heap should be 64 bit instead
234211
static intptr_t last_size = 0;
235212

0 commit comments

Comments
 (0)