Merge pull request #84462 from MewPurPur/optimize-humanizesize

Optimize `String.humanize_size()`
This commit is contained in:
Rémi Verschelde 2024-01-04 14:25:40 +01:00
commit 5fd5176a79
No known key found for this signature in database
GPG key ID: C3336907360768E1

View file

@ -3961,27 +3961,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 {