-module(bytes). -compile([no_auto_import, nowarn_unused_vars, nowarn_unused_function, nowarn_nomatch]). -export([to_string/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 to_b(bytes()) -> float(). to_b(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 humanise(bytes()) -> bytes(). humanise(Bytes) -> B = to_b(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 ).