-module(glethers@address). -compile([no_auto_import, nowarn_unused_vars, nowarn_unused_function, nowarn_nomatch]). -export([from_string/1, decoder/1, to_string/1, to_bit_array/1]). -export_type([address/0, decode_error/0]). -opaque address() :: {address, binary()}. -type decode_error() :: not_enough_bytes | non_hex_decimal | incorrect_length. -spec is_hex_char(binary()) -> boolean(). is_hex_char(Char) -> case Char of <<"0"/utf8>> -> true; <<"1"/utf8>> -> true; <<"2"/utf8>> -> true; <<"3"/utf8>> -> true; <<"4"/utf8>> -> true; <<"5"/utf8>> -> true; <<"6"/utf8>> -> true; <<"7"/utf8>> -> true; <<"8"/utf8>> -> true; <<"9"/utf8>> -> true; <<"a"/utf8>> -> true; <<"b"/utf8>> -> true; <<"c"/utf8>> -> true; <<"d"/utf8>> -> true; <<"e"/utf8>> -> true; <<"f"/utf8>> -> true; <<"A"/utf8>> -> true; <<"B"/utf8>> -> true; <<"C"/utf8>> -> true; <<"D"/utf8>> -> true; <<"E"/utf8>> -> true; <<"F"/utf8>> -> true; _ -> false end. -spec from_string(binary()) -> {ok, address()} | {error, decode_error()}. from_string(Addr) -> Address = case Addr of <<"0x"/utf8, Value/binary>> -> Value; Other -> Other end, gleam@bool:guard( begin _pipe = Address, gleam@string:length(_pipe) end /= 40, {error, incorrect_length}, fun() -> gleam@bool:guard( begin _pipe@1 = Address, _pipe@2 = gleam@string:to_graphemes(_pipe@1), _pipe@3 = gleam@list:map(_pipe@2, fun is_hex_char/1), gleam@list:any(_pipe@3, fun(Is_hex) -> not Is_hex end) end, {error, non_hex_decimal}, fun() -> {ok, {address, Address}} end ) end ). -spec decoder(gleam@dynamic:dynamic_()) -> {ok, address()} | {error, list(gleam@dynamic:decode_error())}. decoder(Value) -> gleam@result:'try'( (gleam@dynamic:element(1, fun gleam@dynamic:string/1))(Value), fun(Str) -> _pipe = from_string(Str), gleam@result:map_error(_pipe, fun(_) -> [] end) end ). -spec to_string(address()) -> binary(). to_string(Address) -> {address, Addr} = Address, <<"0x"/utf8, Addr/binary>>. -spec to_bit_array(address()) -> bitstring(). to_bit_array(Address) -> {address, Addr} = Address, _assert_subject = begin _pipe = Addr, gleam_stdlib:base16_decode(_pipe) end, {ok, Bytes} = case _assert_subject of {ok, _} -> _assert_subject; _assert_fail -> erlang:error(#{gleam_error => let_assert, message => <<"Assertion pattern match failed"/utf8>>, value => _assert_fail, module => <<"glethers/address"/utf8>>, function => <<"to_bit_array"/utf8>>, line => 83}) end, <<0:96, Bytes/bitstring>>.