Current section
Files
Jump to
Current section
Files
src/humanise@bytes.erl
-module(humanise@bytes).
-compile([no_auto_import, nowarn_unused_vars, nowarn_unused_function, nowarn_nomatch]).
-export([to_string/1, as_bytes/1, as_kilobytes/1, as_megabytes/1, as_gigabytes/1, as_terabytes/1, humanise/1]).
-export_type([bytes/0]).
-type bytes() :: {bytes, float()} |
{kilobytes, float()} |
{megabytes, float()} |
{gigabytes, float()} |
{terabytes, float()}.
-spec to_string(bytes()) -> binary().
to_string(Bytes) ->
{N@5, Suffix} = case Bytes of
{bytes, N} ->
{N, <<"B"/utf8>>};
{kilobytes, N@1} ->
{N@1, <<"KB"/utf8>>};
{megabytes, N@2} ->
{N@2, <<"MB"/utf8>>};
{gigabytes, N@3} ->
{N@3, <<"GB"/utf8>>};
{terabytes, N@4} ->
{N@4, <<"TB"/utf8>>}
end,
util:format(N@5, Suffix).
-spec as_bytes(bytes()) -> float().
as_bytes(Bytes) ->
case Bytes of
{bytes, N} ->
N;
{kilobytes, N@1} ->
N@1 * 1000.0;
{megabytes, N@2} ->
N@2 * 1000000.0;
{gigabytes, N@3} ->
N@3 * 1000000000.0;
{terabytes, N@4} ->
N@4 * 1000000000000.0
end.
-spec as_kilobytes(bytes()) -> float().
as_kilobytes(Bytes) ->
case 1000.0 of
+0.0 -> +0.0;
-0.0 -> -0.0;
Gleam@denominator -> as_bytes(Bytes) / Gleam@denominator
end.
-spec as_megabytes(bytes()) -> float().
as_megabytes(Bytes) ->
case 1000000.0 of
+0.0 -> +0.0;
-0.0 -> -0.0;
Gleam@denominator -> as_bytes(Bytes) / Gleam@denominator
end.
-spec as_gigabytes(bytes()) -> float().
as_gigabytes(Bytes) ->
case 1000000000.0 of
+0.0 -> +0.0;
-0.0 -> -0.0;
Gleam@denominator -> as_bytes(Bytes) / Gleam@denominator
end.
-spec as_terabytes(bytes()) -> float().
as_terabytes(Bytes) ->
case 1000000000000.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 < 1000.0,
{bytes, B},
fun() -> gleam@bool:guard(B < 1000000.0, {kilobytes, case 1000.0 of
+0.0 -> +0.0;
-0.0 -> -0.0;
Gleam@denominator -> B / Gleam@denominator
end}, fun() ->
gleam@bool:guard(
B < 1000000000.0,
{megabytes, case 1000000.0 of
+0.0 -> +0.0;
-0.0 -> -0.0;
Gleam@denominator@1 -> B / Gleam@denominator@1
end},
fun() ->
gleam@bool:guard(
B < 1000000000000.0,
{gigabytes, case 1000000000.0 of
+0.0 -> +0.0;
-0.0 -> -0.0;
Gleam@denominator@2 -> B / Gleam@denominator@2
end},
fun() -> {terabytes, case 1000000000000.0 of
+0.0 -> +0.0;
-0.0 -> -0.0;
Gleam@denominator@3 -> B / Gleam@denominator@3
end} end
)
end
)
end) end
).