diff --git a/src/eavro_codec.erl b/src/eavro_codec.erl index 2c23a62..f739242 100644 --- a/src/eavro_codec.erl +++ b/src/eavro_codec.erl @@ -14,6 +14,8 @@ -define(echo(V), io:format("~p~n",[V])). + + %% primitives encode(int, Int) -> Z = zigzag_encode(int, Int), @@ -33,9 +35,21 @@ encode(boolean, true) -> <<1>>; encode(boolean, false) -> <<0>>; encode(null, _Any) -> <<>>; + + %% complex data types encode(#avro_record{fields = Fields}, Data) -> - [encode(Type, Value) || {{_Name, Type}, Value} <- lists:zip(Fields, Data)]; + case Data of + [[_|_]|_]-> + %unpack deep lists + FieldDataList=[{#avro_record{fields=Fields},X} || X <-Data], + [encode(Type, Value) || {Type, Value} <- FieldDataList]; + _ -> + [encode(Type, Value) || {{_Name, Type}, Value} <- lists:zip(Fields, Data)] + end; + + + encode(#avro_enum{symbols = Symbols}, Data) -> ZeroBasedIndex = index_of(Data, Symbols) - 1, encode(int,ZeroBasedIndex); @@ -53,14 +67,20 @@ encode(#avro_array{ items = Type }, Data) when is_list(Data) -> encode_blocks(Type, Data, fun encode/2); encode(Union, {Type, Data}) when is_list(Union) -> try - I = index_of(Type, Union) - 1, + I = index_of(Type, Union) - 1, [encode(long, I), encode(Type, Data)] catch _:not_found -> exit({union_mismatch, Union, Type}) end. encode_blocks(Type, Data, Encoder) when is_list(Data) -> - Count = length(Data), + case Data of + [[_|_]|_]-> + [DeepList]=Data, + Count=length(DeepList); + _-> + Count = length(Data) + end, if Count == 0 -> <<0>>; true -> [encode(long, Count), @@ -69,6 +89,7 @@ encode_blocks(Type, Data, Encoder) when is_list(Data) -> end. + index_of(Item, List) -> index_of(Item, List, 1). index_of(_, [], _) -> exit(not_found);