fix codec

This commit is contained in:
anlicheng 2025-09-17 17:48:03 +08:00
parent 07d9b61ad2
commit a96bfc7da1

View File

@ -20,7 +20,6 @@
encode(PacketType, Packet) when is_integer(PacketType) ->
Bin = encode0(Packet),
<<PacketType, Bin/binary>>.
encode0(#auth_request{uuid = UUID, username = Username, salt = Salt, token = Token, timestamp = Timestamp}) ->
iolist_to_binary([
marshal(?Bytes, UUID),
@ -69,6 +68,7 @@ encode0(#event{service_id = ServiceId, event_type = EventType, params = Params})
marshal(?Bytes, Params)
]).
-spec decode(Bin :: binary()) -> any().
decode(<<PacketType:8, Packet/binary>>) ->
Fields = unmarshal(Packet),
decode0(PacketType, Fields).
@ -93,15 +93,17 @@ decode0(?MESSAGE_EVENT, [ServiceId, EventType, Params]) ->
%%% helper methods
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
marshal(?I32, Field) ->
-spec marshal(Type :: integer(), Field :: any()) -> binary().
marshal(?I32, Field) when is_integer(Field) ->
<<?I32, Field:32>>;
marshal(?Bytes, undefined) ->
<<?Bytes>>;
marshal(?Bytes, Field) ->
marshal(?Bytes, Field) when is_binary(Field) ->
Len = byte_size(Field),
<<?Bytes, Len:16, Field/binary>>.
unmarshal(Bin) ->
-spec unmarshal(Bin :: binary()) -> Components :: [any()].
unmarshal(Bin) when is_binary(Bin) ->
unmarshal(Bin, []).
unmarshal(<<>>, Acc) ->
lists:reverse(Acc);