diff options
| author | Rémi Verschelde <rverschelde@gmail.com> | 2024-01-04 14:25:40 +0100 |
|---|---|---|
| committer | Rémi Verschelde <rverschelde@gmail.com> | 2024-01-04 14:25:40 +0100 |
| commit | 5fd5176a790b6ec99dac64b9f6a41e4c84967d6b (patch) | |
| tree | 64f38b71572226e5e7f33771bbeb772cbd137d59 /core/string | |
| parent | 6c390b620d231d5f2febf05bddd758582513fe46 (diff) | |
| parent | 931928feb9b7fdb295f638c2b4ffdc30a6dcea5a (diff) | |
| download | redot-engine-5fd5176a790b6ec99dac64b9f6a41e4c84967d6b.tar.gz | |
Merge pull request #84462 from MewPurPur/optimize-humanizesize
Optimize `String.humanize_size()`
Diffstat (limited to 'core/string')
| -rw-r--r-- | core/string/ustring.cpp | 47 |
1 files changed, 31 insertions, 16 deletions
diff --git a/core/string/ustring.cpp b/core/string/ustring.cpp index 04904e27c6..6afe28a6a7 100644 --- a/core/string/ustring.cpp +++ b/core/string/ustring.cpp @@ -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 { |
