123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020(*****************************************************************************)(* *)(* Open Source License *)(* Copyright (c) 2018 Dynamic Ledger Solutions, Inc. <contact@tezos.com> *)(* Copyright (c) 2020 Nomadic Labs, <contact@nomadic-labs.com> *)(* *)(* Permission is hereby granted, free of charge, to any person obtaining a *)(* copy of this software and associated documentation files (the "Software"),*)(* to deal in the Software without restriction, including without limitation *)(* the rights to use, copy, modify, merge, publish, distribute, sublicense, *)(* and/or sell copies of the Software, and to permit persons to whom the *)(* Software is furnished to do so, subject to the following conditions: *)(* *)(* The above copyright notice and this permission notice shall be included *)(* in all copies or substantial portions of the Software. *)(* *)(* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR*)(* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, *)(* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL *)(* THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER*)(* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING *)(* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER *)(* DEALINGS IN THE SOFTWARE. *)(* *)(*****************************************************************************)moduleKind=structtypet=[`Fixedofint|`Dynamic|`Variable]typelength=[`Fixedofint|`Variable]typeenum=[`Dynamic|`Variable]letcombinename:t->t->t=funk1k2->match(k1,k2)with|(`Fixedn1,`Fixedn2)->`Fixed(n1+n2)|(`Dynamic,`Dynamic)|(`Fixed_,`Dynamic)|(`Dynamic,`Fixed_)->`Dynamic|(`Variable,`Fixed_)|((`Dynamic|`Fixed_),`Variable)->`Variable|(`Variable,`Dynamic)->Printf.ksprintfinvalid_arg"Cannot merge two %s when the left element is of variable length \
and the right one of dynamic length. You should use the reverse \
order, or wrap the second one with Data_encoding.dynamic_size."name|(`Variable,`Variable)->Printf.ksprintfinvalid_arg"Cannot merge two %s with variable length. You should wrap one of \
them with Data_encoding.dynamic_size."nameletmerge:t->t->t=funk1k2->match(k1,k2)with|(`Fixedn1,`Fixedn2)whenn1=n2->`Fixedn1|(`Fixed_,`Fixed_)->`Dynamic|(`Dynamic,`Dynamic)|(`Fixed_,`Dynamic)|(`Dynamic,`Fixed_)->`Dynamic|(`Variable,(`Dynamic|`Fixed_))|((`Dynamic|`Fixed_),`Variable)|(`Variable,`Variable)->`Variableletmerge_listsz:tlist->t=function|[]->assertfalse(* should be rejected by Data_encoding.union *)|k::ks->(matchList.fold_leftmergekkswith|`Fixedn->`Fixed(n+Binary_size.tag_sizesz)|k->k)endtypecase_tag=Tagofint|Json_only(* [case_tag_internal] is an optimised representation of case_tag. The
idea is to encode values of type [case_tag] to remove a level of
indirection. *)typecase_tag_internal=Uint_option.tletjson_only=Uint_option.noneletmake_tag=Uint_option.someletis_tag=Uint_option.is_someletget_tag=Uint_option.gettype'adesc=|Null:unitdesc|Empty:unitdesc|Ignore:unitdesc|Constant:string->unitdesc|Bool:booldesc|Int8:intdesc|Uint8:intdesc|Int16:intdesc|Uint16:intdesc|Int31:intdesc|Int32:Int32.tdesc|Int64:Int64.tdesc|N:Z.tdesc|Z:Z.tdesc|RangedInt:{minimum:int;maximum:int}->intdesc|RangedFloat:{minimum:float;maximum:float}->floatdesc|Float:floatdesc|Bytes:Kind.length->Bytes.tdesc|String:Kind.length->stringdesc|Padded:'at*int->'adesc|String_enum:('a,string*int)Hashtbl.t*'aarray->'adesc|Array:intoption*'at->'aarraydesc|List:intoption*'at->'alistdesc|Obj:'afield->'adesc|Objs:{kind:Kind.t;left:'at;right:'bt}->('a*'b)desc|Tup:'at->'adesc|Tups:{kind:Kind.t;left:'at;right:'bt}->('a*'b)desc|Union:{kind:Kind.t;tag_size:Binary_size.tag_size;tagged_cases:'acasearray;match_case:'a->match_result;cases:'acaselist;}->'adesc|Mu:{kind:Kind.enum;name:string;title:stringoption;description:stringoption;fix:'at->'at;}->'adesc|Conv:{proj:'a->'b;inj:'b->'a;encoding:'bt;schema:Json_schema.schemaoption;}->'adesc|Describe:{id:string;title:stringoption;description:stringoption;encoding:'at;}->'adesc|Splitted:{encoding:'at;json_encoding:'aJson_encoding.encoding;is_obj:bool;is_tup:bool;}->'adesc|Dynamic_size:{kind:Binary_size.unsigned_integer;encoding:'at;}->'adesc|Check_size:{limit:int;encoding:'at}->'adesc|Delayed:(unit->'at)->'adescand_field=|Req:{name:string;encoding:'at;title:stringoption;description:stringoption;}->'afield|Opt:{name:string;kind:Kind.enum;encoding:'at;title:stringoption;description:stringoption;}->'aoptionfield|Dft:{name:string;encoding:'at;default:'a;title:stringoption;description:stringoption;}->'afieldand'acase=|Case:{title:string;description:stringoption;encoding:'at;proj:'t->'aoption;inj:'a->'t;tag:case_tag_internal;}->'tcaseandmatch_result=Matched:int*'bt*'b->match_resultand'at={encoding:'adesc;mutablejson_encoding:'aJson_encoding.encodingoption;}type'aencoding='atletrecclassify:typea.at->Kind.t=fune->classify_desce.encodingandclassify_desc:typea.adesc->Kind.t=fune->matchewith(* Fixed *)|Null->`Fixed0|Empty->`Fixed0|Constant_->`Fixed0|Bool->`FixedBinary_size.bool|Int8->`FixedBinary_size.int8|Uint8->`FixedBinary_size.uint8|Int16->`FixedBinary_size.int16|Uint16->`FixedBinary_size.uint16|Int31->`FixedBinary_size.int31|Int32->`FixedBinary_size.int32|Int64->`FixedBinary_size.int64|N->`Dynamic|Z->`Dynamic|RangedInt{minimum;maximum}->`FixedBinary_size.(integer_to_size@@range_to_size~minimum~maximum)|Float->`FixedBinary_size.float|RangedFloat_->`FixedBinary_size.float(* Tagged *)|Byteskind->(kind:>Kind.t)|Stringkind->(kind:>Kind.t)|Padded({encoding;_},n)->(matchclassify_descencodingwith|`Fixedm->`Fixed(n+m)|_->assertfalse(* by construction (see [Fixed.padded]) *))|String_enum(_,cases)->`FixedBinary_size.(integer_to_size@@enum_sizecases)|Obj(Opt{kind;_})->(kind:>Kind.t)|Objs{kind;_}->kind|Tups{kind;_}->kind|Union{kind;_}->(kind:>Kind.t)|Mu{kind;_}->(kind:>Kind.t)(* Variable *)|Ignore->`Fixed0|Array_->`Variable|List_->`Variable(* Recursive *)|Obj(Req{encoding;_})->classifyencoding|Obj(Dft{encoding;_})->classifyencoding|Tupencoding->classifyencoding|Conv{encoding;_}->classifyencoding|Describe{encoding;_}->classifyencoding|Splitted{encoding;_}->classifyencoding|Dynamic_size_->`Dynamic|Check_size{encoding;_}->classifyencoding|Delayedf->classify(f())letmake?json_encodingencoding={encoding;json_encoding}moduleFixed=structletstringn=ifn<=0theninvalid_arg"Cannot create a string encoding of negative or null fixed length.";make@@String(`Fixedn)letbytesn=ifn<=0theninvalid_arg"Cannot create a byte encoding of negative or null fixed length.";make@@Bytes(`Fixedn)letadd_paddingen=ifn<=0theninvalid_arg"Cannot create a padding of negative or null fixed length.";matchclassifyewith|`Fixed_->make@@Padded(e,n)|_->invalid_arg"Cannot pad non-fixed size encoding"endletrecis_zeroable:typet.tencoding->bool=fune->(* Whether an encoding can ever produce zero-byte of encoding. It is dangerous
to place zero-size elements in a collection (list/array) because
they are indistinguishable from the absence of elements. *)matche.encodingwith(* trivially true *)|Null->true(* always true *)|Empty->true(* always true *)|Ignore->true(* always true *)|Constant_->true(* always true *)(* trivially false *)|Bool->false|Int8->false|Uint8->false|Int16->false|Uint16->false|Int31->false|Int32->false|Int64->false|N->false|Z->false|RangedInt_->false|RangedFloat_->false|Float->false|Bytes_->false|String_->false|Padded_->false|String_enum_->false(* true in some cases, but in practice always protected by Dynamic *)|Array_->true(* 0-element array *)|List_->true(* 0-element list *)(* represented as whatever is inside: truth mostly propagates *)|Obj(Req{encoding=e;_})->is_zeroablee(* represented as-is *)|Obj(Opt{kind=`Variable;_})->true(* optional field omitted *)|Obj(Dft{encoding=e;_})->is_zeroablee(* represented as-is *)|Obj_->false|Objs{left;right;_}->is_zeroableleft&&is_zeroableright|Tupe->is_zeroablee|Tups{left;right;_}->is_zeroableleft&&is_zeroableright|Union_->false(* includes a tag *)(* other recursive cases: truth propagates *)|Mu{kind=`Dynamic;_}->false(* size prefix *)|Mu{kind=`Variable;fix;_}->is_zeroable(fixe)|Conv{encoding;_}->is_zeroableencoding|Describe{encoding;_}->is_zeroableencoding|Splitted{encoding;_}->is_zeroableencoding|Check_size{encoding;_}->is_zeroableencoding(* Unscrutable: true by default *)|Delayedf->is_zeroable(f())(* Protected against zeroable *)|Dynamic_size_->false(* always some data for size *)moduleVariable=structletstring=make@@String`Variableletbytes=make@@Bytes`Variableletcheck_not_variablenamee=matchclassifyewith|`Variable->Printf.ksprintfinvalid_arg"Cannot insert variable length element in %s. You should wrap the \
contents using Data_encoding.dynamic_size."name|`Dynamic|`Fixed_->()letcheck_not_zeroablenamee=ifis_zeroableethenPrintf.ksprintfinvalid_arg"Cannot insert potentially zero-sized element in %s."nameelse()letarray?max_lengthe=check_not_variable"an array"e;check_not_zeroable"an array"e;letencoding=make@@Array(max_length,e)inmatch(classifye,max_length)with|(`Fixedn,Somemax_length)->letlimit=n*max_lengthinmake@@Check_size{limit;encoding}|(_,_)->encodingletlist?max_lengthe=check_not_variable"a list"e;check_not_zeroable"a list"e;letencoding=make@@List(max_length,e)inmatch(classifye,max_length)with|(`Fixedn,Somemax_length)->letlimit=n*max_lengthinmake@@Check_size{limit;encoding}|(_,_)->encodingendletdynamic_size?(kind=`Uint30)e=make@@Dynamic_size{kind;encoding=e}letcheck_sizelimitencoding=make@@Check_size{limit;encoding}letdelayedf=make@@Delayedfletnull=make@@Nullletempty=make@@Emptyletunit=make@@Ignoreletconstants=make@@Constantsletbool=make@@Boolletint8=make@@Int8letuint8=make@@Uint8letint16=make@@Int16letuint16=make@@Uint16letint31=make@@Int31letint32=make@@Int32letranged_intminimummaximum=letminimum=minminimummaximumandmaximum=maxminimummaximuminifminimum<-(1lsl30)||(1lsl30)-1<maximumtheninvalid_arg"Data_encoding.ranged_int";make@@RangedInt{minimum;maximum}letranged_floatminimummaximum=letminimum=minminimummaximumandmaximum=maxminimummaximuminmake@@RangedFloat{minimum;maximum}letint64=make@@Int64letn=make@@Nletz=make@@Zletfloat=make@@Floatletstring=dynamic_sizeVariable.stringletbytes=dynamic_sizeVariable.bytesletarray?max_lengthe=dynamic_size(Variable.array?max_lengthe)letlist?max_lengthe=dynamic_size(Variable.list?max_lengthe)letstring_enum=function|[]->invalid_arg"data_encoding.string_enum: cannot have zero cases"|[_case]->invalid_arg"data_encoding.string_enum: cannot have a single case, use constant \
instead"|_::_ascases->letarr=Array.of_list(List.mapsndcases)inlettbl=Hashtbl.create(Array.lengtharr)inList.iteri(funind(str,a)->Hashtbl.addtbla(str,ind))cases;make@@String_enum(tbl,arr)letconvprojinj?schemaencoding=make@@Conv{proj;inj;encoding;schema}letdefid?title?descriptionencoding=make@@Describe{id;title;description;encoding}letreq?title?descriptionnt=Req{name=n;encoding=t;title;description}letopt?title?descriptionnencoding=letkind=matchclassifyencodingwith|`Variable->`Variable|`Fixed_|`Dynamic->`DynamicinOpt{name=n;kind;encoding;title;description}letvaropt?title?descriptionnencoding=Opt{name=n;kind=`Variable;encoding;title;description}letdft?title?descriptionntd=Dft{name=n;encoding=t;default=d;title;description}letraw_splitted~json~binary=make@@Splitted{encoding=binary;json_encoding=json;is_obj=false;is_tup=false;}letrecis_obj:typea.at->bool=fune->matche.encodingwith|Obj_->true|Objs_(* by construction *)->true|Conv{encoding=e;_}->is_obje|Dynamic_size{encoding=e;_}->is_obje|Union{cases;_}->List.for_all(fun(Case{encoding=e;_})->is_obje)cases|Empty->true|Ignore->true|Mu{fix;_}->is_obj(fixe)|Splitted{is_obj;_}->is_obj|Delayedf->is_obj(f())|Describe{encoding;_}->is_objencoding|_->falseletrecis_tup:typea.at->bool=fune->matche.encodingwith|Tup_->true|Tups_(* by construction *)->true|Conv{encoding=e;_}->is_tupe|Dynamic_size{encoding=e;_}->is_tupe|Union{cases;_}->List.for_all(functionCase{encoding=e;_}->is_tupe)cases|Mu{fix;_}->is_tup(fixe)|Splitted{is_tup;_}->is_tup|Delayedf->is_tup(f())|Describe{encoding;_}->is_tupencoding|_->falseletraw_merge_objsleftright=letkind=Kind.combine"objects"(classifyleft)(classifyright)inmake@@Objs{kind;left;right}letobj1f1=make@@Objf1letobj2f2f1=raw_merge_objs(obj1f2)(obj1f1)letobj3f3f2f1=raw_merge_objs(obj1f3)(obj2f2f1)letobj4f4f3f2f1=raw_merge_objs(obj2f4f3)(obj2f2f1)letobj5f5f4f3f2f1=raw_merge_objs(obj1f5)(obj4f4f3f2f1)letobj6f6f5f4f3f2f1=raw_merge_objs(obj2f6f5)(obj4f4f3f2f1)letobj7f7f6f5f4f3f2f1=raw_merge_objs(obj3f7f6f5)(obj4f4f3f2f1)letobj8f8f7f6f5f4f3f2f1=raw_merge_objs(obj4f8f7f6f5)(obj4f4f3f2f1)letobj9f9f8f7f6f5f4f3f2f1=raw_merge_objs(obj1f9)(obj8f8f7f6f5f4f3f2f1)letobj10f10f9f8f7f6f5f4f3f2f1=raw_merge_objs(obj2f10f9)(obj8f8f7f6f5f4f3f2f1)letmerge_objso1o2=ifis_objo1&&is_objo2thenraw_merge_objso1o2elseinvalid_arg"Json_encoding.merge_objs"letraw_merge_tupsleftright=letkind=Kind.combine"tuples"(classifyleft)(classifyright)inmake@@Tups{kind;left;right}lettup1e1=make@@Tupe1lettup2e2e1=raw_merge_tups(tup1e2)(tup1e1)lettup3e3e2e1=raw_merge_tups(tup1e3)(tup2e2e1)lettup4e4e3e2e1=raw_merge_tups(tup2e4e3)(tup2e2e1)lettup5e5e4e3e2e1=raw_merge_tups(tup1e5)(tup4e4e3e2e1)lettup6e6e5e4e3e2e1=raw_merge_tups(tup2e6e5)(tup4e4e3e2e1)lettup7e7e6e5e4e3e2e1=raw_merge_tups(tup3e7e6e5)(tup4e4e3e2e1)lettup8e8e7e6e5e4e3e2e1=raw_merge_tups(tup4e8e7e6e5)(tup4e4e3e2e1)lettup9e9e8e7e6e5e4e3e2e1=raw_merge_tups(tup1e9)(tup8e8e7e6e5e4e3e2e1)lettup10e10e9e8e7e6e5e4e3e2e1=raw_merge_tups(tup2e10e9)(tup8e8e7e6e5e4e3e2e1)letmerge_tupst1t2=ifis_tupt1&&is_tupt2thenraw_merge_tupst1t2elseinvalid_arg"Tezos_serial.Encoding.merge_tups"letconv3ty=conv(fun(c,b,a)->(c,(b,a)))(fun(c,(b,a))->(c,b,a))tyletobj3f3f2f1=conv3(obj3f3f2f1)lettup3f3f2f1=conv3(tup3f3f2f1)letconv4ty=conv(fun(d,c,b,a)->((d,c),(b,a)))(fun((d,c),(b,a))->(d,c,b,a))tyletobj4f4f3f2f1=conv4(obj4f4f3f2f1)lettup4f4f3f2f1=conv4(tup4f4f3f2f1)letconv5ty=conv(fun(e,d,c,b,a)->(e,((d,c),(b,a))))(fun(e,((d,c),(b,a)))->(e,d,c,b,a))tyletobj5f5f4f3f2f1=conv5(obj5f5f4f3f2f1)lettup5f5f4f3f2f1=conv5(tup5f5f4f3f2f1)letconv6ty=conv(fun(f,e,d,c,b,a)->((f,e),((d,c),(b,a))))(fun((f,e),((d,c),(b,a)))->(f,e,d,c,b,a))tyletobj6f6f5f4f3f2f1=conv6(obj6f6f5f4f3f2f1)lettup6f6f5f4f3f2f1=conv6(tup6f6f5f4f3f2f1)letconv7ty=conv(fun(g,f,e,d,c,b,a)->((g,(f,e)),((d,c),(b,a))))(fun((g,(f,e)),((d,c),(b,a)))->(g,f,e,d,c,b,a))tyletobj7f7f6f5f4f3f2f1=conv7(obj7f7f6f5f4f3f2f1)lettup7f7f6f5f4f3f2f1=conv7(tup7f7f6f5f4f3f2f1)letconv8ty=conv(fun(h,g,f,e,d,c,b,a)->(((h,g),(f,e)),((d,c),(b,a))))(fun(((h,g),(f,e)),((d,c),(b,a)))->(h,g,f,e,d,c,b,a))tyletobj8f8f7f6f5f4f3f2f1=conv8(obj8f8f7f6f5f4f3f2f1)lettup8f8f7f6f5f4f3f2f1=conv8(tup8f8f7f6f5f4f3f2f1)letconv9ty=conv(fun(i,h,g,f,e,d,c,b,a)->(i,(((h,g),(f,e)),((d,c),(b,a)))))(fun(i,(((h,g),(f,e)),((d,c),(b,a))))->(i,h,g,f,e,d,c,b,a))tyletobj9f9f8f7f6f5f4f3f2f1=conv9(obj9f9f8f7f6f5f4f3f2f1)lettup9f9f8f7f6f5f4f3f2f1=conv9(tup9f9f8f7f6f5f4f3f2f1)letconv10ty=conv(fun(j,i,h,g,f,e,d,c,b,a)->((j,i),(((h,g),(f,e)),((d,c),(b,a)))))(fun((j,i),(((h,g),(f,e)),((d,c),(b,a))))->(j,i,h,g,f,e,d,c,b,a))tyletobj10f10f9f8f7f6f5f4f3f2f1=conv10(obj10f10f9f8f7f6f5f4f3f2f1)lettup10f10f9f8f7f6f5f4f3f2f1=conv10(tup10f10f9f8f7f6f5f4f3f2f1)letundefined_encoding=delayed(fun_->assertfalse)letundefined_proj_=Noneletundefined_inj_=assertfalseletundefined_case:typea.acase=Case{title="<YOU SHOULD NEVER SEE THAT>";description=None;encoding=undefined_encoding;proj=undefined_proj;inj=undefined_inj;tag=Uint_option.none;}letis_undefined_casec=c==undefined_caseletvalid_tagtag_sizet=letmax_tag=Binary_size.max_inttag_sizeinift>max_tagthenFormat.kasprintfinvalid_arg"The tag %d is invalid because it should be less than %d."tmax_tagletmatching?(tag_size=`Uint8)match_casecases=ifcases=[]theninvalid_arg"Data_encoding.union: empty list of cases.";lettagged_cases_list=List.filter(fun(Case{tag;_})->is_tagtag&&(valid_tagtag_size(get_tagtag);true))casesin(* In [tagged_cases_list] all tags are [some] so [get] cannot fail *)letmax_used_tag=List.fold_left(funm(Case{tag;_})->max(Uint_option.gettag)m)(-1)tagged_cases_listinlettagged_cases=Array.make(max_used_tag+1)undefined_caseinList.iter(fun(Case{tag;_}ascase)->lettag=Uint_option.gettaginifnot(is_undefined_casetagged_cases.(tag))thenFormat.kasprintfinvalid_arg"The tag %d appears twice in an union."tag;tagged_cases.(tag)<-case)tagged_cases_list;letclassify_case(Case{encoding;_})=classifyencodinginletkinds=List.mapclassify_casecasesinletkind=Kind.merge_listtag_sizekindsinmake@@Union{kind;tag_size;tagged_cases;match_case;cases}letunion?(tag_size=`Uint8)cases=letmatch_case=letacases=Array.of_list@@List.filter(fun(Case{tag;_})->is_tagtag)casesinfunx->letrecfindi=ifi>=Array.lengthacasesthenraiseBinary_error_types.(Write_errorNo_case_matched)elselet(Case{tag;encoding;proj;_})=acases.(i)inmatchprojxwith|None->find(i+1)|Somev->(* By definition of [acases], the following [get] cannot fail. *)Matched(Uint_option.gettag,encoding,v)infind0inmatching~tag_sizematch_casecasesletcase~title?descriptiontagencodingprojinj=lettag=matchtagwith|Tagt->ift<0thenraise(Invalid_argument"Data_encoding.tag: negative tag")elsemake_tagt|Json_only->json_onlyinCase{title;description;encoding;proj;inj;tag}letmatched?(tag_size:[`Uint8|`Uint16]=`Uint8)tagencodingv=iftag<0thenraise(Invalid_argument"Data_encoding.matched: negative tag");valid_tagtag_sizetag;Matched(tag,encoding,v)letrecis_nullable:typet.tencoding->bool=fune->matche.encodingwith|Null->true|Empty->false|Ignore->true|Constant_->false|Bool->false|Int8->false|Uint8->false|Int16->false|Uint16->false|Int31->false|Int32->false|Int64->false|N->false|Z->false|RangedInt_->false|RangedFloat_->false|Float->false|Bytes_->false|String_->false|Padded(e,_)->is_nullablee|String_enum_->false|Array_->false|List_->false|Obj_->false|Objs_->false|Tup_->false|Tups_->false|Union{cases;_}->List.exists(fun(Case{encoding=e;_})->is_nullablee)cases|Mu{fix;_}->is_nullable(fixe)|Conv{encoding=e;_}->is_nullablee|Describe{encoding=e;_}->is_nullablee|Splitted{json_encoding;_}->Json_encoding.is_nullablejson_encoding|Dynamic_size{encoding=e;_}->is_nullablee|Check_size{encoding=e;_}->is_nullablee|Delayed_->trueletoptionty=ifis_nullabletytheninvalid_arg"Data_encoding.option: cannot nest nullable encodings";(* TODO add a special construct `Option` in the GADT *)union~tag_size:`Uint8[case(Tag1)ty~title:"Some"(funx->x)(funx->Somex);case(Tag0)null~title:"None"(functionNone->Some()|Some_->None)(fun()->None);]letmuname?title?descriptionfix=(* The latest application of [fix] is memoized to avoid recomputing
it each time a value encoded by [mu] is processed. [fix] may
sometimes be applied to distinct arguments if the encoding is used
in different contexts. Hence, we remember the last input of [fix]
in the closure, so that we can recompute [fix] if this argument
has changed.
This partial memoization only takes a bounded amount of memory
and is useful because in practice we decode many values before
applying [fix] to a new argument. *)letself=refNoneinletfix_f=fixinletfixe=match!selfwith|Some(e0,e')whene==e0->e'|_->lete'=fix_feinself:=Some(e,e');e'in(* Attempt to determine kind. Note that this can results in memoisation
misses: the [fix] function might be called multiple times. *)tryletprecursor=make@@Mu{kind=`Dynamic;name;title;description;fix}inletfixed_precursor=fixprecursorinmatchclassify@@fixed_precursorwith|`Fixed_|`Dynamic->fixed_precursor|`Variable->raiseExitwithExit|_(* TODO variability error *)->letprecursor=make@@Mu{kind=`Variable;name;title;description;fix}inletfixed_precursor=fixprecursorinignore(classifyfixed_precursor);fixed_precursorletresultok_encerror_enc=union~tag_size:`Uint8[case(Tag1)(obj1(req"ok"ok_enc))~title:"Ok"(functionOkx->Somex|Error_->None)(funx->Okx);case(Tag0)(obj1(req"error"error_enc))~title:"Result"(functionOk_->None|Errorx->Somex)(funx->Errorx);]