Current section

Files

Jump to
humanise src humanise@bytes1024.erl
Raw

src/humanise@bytes1024.erl

-module(humanise@bytes1024).
-compile([no_auto_import, nowarn_unused_vars, nowarn_unused_function, nowarn_nomatch]).
-export([to_string/1, as_bytes/1, as_kibibytes/1, as_mebibytes/1, as_gibibytes/1, as_tebibytes/1, humanise/1]).
-export_type([bytes/0]).
-type bytes() :: {bytes, float()} |
{kibibytes, float()} |
{mebibytes, float()} |
{gibibytes, float()} |
{tebibytes, float()}.
-spec to_string(bytes()) -> binary().
to_string(Bytes) ->
{N@5, Suffix} = case Bytes of
{bytes, N} ->
{N, <<"B"/utf8>>};
{kibibytes, N@1} ->
{N@1, <<"KiB"/utf8>>};
{mebibytes, N@2} ->
{N@2, <<"MiB"/utf8>>};
{gibibytes, N@3} ->
{N@3, <<"GiB"/utf8>>};
{tebibytes, N@4} ->
{N@4, <<"TiB"/utf8>>}
end,
util:format(N@5, Suffix).
-spec as_bytes(bytes()) -> float().
as_bytes(Bytes) ->
case Bytes of
{bytes, N} ->
N;
{kibibytes, N@1} ->
N@1 * 1024.0;
{mebibytes, N@2} ->
N@2 * 1048576.0;
{gibibytes, N@3} ->
N@3 * 1073741824.0;
{tebibytes, N@4} ->
N@4 * 1099511627776.0
end.
-spec as_kibibytes(bytes()) -> float().
as_kibibytes(Bytes) ->
case 1024.0 of
+0.0 -> +0.0;
-0.0 -> -0.0;
Gleam@denominator -> as_bytes(Bytes) / Gleam@denominator
end.
-spec as_mebibytes(bytes()) -> float().
as_mebibytes(Bytes) ->
case 1048576.0 of
+0.0 -> +0.0;
-0.0 -> -0.0;
Gleam@denominator -> as_bytes(Bytes) / Gleam@denominator
end.
-spec as_gibibytes(bytes()) -> float().
as_gibibytes(Bytes) ->
case 1073741824.0 of
+0.0 -> +0.0;
-0.0 -> -0.0;
Gleam@denominator -> as_bytes(Bytes) / Gleam@denominator
end.
-spec as_tebibytes(bytes()) -> float().
as_tebibytes(Bytes) ->
case 1099511627776.0 of
+0.0 -> +0.0;
-0.0 -> -0.0;
Gleam@denominator -> as_bytes(Bytes) / Gleam@denominator
end.
-spec humanise(bytes()) -> bytes().
humanise(Bytes) ->
B = as_bytes(Bytes),
gleam@bool:guard(
B < 1024.0,
{bytes, B},
fun() -> gleam@bool:guard(B < 1048576.0, {kibibytes, case 1024.0 of
+0.0 -> +0.0;
-0.0 -> -0.0;
Gleam@denominator -> B / Gleam@denominator
end}, fun() ->
gleam@bool:guard(
B < 1073741824.0,
{mebibytes, case 1048576.0 of
+0.0 -> +0.0;
-0.0 -> -0.0;
Gleam@denominator@1 -> B / Gleam@denominator@1
end},
fun() ->
gleam@bool:guard(
B < 1099511627776.0,
{gibibytes, case 1073741824.0 of
+0.0 -> +0.0;
-0.0 -> -0.0;
Gleam@denominator@2 -> B / Gleam@denominator@2
end},
fun() -> {tebibytes, case 1099511627776.0 of
+0.0 -> +0.0;
-0.0 -> -0.0;
Gleam@denominator@3 -> B / Gleam@denominator@3
end} end
)
end
)
end) end
).