Optimize String.humanize_size()

This commit is contained in:
MewPurPur 2023-11-05 00:09:23 +02:00
parent b733901e9e
commit 931928feb9

View file

@ -3941,27 +3941,42 @@ static int _humanize_digits(int p_num) {
}
String String::humanize_size(uint64_t p_size) {
int magnitude = 0;
uint64_t _div = 1;
Vector<String> prefixes;
prefixes.push_back(RTR("B"));
prefixes.push_back(RTR("KiB"));
prefixes.push_back(RTR("MiB"));
prefixes.push_back(RTR("GiB"));
prefixes.push_back(RTR("TiB"));
prefixes.push_back(RTR("PiB"));
prefixes.push_back(RTR("EiB"));
int prefix_idx = 0;
while (prefix_idx < prefixes.size() - 1 && p_size > (_div * 1024)) {
while (p_size > _div * 1024 && magnitude < 6) {
_div *= 1024;
prefix_idx++;
magnitude++;
}
const int digits = prefix_idx > 0 ? _humanize_digits(p_size / _div) : 0;
const double divisor = prefix_idx > 0 ? _div : 1;
if (magnitude == 0) {
return String::num(p_size) + " " + RTR("B");
} else {
String suffix;
switch (magnitude) {
case 1:
suffix = RTR("KiB");
break;
case 2:
suffix = RTR("MiB");
break;
case 3:
suffix = RTR("GiB");
break;
case 4:
suffix = RTR("TiB");
break;
case 5:
suffix = RTR("PiB");
break;
case 6:
suffix = RTR("EiB");
break;
}
return String::num(p_size / divisor).pad_decimals(digits) + " " + prefixes[prefix_idx];
const double divisor = _div;
const int digits = _humanize_digits(p_size / _div);
return String::num(p_size / divisor).pad_decimals(digits) + " " + suffix;
}
}
bool String::is_absolute_path() const {