add subname id #20

Closed
zxq9 wants to merge 3 commits from add-subname-id into master
Showing only changes of commit 81d0daa9d5 - Show all commits

View File

@ -37,6 +37,7 @@
-define(PUB_SIZE, 32). -define(PUB_SIZE, 32).
-define(TAG_SIZE, 1). -define(TAG_SIZE, 1).
-define(SERIALIZED_SIZE, 33). %% ?TAG_SIZE + ?PUB_SIZE -define(SERIALIZED_SIZE, 33). %% ?TAG_SIZE + ?PUB_SIZE
-define(SUBNAME_SERIALIZED_SIZE, 65). %% ?TAG_SIZE + ?PUB_SIZE + ?PUB_SIZE
-define(IS_TAG(___TAG___), ___TAG___ =:= account; -define(IS_TAG(___TAG___), ___TAG___ =:= account;
___TAG___ =:= oracle; ___TAG___ =:= oracle;
@ -83,24 +84,33 @@ is_id(_) -> false.
-spec encode(id()) -> binary(). -spec encode(id()) -> binary().
encode(#id{tag = Tag, val = Val}) -> encode(#id{tag = Tag, val = Val}) ->
Res = <<(encode_tag(Tag)):?TAG_SIZE/unit:8, Val/binary>>, Res = <<(encode_tag(Tag)):?TAG_SIZE/unit:8, Val/binary>>,
true = ?SERIALIZED_SIZE =:= byte_size(Res), true = serialized_size(Tag) =:= byte_size(Res),
Res. Res.
-spec decode(binary()) -> id(). -spec decode(binary()) -> id().
decode(<<Tag:?TAG_SIZE/unit:8, Val:?PUB_SIZE/binary>>) -> decode(<<Tag:?TAG_SIZE/unit:8, Val:?PUB_SIZE/binary>>) ->
#id{ tag = decode_tag(Tag) #id{ tag = decode_tag(Tag)
, val = Val};
decode(<<SubnameTag:?TAG_SIZE/unit:8, Val:(?PUB_SIZE+?PUB_SIZE)/binary>>) ->
#id{ tag = subname = decode_tag(SubnameTag)
, val = Val}. , val = Val}.
%%%=================================================================== %%%===================================================================
%%% Internal functions %%% Internal functions
%%%=================================================================== %%%===================================================================
serialized_size(subname) -> ?SUBNAME_SERIALIZED_SIZE;
serialized_size(_) -> ?SERIALIZED_SIZE.
encode_tag(account) -> 1; encode_tag(account) -> 1;
encode_tag(name) -> 2; encode_tag(name) -> 2;
encode_tag(commitment) -> 3; encode_tag(commitment) -> 3;
encode_tag(oracle) -> 4; encode_tag(oracle) -> 4;
encode_tag(contract) -> 5; encode_tag(contract) -> 5;
encode_tag(channel) -> 6; encode_tag(channel) -> 6;
encode_tag(subname) -> 7;
encode_tag(Other) -> error({illegal_id_tag_name, Other}). encode_tag(Other) -> error({illegal_id_tag_name, Other}).
decode_tag(1) -> account; decode_tag(1) -> account;
@ -109,4 +119,5 @@ decode_tag(3) -> commitment;
decode_tag(4) -> oracle; decode_tag(4) -> oracle;
decode_tag(5) -> contract; decode_tag(5) -> contract;
decode_tag(6) -> channel; decode_tag(6) -> channel;
decode_tag(7) -> subname;
decode_tag(X) -> error({illegal_id_tag, X}). decode_tag(X) -> error({illegal_id_tag, X}).