Inverse function to humanize_size?

:information_source: Attention Topic was automatically imported from the old Question2Answer platform.
:bust_in_silhouette: Asked By monnef

Is there an inverse function to humanize_size?

var bytes = 133790307
var size = String.humanize_size(bytes)
print(size) # prints "127.5 MiB"

^ from docs. I am looking for a similar function which reverses the first one. Something like this:

String.dehumanize_size("127.5 MiB") # 133790307

As far as I know there isn’t yet to reverse the result of humanize_size

sarapan_malam | 2022-09-13 15:48

:bust_in_silhouette: Reply From: skysphr

Precision of the data will be inevitably lost, but reversing this code would yield in a function such as

func robotize_size(size: String) -> int:
    var suffixes = {
        "KiB": 1 << 10,
        "MiB": 1 << 20,
        "GiB": 1 << 30,
        "TiB": 1 << 40,
        "PiB": 1 << 50,
        "EiB": 1 << 60,
        "B": 1 # this muse be checked last
    }
    
    for suffix in suffixes:
        if not size.ends_with(suffix):
            continue
        var value = size.trim_suffix(suffix)
        if not value.strip_edges().is_valid_float():
            # String invalid
            return -1
        return int(value.to_float() * suffixes[suffix])

    # String does not contain any prefix
    return -1

Seems to be working fine. suffixes could be moved as const outside the function to optimize it a bit, so it’s not constructed every function call.

monnef | 2022-09-15 17:13