Fix type-driven encode, more docs
Gajumaru Serialization Tests / tests (push) Successful in 48m53s

This commit is contained in:
Ulf Wiger
2025-04-05 21:44:36 +02:00
parent 3ede4f22e1
commit dd1c2455f0
2 changed files with 102 additions and 53 deletions
+18 -7
View File
@@ -29,6 +29,10 @@ Main API:
* `serialize_typed(template(), term()) -> binary()`
* `deserialize(binary()) -> term()`
In the examples below, we use the `decode` functions, to illustrate
how the type information is represented. The fully serialized form is
produced by the `serialize` functions.
The basic types supported by the encoder are:
* `non_neg_integer()` (`int` , code: 248)
* `binary()` (`binary`, code: 249)
@@ -88,16 +92,23 @@ Template-driven encoding
----
Templates can be provided to the encoder by either naming an already registered
type, or by passing a template directly. The template will then be enforced, and
used to slightly compress the encoding.
type, or by passing a template directly. In both cases, the encoder will enforce
the type information in the template.
In the following example, as the encoder knows that `{11,12}` is encoded as a
tuple of two integers, it can omit the inner type tags.
If the template has been registered, the encoder omits inner type tags (still
inserting the top-level tag), leading to some compression of the output.
This also means that the serialized term cannot be decoded without the same
schema information on the decoder side.
In the case of a directly provided template, all type information is inserted,
such that the serialized term can be decoded without any added type information.
The template types are still enforced during encoding.
```erlang
ET = fun(Type,Term) -> io:fwrite("~w~n", [gmser_dyn:encode_typed(Type,Term)]) end.
ET({int,int}, {11,12}) ->[<<0>>,<<1>>,[<<253>>,[<<11>>,<<12>>]]]
ET({int,int}, {11,a}) ->
** exception error: {illegal,int,a} ...
ET([{int,int}], [{1,2}]) -> [<<0>>,<<1>>,[<<251>>,[[[<<248>>,<<1>>],[<<248>>,<<2>>]]]]]
gmser_dyn:register_type(1000,lt2i,[{int,int}]).
ET(lt2i, [{1,2}]) -> [<<0>>,<<1>>,[<<3,232>>,[[<<1>>,<<2>>]]]]
```