1
0
Fork 0
mirror of https://github.com/NixOS/nix synced 2024-09-19 10:50:24 -04:00

Move printSize() into libutil

Also always include the unit (i.e. "MiB" instead of "M").
This commit is contained in:
Eelco Dolstra 2024-05-10 16:49:40 +02:00
parent dbe1b51580
commit 5314430437
4 changed files with 26 additions and 16 deletions

View file

@ -112,6 +112,21 @@ std::string rewriteStrings(std::string s, const StringMap & rewrites)
}
std::string renderSize(uint64_t value)
{
static const std::array<char, 9> prefixes{{
'K', 'K', 'M', 'G', 'T', 'P', 'E', 'Z', 'Y'
}};
size_t power = 0;
double res = value;
while (res > 1024 && power < prefixes.size()) {
++power;
res /= 1024;
}
return fmt("%6.1f %ciB", power == 0 ? res / 1024 : res, prefixes.at(power));
}
bool hasPrefix(std::string_view s, std::string_view prefix)
{
return s.compare(0, prefix.size(), prefix) == 0;

View file

@ -137,6 +137,12 @@ N string2IntWithUnitPrefix(std::string_view s)
throw UsageError("'%s' is not an integer", s);
}
/**
* Pretty-print a byte value, e.g. 12433615056 is rendered as `11.6
* GiB`.
*/
std::string renderSize(uint64_t value);
/**
* Parse a string into a float.
*/

View file

@ -139,21 +139,10 @@ struct CmdPathInfo : StorePathsCommand, MixJSON
void printSize(uint64_t value)
{
if (!humanReadable) {
if (humanReadable)
std::cout << fmt("\t%s", renderSize(value));
else
std::cout << fmt("\t%11d", value);
return;
}
static const std::array<char, 9> idents{{
' ', 'K', 'M', 'G', 'T', 'P', 'E', 'Z', 'Y'
}};
size_t power = 0;
double res = value;
while (res > 1024 && power < idents.size()) {
++power;
res /= 1024;
}
std::cout << fmt("\t%6.1f%c", res, idents.at(power));
}
void run(ref<Store> store, StorePaths && storePaths) override

View file

@ -26,8 +26,8 @@ R""(
```console
# nix path-info --recursive --size --closure-size --human-readable nixpkgs#rustc
/nix/store/01rrgsg5zk3cds0xgdsq40zpk6g51dz9-ncurses-6.2-dev 386.7K 69.1M
/nix/store/0q783wnvixpqz6dxjp16nw296avgczam-libpfm-4.11.0 5.9M 37.4M
/nix/store/01rrgsg5zk3cds0xgdsq40zpk6g51dz9-ncurses-6.2-dev 386.7 KiB 69.1 MiB
/nix/store/0q783wnvixpqz6dxjp16nw296avgczam-libpfm-4.11.0 5.9 MiB 37.4 MiB
```