-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathunits.cpp
More file actions
92 lines (74 loc) · 2.75 KB
/
units.cpp
File metadata and controls
92 lines (74 loc) · 2.75 KB
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
#include "units.hpp"
#include <algorithm>
#include <map>
#include <stdexcept>
#include <vector>
std::string bytes2human(uint64_t size){
static const std::vector<std::string> units { "", "kb", "mb", "gb", "tb" };
if( size == 0 )
return "0";
int i = 0;
while( i<units.size()-1 && size > 4096 ){
i++;
size/=1024;
}
return std::to_string(size) + units[i];
}
uint64_t human2bytes(const std::string& size) {
static const std::map<std::string, uint64_t> units = {
{"kb", 1024},
{"mb", 1024 * 1024},
{"gb", 1024 * 1024 * 1024},
{"tb", 1024ULL * 1024 * 1024 * 1024}
};
// if size starts with "0x" then it's a hex number
if (size.length() > 2 && size[0] == '0' && (size[1]|0x20) == 'x') {
return std::stoull(size, nullptr, 16);
}
size_t i = 0;
for (; i < size.length(); ++i) {
if (!isdigit(size[i])) {
break;
}
}
std::string numberPart = size.substr(0, i);
std::string unitPart = i < size.length() ? size.substr(i) : "";
std::transform(unitPart.begin(), unitPart.end(), unitPart.begin(), ::tolower);
uint64_t number = std::stoull(numberPart);
if( unitPart.size() == 1 )
unitPart += 'b';
if (!unitPart.empty() && units.find(unitPart) == units.end()) {
throw std::runtime_error("Unsupported unit: " + unitPart);
}
uint64_t multiplier = unitPart.empty() ? 1 : units.at(unitPart);
if (multiplier > 1 && number > UINT64_MAX / multiplier) {
throw std::runtime_error("Resulting value out of range.");
}
return number * multiplier;
}
std::string seconds2human(uint64_t seconds, size_t maxUnits) {
// Define time units and their corresponding abbreviations
static const std::vector<std::pair<uint64_t, std::string>> units = {
{86400, "d"}, // Days
{3600, "h"}, // Hours
{60, "m"}, // Minutes
{1, "s"} // Seconds
};
std::string result;
size_t unitsAdded = 0;
for (const auto& unit : units) {
if (seconds >= unit.first || unitsAdded > 0) { // Ensure we process lower units if a higher one has been added
if (unitsAdded < maxUnits) {
uint64_t amount = seconds / unit.first;
seconds %= unit.first; // Calculate remainder for the next unit
if (amount > 0 || unitsAdded > 0) { // Add the unit if it's non-zero or if we've already added a unit before
result += std::to_string(amount) + unit.second;
++unitsAdded;
}
} else {
break; // Stop if we've added the maximum number of units
}
}
}
return result.empty() ? "0s" : result; // Handle the case where seconds is 0
}