1
0

mpack.h 255 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207
  1. /**
  2. * The MIT License (MIT)
  3. *
  4. * Copyright (c) 2015-2021 Nicholas Fraser and the MPack authors
  5. *
  6. * Permission is hereby granted, free of charge, to any person obtaining a copy
  7. * of this software and associated documentation files (the "Software"), to deal
  8. * in the Software without restriction, including without limitation the rights
  9. * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  10. * copies of the Software, and to permit persons to whom the Software is
  11. * furnished to do so, subject to the following conditions:
  12. *
  13. * The above copyright notice and this permission notice shall be included in all
  14. * copies or substantial portions of the Software.
  15. *
  16. * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  17. * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  18. * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  19. * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  20. * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  21. * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
  22. * SOFTWARE.
  23. *
  24. */
  25. /*
  26. * This is the MPack 1.1.1 amalgamation package.
  27. *
  28. * http://github.com/ludocode/mpack
  29. */
  30. #ifndef MPACK_H
  31. #define MPACK_H 1
  32. #define MPACK_AMALGAMATED 1
  33. #define MPACK_RELEASE_VERSION 1
  34. #if defined(MPACK_HAS_CONFIG) && MPACK_HAS_CONFIG
  35. #include "mpack-config.h"
  36. #endif
  37. /* mpack/mpack-platform.h.h */
  38. /**
  39. * @file
  40. *
  41. * Abstracts all platform-specific code from MPack and handles configuration
  42. * options.
  43. *
  44. * This verifies the configuration and sets defaults based on the platform,
  45. * contains implementations of standard C functions when libc is not available,
  46. * and provides wrappers to all library functions.
  47. *
  48. * Documentation for configuration options is available here:
  49. *
  50. * https://ludocode.github.io/mpack/group__config.html
  51. */
  52. #ifndef MPACK_PLATFORM_H
  53. #define MPACK_PLATFORM_H 1
  54. /**
  55. * @defgroup config Configuration Options
  56. *
  57. * Defines the MPack configuration options.
  58. *
  59. * Custom configuration of MPack is not usually necessary. In almost all
  60. * cases you can ignore this and use the defaults.
  61. *
  62. * If you do want to configure MPack, you can define the below options as part
  63. * of your build system or project settings. This will override the below
  64. * defaults.
  65. *
  66. * If you'd like to use a file for configuration instead, define
  67. * @ref MPACK_HAS_CONFIG to 1 in your build system or project settings.
  68. * This will cause MPack to include a file you create called @c mpack-config.h
  69. * in which you can define your configuration. This is useful if you need to
  70. * include specific headers (such as a custom allocator) in order to configure
  71. * MPack to use it.
  72. *
  73. * @warning The value of all configuration options must be the same in
  74. * all translation units of your project, as well as in the mpack source
  75. * itself. These configuration options affect the layout of structs, among
  76. * other things, which cannot be different in source files that are linked
  77. * together.
  78. *
  79. * @note MPack does not contain defaults for building inside the Linux kernel.
  80. * There is a <a href="https://github.com/ludocode/mpack-linux-kernel">
  81. * configuration file for the Linux kernel</a> that can be used instead.
  82. *
  83. * @{
  84. */
  85. /*
  86. * Pre-include checks
  87. *
  88. * These need to come before the user's mpack-config.h because they might be
  89. * including headers in it.
  90. */
  91. /** @cond */
  92. #if defined(_MSC_VER) && _MSC_VER < 1800 && !defined(__cplusplus)
  93. #error "In Visual Studio 2012 and earlier, MPack must be compiled as C++. Enable the /Tp compiler flag."
  94. #endif
  95. #if defined(_WIN32) && MPACK_INTERNAL
  96. #define _CRT_SECURE_NO_WARNINGS 1
  97. #endif
  98. #ifndef __STDC_LIMIT_MACROS
  99. #define __STDC_LIMIT_MACROS 1
  100. #endif
  101. #ifndef __STDC_FORMAT_MACROS
  102. #define __STDC_FORMAT_MACROS 1
  103. #endif
  104. #ifndef __STDC_CONSTANT_MACROS
  105. #define __STDC_CONSTANT_MACROS 1
  106. #endif
  107. /** @endcond */
  108. /**
  109. * @name File Configuration
  110. * @{
  111. */
  112. /**
  113. * @def MPACK_HAS_CONFIG
  114. *
  115. * Causes MPack to include a file you create called @c mpack-config.h .
  116. *
  117. * The file is included before MPack sets any defaults for undefined
  118. * configuration options. You can use it to configure MPack.
  119. *
  120. * This is off by default.
  121. */
  122. #if defined(MPACK_HAS_CONFIG)
  123. #if MPACK_HAS_CONFIG
  124. #include "mpack-config.h"
  125. #endif
  126. #else
  127. #define MPACK_HAS_CONFIG 0
  128. #endif
  129. /**
  130. * @}
  131. */
  132. // this needs to come first since some stuff depends on it
  133. /** @cond */
  134. #ifndef MPACK_NO_BUILTINS
  135. #define MPACK_NO_BUILTINS 0
  136. #endif
  137. /** @endcond */
  138. /**
  139. * @name Features
  140. * @{
  141. */
  142. /**
  143. * @def MPACK_READER
  144. *
  145. * Enables compilation of the base Tag Reader.
  146. */
  147. #ifndef MPACK_READER
  148. #define MPACK_READER 1
  149. #endif
  150. /**
  151. * @def MPACK_EXPECT
  152. *
  153. * Enables compilation of the static Expect API.
  154. */
  155. #ifndef MPACK_EXPECT
  156. #define MPACK_EXPECT 1
  157. #endif
  158. /**
  159. * @def MPACK_NODE
  160. *
  161. * Enables compilation of the dynamic Node API.
  162. */
  163. #ifndef MPACK_NODE
  164. #define MPACK_NODE 1
  165. #endif
  166. /**
  167. * @def MPACK_WRITER
  168. *
  169. * Enables compilation of the Writer.
  170. */
  171. #ifndef MPACK_WRITER
  172. #define MPACK_WRITER 1
  173. #endif
  174. /**
  175. * @def MPACK_BUILDER
  176. *
  177. * Enables compilation of the Builder.
  178. *
  179. * The Builder API provides additional functions to the Writer for
  180. * automatically determining the element count of compound elements so you do
  181. * not have to specify them up-front.
  182. *
  183. * This requires a @c malloc(). It is enabled by default if MPACK_WRITER is
  184. * enabled and MPACK_MALLOC is defined.
  185. *
  186. * @see mpack_build_map()
  187. * @see mpack_build_array()
  188. * @see mpack_complete_map()
  189. * @see mpack_complete_array()
  190. */
  191. // This is defined furthur below after we've resolved whether we have malloc().
  192. /**
  193. * @def MPACK_COMPATIBILITY
  194. *
  195. * Enables compatibility features for reading and writing older
  196. * versions of MessagePack.
  197. *
  198. * This is disabled by default. When disabled, the behaviour is equivalent to
  199. * using the default version, @ref mpack_version_current.
  200. *
  201. * Enable this if you need to interoperate with applications or data that do
  202. * not support the new (v5) MessagePack spec. See the section on v4
  203. * compatibility in @ref docs/protocol.md for more information.
  204. */
  205. #ifndef MPACK_COMPATIBILITY
  206. #define MPACK_COMPATIBILITY 0
  207. #endif
  208. /**
  209. * @def MPACK_EXTENSIONS
  210. *
  211. * Enables the use of extension types.
  212. *
  213. * This is disabled by default. Define it to 1 to enable it. If disabled,
  214. * functions to read and write extensions will not exist, and any occurrence of
  215. * extension types in parsed messages will flag @ref mpack_error_invalid.
  216. *
  217. * MPack discourages the use of extension types. See the section on extension
  218. * types in @ref docs/protocol.md for more information.
  219. */
  220. #ifndef MPACK_EXTENSIONS
  221. #define MPACK_EXTENSIONS 0
  222. #endif
  223. /**
  224. * @}
  225. */
  226. // workarounds for Doxygen
  227. #if defined(MPACK_DOXYGEN)
  228. #if MPACK_DOXYGEN
  229. // We give these their default values of 0 here even though they are defined to
  230. // 1 in the doxyfile. Doxygen will show this as the value in the docs, even
  231. // though it ignores it when parsing the rest of the source. This is what we
  232. // want, since we want the documentation to show these defaults but still
  233. // generate documentation for the functions they add when they're on.
  234. #define MPACK_COMPATIBILITY 0
  235. #define MPACK_EXTENSIONS 0
  236. #endif
  237. #endif
  238. /**
  239. * @name Dependencies
  240. * @{
  241. */
  242. /**
  243. * @def MPACK_CONFORMING
  244. *
  245. * Enables the inclusion of basic C headers to define standard types and
  246. * macros.
  247. *
  248. * This causes MPack to include headers required for conforming implementations
  249. * of C99 even in freestanding, in particular <stddef.h>, <stdint.h>,
  250. * <stdbool.h> and <limits.h>. It also includes <inttypes.h>; this is
  251. * technically not required for freestanding but MPack needs it to detect
  252. * integer limits.
  253. *
  254. * You can disable this if these headers are unavailable or if they do not
  255. * define the standard types and macros (for example inside the Linux kernel.)
  256. * If this is disabled, MPack will include no headers and will assume a 32-bit
  257. * int. You will probably also want to define @ref MPACK_HAS_CONFIG to 1 and
  258. * include your own headers in the config file. You must provide definitions
  259. * for standard types such as @c size_t, @c bool, @c int32_t and so on.
  260. *
  261. * @see <a href="https://en.cppreference.com/w/c/language/conformance">
  262. * cppreference.com documentation on Conformance</a>
  263. */
  264. #ifndef MPACK_CONFORMING
  265. #define MPACK_CONFORMING 1
  266. #endif
  267. /**
  268. * @def MPACK_STDLIB
  269. *
  270. * Enables the use of the C stdlib.
  271. *
  272. * This allows the library to use basic functions like @c memcmp() and @c
  273. * strlen(), as well as @c malloc() for debugging and in allocation helpers.
  274. *
  275. * If this is disabled, allocation helper functions will not be defined, and
  276. * MPack will attempt to detect compiler intrinsics for functions like @c
  277. * memcmp() (assuming @ref MPACK_NO_BUILTINS is not set.) It will fallback to
  278. * its own (slow) implementations if it cannot use builtins. You may want to
  279. * define @ref MPACK_MEMCMP and friends if you disable this.
  280. *
  281. * @see MPACK_MEMCMP
  282. * @see MPACK_MEMCPY
  283. * @see MPACK_MEMMOVE
  284. * @see MPACK_MEMSET
  285. * @see MPACK_STRLEN
  286. * @see MPACK_MALLOC
  287. * @see MPACK_REALLOC
  288. * @see MPACK_FREE
  289. */
  290. #ifndef MPACK_STDLIB
  291. #if !MPACK_CONFORMING
  292. // If we don't even have a proper <limits.h> we assume we won't have
  293. // malloc() either.
  294. #define MPACK_STDLIB 0
  295. #else
  296. #define MPACK_STDLIB 1
  297. #endif
  298. #endif
  299. /**
  300. * @def MPACK_STDIO
  301. *
  302. * Enables the use of C stdio. This adds helpers for easily
  303. * reading/writing C files and makes debugging easier.
  304. */
  305. #ifndef MPACK_STDIO
  306. #if !MPACK_STDLIB || defined(__AVR__)
  307. #define MPACK_STDIO 0
  308. #else
  309. #define MPACK_STDIO 1
  310. #endif
  311. #endif
  312. /**
  313. * Whether the 'float' type and floating point operations are supported.
  314. *
  315. * If @ref MPACK_FLOAT is disabled, floats are read and written as @c uint32_t
  316. * instead. This way messages with floats do not result in errors and you can
  317. * still perform manual float parsing yourself.
  318. */
  319. #ifndef MPACK_FLOAT
  320. #define MPACK_FLOAT 1
  321. #endif
  322. /**
  323. * Whether the 'double' type is supported. This requires support for 'float'.
  324. *
  325. * If @ref MPACK_DOUBLE is disabled, doubles are read and written as @c
  326. * uint32_t instead. This way messages with doubles do not result in errors and
  327. * you can still perform manual doubles parsing yourself.
  328. *
  329. * If @ref MPACK_FLOAT is enabled but @ref MPACK_DOUBLE is not, doubles can be
  330. * read as floats using the shortening conversion functions, e.g. @ref
  331. * mpack_expect_float() or @ref mpack_node_float().
  332. */
  333. #ifndef MPACK_DOUBLE
  334. #if !MPACK_FLOAT || defined(__AVR__)
  335. // AVR supports only float, not double.
  336. #define MPACK_DOUBLE 0
  337. #else
  338. #define MPACK_DOUBLE 1
  339. #endif
  340. #endif
  341. /**
  342. * @}
  343. */
  344. /**
  345. * @name Allocation Functions
  346. * @{
  347. */
  348. /**
  349. * @def MPACK_MALLOC
  350. *
  351. * Defines the memory allocation function used by MPack. This is used by
  352. * helpers for automatically allocating data the correct size, and for
  353. * debugging functions. If this macro is undefined, the allocation helpers
  354. * will not be compiled.
  355. *
  356. * Set this to use a custom @c malloc() function. Your function must have the
  357. * signature:
  358. *
  359. * @code
  360. * void* malloc(size_t size);
  361. * @endcode
  362. *
  363. * The default is @c malloc() if @ref MPACK_STDLIB is enabled.
  364. */
  365. /**
  366. * @def MPACK_FREE
  367. *
  368. * Defines the memory free function used by MPack. This is used by helpers
  369. * for automatically allocating data the correct size. If this macro is
  370. * undefined, the allocation helpers will not be compiled.
  371. *
  372. * Set this to use a custom @c free() function. Your function must have the
  373. * signature:
  374. *
  375. * @code
  376. * void free(void* p);
  377. * @endcode
  378. *
  379. * The default is @c free() if @ref MPACK_MALLOC has not been customized and
  380. * @ref MPACK_STDLIB is enabled.
  381. */
  382. /**
  383. * @def MPACK_REALLOC
  384. *
  385. * Defines the realloc function used by MPack. It is used by growable
  386. * buffers to resize more efficiently.
  387. *
  388. * The default is @c realloc() if @ref MPACK_MALLOC has not been customized and
  389. * @ref MPACK_STDLIB is enabled.
  390. *
  391. * Set this to use a custom @c realloc() function. Your function must have the
  392. * signature:
  393. *
  394. * @code
  395. * void* realloc(void* p, size_t new_size);
  396. * @endcode
  397. *
  398. * This is optional, even when @ref MPACK_MALLOC is used. If @ref MPACK_MALLOC is
  399. * set and @ref MPACK_REALLOC is not, @ref MPACK_MALLOC is used with a simple copy
  400. * to grow buffers.
  401. */
  402. #if defined(MPACK_MALLOC) && !defined(MPACK_FREE)
  403. #error "MPACK_MALLOC requires MPACK_FREE."
  404. #endif
  405. #if !defined(MPACK_MALLOC) && defined(MPACK_FREE)
  406. #error "MPACK_FREE requires MPACK_MALLOC."
  407. #endif
  408. // These were never configurable in lowercase but we check anyway.
  409. #ifdef mpack_malloc
  410. #error "Define MPACK_MALLOC, not mpack_malloc."
  411. #endif
  412. #ifdef mpack_realloc
  413. #error "Define MPACK_REALLOC, not mpack_realloc."
  414. #endif
  415. #ifdef mpack_free
  416. #error "Define MPACK_FREE, not mpack_free."
  417. #endif
  418. // We don't use calloc() at all.
  419. #ifdef MPACK_CALLOC
  420. #error "Don't define MPACK_CALLOC. MPack does not use calloc()."
  421. #endif
  422. #ifdef mpack_calloc
  423. #error "Don't define mpack_calloc. MPack does not use calloc()."
  424. #endif
  425. // Use defaults in stdlib if we have them. Without it we don't use malloc.
  426. #if defined(MPACK_STDLIB)
  427. #if MPACK_STDLIB && !defined(MPACK_MALLOC)
  428. #define MPACK_MALLOC malloc
  429. #define MPACK_REALLOC realloc
  430. #define MPACK_FREE free
  431. #endif
  432. #endif
  433. /**
  434. * @}
  435. */
  436. // This needs to be defined after we've decided whether we have malloc().
  437. #ifndef MPACK_BUILDER
  438. #if defined(MPACK_MALLOC) && MPACK_WRITER
  439. #define MPACK_BUILDER 1
  440. #else
  441. #define MPACK_BUILDER 0
  442. #endif
  443. #endif
  444. /**
  445. * @name System Functions
  446. * @{
  447. */
  448. /**
  449. * @def MPACK_MEMCMP
  450. *
  451. * The function MPack will use to provide @c memcmp().
  452. *
  453. * Set this to use a custom @c memcmp() function. Your function must have the
  454. * signature:
  455. *
  456. * @code
  457. * int memcmp(const void* left, const void* right, size_t count);
  458. * @endcode
  459. */
  460. /**
  461. * @def MPACK_MEMCPY
  462. *
  463. * The function MPack will use to provide @c memcpy().
  464. *
  465. * Set this to use a custom @c memcpy() function. Your function must have the
  466. * signature:
  467. *
  468. * @code
  469. * void* memcpy(void* restrict dest, const void* restrict src, size_t count);
  470. * @endcode
  471. */
  472. /**
  473. * @def MPACK_MEMMOVE
  474. *
  475. * The function MPack will use to provide @c memmove().
  476. *
  477. * Set this to use a custom @c memmove() function. Your function must have the
  478. * signature:
  479. *
  480. * @code
  481. * void* memmove(void* dest, const void* src, size_t count);
  482. * @endcode
  483. */
  484. /**
  485. * @def MPACK_MEMSET
  486. *
  487. * The function MPack will use to provide @c memset().
  488. *
  489. * Set this to use a custom @c memset() function. Your function must have the
  490. * signature:
  491. *
  492. * @code
  493. * void* memset(void* p, int c, size_t count);
  494. * @endcode
  495. */
  496. /**
  497. * @def MPACK_STRLEN
  498. *
  499. * The function MPack will use to provide @c strlen().
  500. *
  501. * Set this to use a custom @c strlen() function. Your function must have the
  502. * signature:
  503. *
  504. * @code
  505. * size_t strlen(const char* str);
  506. * @endcode
  507. */
  508. // These were briefly configurable in lowercase in an unreleased version. Just
  509. // to make sure no one is doing this, we make sure these aren't already defined.
  510. #ifdef mpack_memcmp
  511. #error "Define MPACK_MEMCMP, not mpack_memcmp."
  512. #endif
  513. #ifdef mpack_memcpy
  514. #error "Define MPACK_MEMCPY, not mpack_memcpy."
  515. #endif
  516. #ifdef mpack_memmove
  517. #error "Define MPACK_MEMMOVE, not mpack_memmove."
  518. #endif
  519. #ifdef mpack_memset
  520. #error "Define MPACK_MEMSET, not mpack_memset."
  521. #endif
  522. #ifdef mpack_strlen
  523. #error "Define MPACK_STRLEN, not mpack_strlen."
  524. #endif
  525. // If the standard library is available, we prefer to use its functions.
  526. #if MPACK_STDLIB
  527. #ifndef MPACK_MEMCMP
  528. #define MPACK_MEMCMP memcmp
  529. #endif
  530. #ifndef MPACK_MEMCPY
  531. #define MPACK_MEMCPY memcpy
  532. #endif
  533. #ifndef MPACK_MEMMOVE
  534. #define MPACK_MEMMOVE memmove
  535. #endif
  536. #ifndef MPACK_MEMSET
  537. #define MPACK_MEMSET memset
  538. #endif
  539. #ifndef MPACK_STRLEN
  540. #define MPACK_STRLEN strlen
  541. #endif
  542. #endif
  543. #if !MPACK_NO_BUILTINS
  544. #ifdef __has_builtin
  545. #if !defined(MPACK_MEMCMP) && __has_builtin(__builtin_memcmp)
  546. #define MPACK_MEMCMP __builtin_memcmp
  547. #endif
  548. #if !defined(MPACK_MEMCPY) && __has_builtin(__builtin_memcpy)
  549. #define MPACK_MEMCPY __builtin_memcpy
  550. #endif
  551. #if !defined(MPACK_MEMMOVE) && __has_builtin(__builtin_memmove)
  552. #define MPACK_MEMMOVE __builtin_memmove
  553. #endif
  554. #if !defined(MPACK_MEMSET) && __has_builtin(__builtin_memset)
  555. #define MPACK_MEMSET __builtin_memset
  556. #endif
  557. #if !defined(MPACK_STRLEN) && __has_builtin(__builtin_strlen)
  558. #define MPACK_STRLEN __builtin_strlen
  559. #endif
  560. #elif defined(__GNUC__)
  561. #ifndef MPACK_MEMCMP
  562. #define MPACK_MEMCMP __builtin_memcmp
  563. #endif
  564. #ifndef MPACK_MEMCPY
  565. #define MPACK_MEMCPY __builtin_memcpy
  566. #endif
  567. // There's not always a builtin memmove for GCC. If we can't test for
  568. // it with __has_builtin above, we don't use it. It's been around for
  569. // much longer under clang, but then so has __has_builtin, so we let
  570. // the block above handle it.
  571. #ifndef MPACK_MEMSET
  572. #define MPACK_MEMSET __builtin_memset
  573. #endif
  574. #ifndef MPACK_STRLEN
  575. #define MPACK_STRLEN __builtin_strlen
  576. #endif
  577. #endif
  578. #endif
  579. /**
  580. * @}
  581. */
  582. /**
  583. * @name Debugging Options
  584. * @{
  585. */
  586. /**
  587. * @def MPACK_DEBUG
  588. *
  589. * Enables debug features. You may want to wrap this around your
  590. * own debug preprocs. By default, this is enabled if @c DEBUG or @c _DEBUG
  591. * are defined. (@c NDEBUG is not used since it is allowed to have
  592. * different values in different translation units.)
  593. */
  594. #if !defined(MPACK_DEBUG)
  595. #if defined(DEBUG) || defined(_DEBUG)
  596. #define MPACK_DEBUG 1
  597. #else
  598. #define MPACK_DEBUG 0
  599. #endif
  600. #endif
  601. /**
  602. * @def MPACK_STRINGS
  603. *
  604. * Enables descriptive error and type strings.
  605. *
  606. * This can be turned off (by defining it to 0) to maximize space savings
  607. * on embedded devices. If this is disabled, string functions such as
  608. * mpack_error_to_string() and mpack_type_to_string() return an empty string.
  609. */
  610. #ifndef MPACK_STRINGS
  611. #ifdef __AVR__
  612. #define MPACK_STRINGS 0
  613. #else
  614. #define MPACK_STRINGS 1
  615. #endif
  616. #endif
  617. /**
  618. * Set this to 1 to implement a custom @ref mpack_assert_fail() function.
  619. * See the documentation on @ref mpack_assert_fail() for details.
  620. *
  621. * Asserts are only used when @ref MPACK_DEBUG is enabled, and can be
  622. * triggered by bugs in MPack or bugs due to incorrect usage of MPack.
  623. */
  624. #ifndef MPACK_CUSTOM_ASSERT
  625. #define MPACK_CUSTOM_ASSERT 0
  626. #endif
  627. /**
  628. * @def MPACK_READ_TRACKING
  629. *
  630. * Enables compound type size tracking for readers. This ensures that the
  631. * correct number of elements or bytes are read from a compound type.
  632. *
  633. * This is enabled by default in debug builds (provided a @c malloc() is
  634. * available.)
  635. */
  636. #if !defined(MPACK_READ_TRACKING)
  637. #if MPACK_DEBUG && MPACK_READER && defined(MPACK_MALLOC)
  638. #define MPACK_READ_TRACKING 1
  639. #else
  640. #define MPACK_READ_TRACKING 0
  641. #endif
  642. #endif
  643. #if MPACK_READ_TRACKING && !MPACK_READER
  644. #error "MPACK_READ_TRACKING requires MPACK_READER."
  645. #endif
  646. /**
  647. * @def MPACK_WRITE_TRACKING
  648. *
  649. * Enables compound type size tracking for writers. This ensures that the
  650. * correct number of elements or bytes are written in a compound type.
  651. *
  652. * Note that without write tracking enabled, it is possible for buggy code
  653. * to emit invalid MessagePack without flagging an error by writing the wrong
  654. * number of elements or bytes in a compound type. With tracking enabled,
  655. * MPack will catch such errors and break on the offending line of code.
  656. *
  657. * This is enabled by default in debug builds (provided a @c malloc() is
  658. * available.)
  659. */
  660. #if !defined(MPACK_WRITE_TRACKING)
  661. #if MPACK_DEBUG && MPACK_WRITER && defined(MPACK_MALLOC)
  662. #define MPACK_WRITE_TRACKING 1
  663. #else
  664. #define MPACK_WRITE_TRACKING 0
  665. #endif
  666. #endif
  667. #if MPACK_WRITE_TRACKING && !MPACK_WRITER
  668. #error "MPACK_WRITE_TRACKING requires MPACK_WRITER."
  669. #endif
  670. /**
  671. * @}
  672. */
  673. /**
  674. * @name Miscellaneous Options
  675. * @{
  676. */
  677. /**
  678. * Whether to optimize for size or speed.
  679. *
  680. * Optimizing for size simplifies some parsing and encoding algorithms
  681. * at the expense of speed and saves a few kilobytes of space in the
  682. * resulting executable.
  683. *
  684. * This automatically detects -Os with GCC/Clang. Unfortunately there
  685. * doesn't seem to be a macro defined for /Os under MSVC.
  686. */
  687. #ifndef MPACK_OPTIMIZE_FOR_SIZE
  688. #ifdef __OPTIMIZE_SIZE__
  689. #define MPACK_OPTIMIZE_FOR_SIZE 1
  690. #else
  691. #define MPACK_OPTIMIZE_FOR_SIZE 0
  692. #endif
  693. #endif
  694. /**
  695. * Stack space in bytes to use when initializing a reader or writer
  696. * with a stack-allocated buffer.
  697. *
  698. * @warning Make sure you have sufficient stack space. Some libc use relatively
  699. * small stacks even on desktop platforms, e.g. musl.
  700. */
  701. #ifndef MPACK_STACK_SIZE
  702. #define MPACK_STACK_SIZE 4096
  703. #endif
  704. /**
  705. * Buffer size to use for allocated buffers (such as for a file writer.)
  706. *
  707. * Starting with a single page and growing as needed seems to
  708. * provide the best performance with minimal memory waste.
  709. * Increasing this does not improve performance even when writing
  710. * huge messages.
  711. */
  712. #ifndef MPACK_BUFFER_SIZE
  713. #define MPACK_BUFFER_SIZE 4096
  714. #endif
  715. /**
  716. * Minimum size for paged allocations in bytes.
  717. *
  718. * This is the value used by default for MPACK_NODE_PAGE_SIZE and
  719. * MPACK_BUILDER_PAGE_SIZE.
  720. */
  721. #ifndef MPACK_PAGE_SIZE
  722. #define MPACK_PAGE_SIZE 4096
  723. #endif
  724. /**
  725. * Minimum size of an allocated node page in bytes.
  726. *
  727. * The children for a given compound element must be contiguous, so
  728. * larger pages than this may be allocated as needed. (Safety checks
  729. * exist to prevent malicious data from causing too large allocations.)
  730. *
  731. * See @ref mpack_node_data_t for the size of nodes.
  732. *
  733. * Using as many nodes fit in one memory page seems to provide the
  734. * best performance, and has very little waste when parsing small
  735. * messages.
  736. */
  737. #ifndef MPACK_NODE_PAGE_SIZE
  738. #define MPACK_NODE_PAGE_SIZE MPACK_PAGE_SIZE
  739. #endif
  740. /**
  741. * Minimum size of an allocated builder page in bytes.
  742. *
  743. * Builder writes are deferred to the allocated builder buffer which is
  744. * composed of a list of buffer pages. This defines the size of those pages.
  745. */
  746. #ifndef MPACK_BUILDER_PAGE_SIZE
  747. #define MPACK_BUILDER_PAGE_SIZE MPACK_PAGE_SIZE
  748. #endif
  749. /**
  750. * @def MPACK_BUILDER_INTERNAL_STORAGE
  751. *
  752. * Enables a small amount of internal storage within the writer to avoid some
  753. * allocations when using builders.
  754. *
  755. * This is disabled by default. Enable it to potentially improve performance at
  756. * the expense of a larger writer.
  757. *
  758. * @see MPACK_BUILDER_INTERNAL_STORAGE_SIZE to configure its size.
  759. */
  760. #ifndef MPACK_BUILDER_INTERNAL_STORAGE
  761. #define MPACK_BUILDER_INTERNAL_STORAGE 0
  762. #endif
  763. /**
  764. * Amount of space reserved inside @ref mpack_writer_t for the Builders. This
  765. * can allow small messages to be built with the Builder API without incurring
  766. * an allocation.
  767. *
  768. * Builder metadata is placed in this space in addition to the literal
  769. * MessagePack data. It needs to be big enough to be useful, but not so big as
  770. * to overflow the stack. If more space is needed, pages are allocated.
  771. *
  772. * This is only used if MPACK_BUILDER_INTERNAL_STORAGE is enabled.
  773. *
  774. * @see MPACK_BUILDER_PAGE_SIZE
  775. * @see MPACK_BUILDER_INTERNAL_STORAGE
  776. *
  777. * @warning Writers are typically placed on the stack so make sure you have
  778. * sufficient stack space. Some libc use relatively small stacks even on
  779. * desktop platforms, e.g. musl.
  780. */
  781. #ifndef MPACK_BUILDER_INTERNAL_STORAGE_SIZE
  782. #define MPACK_BUILDER_INTERNAL_STORAGE_SIZE 256
  783. #endif
  784. /**
  785. * The initial depth for the node parser. When MPACK_MALLOC is available,
  786. * the node parser has no practical depth limit, and it is not recursive
  787. * so there is no risk of overflowing the call stack.
  788. */
  789. #ifndef MPACK_NODE_INITIAL_DEPTH
  790. #define MPACK_NODE_INITIAL_DEPTH 8
  791. #endif
  792. /**
  793. * The maximum depth for the node parser if @ref MPACK_MALLOC is not available.
  794. */
  795. #ifndef MPACK_NODE_MAX_DEPTH_WITHOUT_MALLOC
  796. #define MPACK_NODE_MAX_DEPTH_WITHOUT_MALLOC 32
  797. #endif
  798. /**
  799. * @def MPACK_NO_BUILTINS
  800. *
  801. * Whether to disable compiler intrinsics and other built-in functions.
  802. *
  803. * If this is enabled, MPack won't use `__attribute__`, `__declspec`, any
  804. * function starting with `__builtin`, or pretty much anything else that isn't
  805. * standard C.
  806. */
  807. #if defined(MPACK_DOXYGEN)
  808. #if MPACK_DOXYGEN
  809. #define MPACK_NO_BUILTINS 0
  810. #endif
  811. #endif
  812. /**
  813. * @}
  814. */
  815. #if MPACK_DEBUG
  816. /**
  817. * @name Debug Functions
  818. * @{
  819. */
  820. /**
  821. * Implement this and define @ref MPACK_CUSTOM_ASSERT to use a custom
  822. * assertion function.
  823. *
  824. * This function should not return. If it does, MPack will @c abort().
  825. *
  826. * If you use C++, make sure you include @c mpack.h where you define
  827. * this to get the correct linkage (or define it <code>extern "C"</code>.)
  828. *
  829. * Asserts are only used when @ref MPACK_DEBUG is enabled, and can be
  830. * triggered by bugs in MPack or bugs due to incorrect usage of MPack.
  831. */
  832. void mpack_assert_fail(const char* message);
  833. /**
  834. * @}
  835. */
  836. #endif
  837. // The rest of this file shouldn't show up in Doxygen docs.
  838. /** @cond */
  839. /*
  840. * All remaining pseudo-configuration options that have not yet been set must
  841. * be defined here in order to support -Wundef.
  842. *
  843. * These aren't real configuration options; they are implementation details of
  844. * MPack.
  845. */
  846. #ifndef MPACK_CUSTOM_BREAK
  847. #define MPACK_CUSTOM_BREAK 0
  848. #endif
  849. #ifndef MPACK_EMIT_INLINE_DEFS
  850. #define MPACK_EMIT_INLINE_DEFS 0
  851. #endif
  852. #ifndef MPACK_AMALGAMATED
  853. #define MPACK_AMALGAMATED 0
  854. #endif
  855. #ifndef MPACK_RELEASE_VERSION
  856. #define MPACK_RELEASE_VERSION 0
  857. #endif
  858. #ifndef MPACK_INTERNAL
  859. #define MPACK_INTERNAL 0
  860. #endif
  861. /* System headers (based on configuration) */
  862. #if MPACK_CONFORMING
  863. #include <stddef.h>
  864. #include <stdint.h>
  865. #include <stdbool.h>
  866. #include <inttypes.h>
  867. #include <limits.h>
  868. #endif
  869. #if MPACK_STDLIB
  870. #include <string.h>
  871. #include <stdlib.h>
  872. #endif
  873. #if MPACK_STDIO
  874. #include <stdio.h>
  875. #include <errno.h>
  876. #if MPACK_DEBUG
  877. #include <stdarg.h>
  878. #endif
  879. #endif
  880. /*
  881. * Integer Constants and Limits
  882. */
  883. #if MPACK_CONFORMING
  884. #define MPACK_INT64_C INT64_C
  885. #define MPACK_UINT64_C UINT64_C
  886. #define MPACK_INT8_MIN INT8_MIN
  887. #define MPACK_INT16_MIN INT16_MIN
  888. #define MPACK_INT32_MIN INT32_MIN
  889. #define MPACK_INT64_MIN INT64_MIN
  890. #define MPACK_INT_MIN INT_MIN
  891. #define MPACK_INT8_MAX INT8_MAX
  892. #define MPACK_INT16_MAX INT16_MAX
  893. #define MPACK_INT32_MAX INT32_MAX
  894. #define MPACK_INT64_MAX INT64_MAX
  895. #define MPACK_INT_MAX INT_MAX
  896. #define MPACK_UINT8_MAX UINT8_MAX
  897. #define MPACK_UINT16_MAX UINT16_MAX
  898. #define MPACK_UINT32_MAX UINT32_MAX
  899. #define MPACK_UINT64_MAX UINT64_MAX
  900. #define MPACK_UINT_MAX UINT_MAX
  901. #else
  902. // For a non-conforming implementation we assume int is 32 bits.
  903. #define MPACK_INT64_C(x) ((int64_t)(x##LL))
  904. #define MPACK_UINT64_C(x) ((uint64_t)(x##LLU))
  905. #define MPACK_INT8_MIN ((int8_t)(0x80))
  906. #define MPACK_INT16_MIN ((int16_t)(0x8000))
  907. #define MPACK_INT32_MIN ((int32_t)(0x80000000))
  908. #define MPACK_INT64_MIN MPACK_INT64_C(0x8000000000000000)
  909. #define MPACK_INT_MIN MPACK_INT32_MIN
  910. #define MPACK_INT8_MAX ((int8_t)(0x7f))
  911. #define MPACK_INT16_MAX ((int16_t)(0x7fff))
  912. #define MPACK_INT32_MAX ((int32_t)(0x7fffffff))
  913. #define MPACK_INT64_MAX MPACK_INT64_C(0x7fffffffffffffff)
  914. #define MPACK_INT_MAX MPACK_INT32_MAX
  915. #define MPACK_UINT8_MAX ((uint8_t)(0xffu))
  916. #define MPACK_UINT16_MAX ((uint16_t)(0xffffu))
  917. #define MPACK_UINT32_MAX ((uint32_t)(0xffffffffu))
  918. #define MPACK_UINT64_MAX MPACK_UINT64_C(0xffffffffffffffff)
  919. #define MPACK_UINT_MAX MPACK_UINT32_MAX
  920. #endif
  921. /*
  922. * Floating point support
  923. */
  924. #if MPACK_DOUBLE && !MPACK_FLOAT
  925. #error "MPACK_DOUBLE requires MPACK_FLOAT."
  926. #endif
  927. // If we don't have support for float or double, we poison the identifiers to
  928. // make sure we don't define anything related to them.
  929. #if MPACK_INTERNAL
  930. #ifdef __GNUC__
  931. #if !MPACK_FLOAT
  932. #pragma GCC poison float
  933. #endif
  934. #if !MPACK_DOUBLE
  935. #pragma GCC poison double
  936. #endif
  937. #endif
  938. #endif
  939. /*
  940. * extern C
  941. */
  942. #ifdef __cplusplus
  943. #define MPACK_EXTERN_C_BEGIN extern "C" {
  944. #define MPACK_EXTERN_C_END }
  945. #else
  946. #define MPACK_EXTERN_C_BEGIN /*nothing*/
  947. #define MPACK_EXTERN_C_END /*nothing*/
  948. #endif
  949. /*
  950. * Warnings
  951. */
  952. #if defined(__GNUC__)
  953. // Diagnostic push is not supported before GCC 4.6.
  954. #if defined(__clang__) || __GNUC__ > 4 || (__GNUC__ == 4 && __GNUC_MINOR__ >= 6)
  955. #define MPACK_SILENCE_WARNINGS_PUSH _Pragma ("GCC diagnostic push")
  956. #define MPACK_SILENCE_WARNINGS_POP _Pragma ("GCC diagnostic pop")
  957. #endif
  958. #elif defined(_MSC_VER)
  959. // To support VS2017 and earlier we need to use __pragma and not _Pragma
  960. #define MPACK_SILENCE_WARNINGS_PUSH __pragma(warning(push))
  961. #define MPACK_SILENCE_WARNINGS_POP __pragma(warning(pop))
  962. #endif
  963. #if defined(_MSC_VER)
  964. // These are a bunch of mostly useless warnings emitted under MSVC /W4,
  965. // some as a result of the expansion of macros.
  966. #define MPACK_SILENCE_WARNINGS_MSVC_W4 \
  967. __pragma(warning(disable:4996)) /* _CRT_SECURE_NO_WARNINGS */ \
  968. __pragma(warning(disable:4127)) /* comparison is constant */ \
  969. __pragma(warning(disable:4702)) /* unreachable code */ \
  970. __pragma(warning(disable:4310)) /* cast truncates constant value */
  971. #else
  972. #define MPACK_SILENCE_WARNINGS_MSVC_W4 /*nothing*/
  973. #endif
  974. /* GCC versions before 5.1 warn about defining a C99 non-static inline function
  975. * before declaring it (see issue #20). */
  976. #if defined(__GNUC__) && !defined(__clang__)
  977. #if __GNUC__ < 5 || (__GNUC__ == 5 && __GNUC_MINOR__ < 1)
  978. #ifdef __cplusplus
  979. #define MPACK_SILENCE_WARNINGS_MISSING_PROTOTYPES \
  980. _Pragma ("GCC diagnostic ignored \"-Wmissing-declarations\"")
  981. #else
  982. #define MPACK_SILENCE_WARNINGS_MISSING_PROTOTYPES \
  983. _Pragma ("GCC diagnostic ignored \"-Wmissing-prototypes\"")
  984. #endif
  985. #endif
  986. #endif
  987. #ifndef MPACK_SILENCE_WARNINGS_MISSING_PROTOTYPES
  988. #define MPACK_SILENCE_WARNINGS_MISSING_PROTOTYPES /*nothing*/
  989. #endif
  990. /* GCC versions before 4.8 warn about shadowing a function with a variable that
  991. * isn't a function or function pointer (like "index"). */
  992. #if defined(__GNUC__) && !defined(__clang__)
  993. #if __GNUC__ == 4 && __GNUC_MINOR__ < 8
  994. #define MPACK_SILENCE_WARNINGS_SHADOW \
  995. _Pragma ("GCC diagnostic ignored \"-Wshadow\"")
  996. #endif
  997. #endif
  998. #ifndef MPACK_SILENCE_WARNINGS_SHADOW
  999. #define MPACK_SILENCE_WARNINGS_SHADOW /*nothing*/
  1000. #endif
  1001. // On platforms with small size_t (e.g. AVR) we get type limits warnings where
  1002. // we compare a size_t to e.g. MPACK_UINT32_MAX.
  1003. #ifdef __AVR__
  1004. #define MPACK_SILENCE_WARNINGS_TYPE_LIMITS \
  1005. _Pragma ("GCC diagnostic ignored \"-Wtype-limits\"")
  1006. #else
  1007. #define MPACK_SILENCE_WARNINGS_TYPE_LIMITS /*nothing*/
  1008. #endif
  1009. // MPack uses declarations after statements. This silences warnings about it
  1010. // (e.g. when using MPack in a Linux kernel module.)
  1011. #if defined(__GNUC__) && !defined(__cplusplus)
  1012. #define MPACK_SILENCE_WARNINGS_DECLARATION_AFTER_STATEMENT \
  1013. _Pragma ("GCC diagnostic ignored \"-Wdeclaration-after-statement\"")
  1014. #else
  1015. #define MPACK_SILENCE_WARNINGS_DECLARATION_AFTER_STATEMENT /*nothing*/
  1016. #endif
  1017. #ifdef MPACK_SILENCE_WARNINGS_PUSH
  1018. // We only silence warnings if push/pop is supported, that way we aren't
  1019. // silencing warnings in code that uses MPack. If your compiler doesn't
  1020. // support push/pop silencing of warnings, you'll have to turn off
  1021. // conflicting warnings manually.
  1022. #define MPACK_SILENCE_WARNINGS_BEGIN \
  1023. MPACK_SILENCE_WARNINGS_PUSH \
  1024. MPACK_SILENCE_WARNINGS_MSVC_W4 \
  1025. MPACK_SILENCE_WARNINGS_MISSING_PROTOTYPES \
  1026. MPACK_SILENCE_WARNINGS_SHADOW \
  1027. MPACK_SILENCE_WARNINGS_TYPE_LIMITS \
  1028. MPACK_SILENCE_WARNINGS_DECLARATION_AFTER_STATEMENT
  1029. #define MPACK_SILENCE_WARNINGS_END \
  1030. MPACK_SILENCE_WARNINGS_POP
  1031. #else
  1032. #define MPACK_SILENCE_WARNINGS_BEGIN /*nothing*/
  1033. #define MPACK_SILENCE_WARNINGS_END /*nothing*/
  1034. #endif
  1035. MPACK_SILENCE_WARNINGS_BEGIN
  1036. MPACK_EXTERN_C_BEGIN
  1037. /* Miscellaneous helper macros */
  1038. #define MPACK_UNUSED(var) ((void)(var))
  1039. #define MPACK_STRINGIFY_IMPL(arg) #arg
  1040. #define MPACK_STRINGIFY(arg) MPACK_STRINGIFY_IMPL(arg)
  1041. // This is a workaround for MSVC's incorrect expansion of __VA_ARGS__. It
  1042. // treats __VA_ARGS__ as a single preprocessor token when passed in the
  1043. // argument list of another macro unless we use an outer wrapper to expand it
  1044. // lexically first. (For safety/consistency we use this in all variadic macros
  1045. // that don't ignore the variadic arguments regardless of whether __VA_ARGS__
  1046. // is passed to another macro.)
  1047. // https://stackoverflow.com/a/32400131
  1048. #define MPACK_EXPAND(x) x
  1049. // Extracts the first argument of a variadic macro list, where there might only
  1050. // be one argument.
  1051. #define MPACK_EXTRACT_ARG0_IMPL(first, ...) first
  1052. #define MPACK_EXTRACT_ARG0(...) MPACK_EXPAND(MPACK_EXTRACT_ARG0_IMPL( __VA_ARGS__ , ignored))
  1053. // Stringifies the first argument of a variadic macro list, where there might
  1054. // only be one argument.
  1055. #define MPACK_STRINGIFY_ARG0_impl(first, ...) #first
  1056. #define MPACK_STRINGIFY_ARG0(...) MPACK_EXPAND(MPACK_STRINGIFY_ARG0_impl( __VA_ARGS__ , ignored))
  1057. /*
  1058. * Definition of inline macros.
  1059. *
  1060. * MPack does not use static inline in header files; only one non-inline definition
  1061. * of each function should exist in the final build. This can reduce the binary size
  1062. * in cases where the compiler cannot or chooses not to inline a function.
  1063. * The addresses of functions should also compare equal across translation units
  1064. * regardless of whether they are declared inline.
  1065. *
  1066. * The above requirements mean that the declaration and definition of non-trivial
  1067. * inline functions must be separated so that the definitions will only
  1068. * appear when necessary. In addition, three different linkage models need
  1069. * to be supported:
  1070. *
  1071. * - The C99 model, where a standalone function is emitted only if there is any
  1072. * `extern inline` or non-`inline` declaration (including the definition itself)
  1073. *
  1074. * - The GNU model, where an `inline` definition emits a standalone function and an
  1075. * `extern inline` definition does not, regardless of other declarations
  1076. *
  1077. * - The C++ model, where `inline` emits a standalone function with special
  1078. * (COMDAT) linkage
  1079. *
  1080. * The macros below wrap up everything above. All inline functions defined in header
  1081. * files have a single non-inline definition emitted in the compilation of
  1082. * mpack-platform.c. All inline declarations and definitions use the same MPACK_INLINE
  1083. * specification to simplify the rules on when standalone functions are emitted.
  1084. * Inline functions in source files are defined MPACK_STATIC_INLINE.
  1085. *
  1086. * Additional reading:
  1087. * http://www.greenend.org.uk/rjk/tech/inline.html
  1088. */
  1089. #if defined(__cplusplus)
  1090. // C++ rules
  1091. // The linker will need COMDAT support to link C++ object files,
  1092. // so we don't need to worry about emitting definitions from C++
  1093. // translation units. If mpack-platform.c (or the amalgamation)
  1094. // is compiled as C, its definition will be used, otherwise a
  1095. // C++ definition will be used, and no other C files will emit
  1096. // a definition.
  1097. #define MPACK_INLINE inline
  1098. #elif defined(_MSC_VER)
  1099. // MSVC 2013 always uses COMDAT linkage, but it doesn't treat 'inline' as a
  1100. // keyword in C99 mode. (This appears to be fixed in a later version of
  1101. // MSVC but we don't bother detecting it.)
  1102. #define MPACK_INLINE __inline
  1103. #define MPACK_STATIC_INLINE static __inline
  1104. #elif defined(__GNUC__) && (defined(__GNUC_GNU_INLINE__) || \
  1105. (!defined(__GNUC_STDC_INLINE__) && !defined(__GNUC_GNU_INLINE__)))
  1106. // GNU rules
  1107. #if MPACK_EMIT_INLINE_DEFS
  1108. #define MPACK_INLINE inline
  1109. #else
  1110. #define MPACK_INLINE extern inline
  1111. #endif
  1112. #elif defined(__TINYC__)
  1113. // tcc ignores the inline keyword, so we have to use static inline. We
  1114. // issue a warning to make sure you are aware. You can define the below
  1115. // macro to disable the warning. Hopefully this will be fixed soon:
  1116. // https://lists.nongnu.org/archive/html/tinycc-devel/2019-06/msg00000.html
  1117. #ifndef MPACK_DISABLE_TINYC_INLINE_WARNING
  1118. #warning "Single-definition inline is not supported by tcc. All inlines will be static. Define MPACK_DISABLE_TINYC_INLINE_WARNING to disable this warning."
  1119. #endif
  1120. #define MPACK_INLINE static inline
  1121. #else
  1122. // C99 rules
  1123. #if MPACK_EMIT_INLINE_DEFS
  1124. #define MPACK_INLINE extern inline
  1125. #else
  1126. #define MPACK_INLINE inline
  1127. #endif
  1128. #endif
  1129. #ifndef MPACK_STATIC_INLINE
  1130. #define MPACK_STATIC_INLINE static inline
  1131. #endif
  1132. #ifdef MPACK_OPTIMIZE_FOR_SPEED
  1133. #error "You should define MPACK_OPTIMIZE_FOR_SIZE, not MPACK_OPTIMIZE_FOR_SPEED."
  1134. #endif
  1135. /*
  1136. * Prevent inlining
  1137. *
  1138. * When a function is only used once, it is almost always inlined
  1139. * automatically. This can cause poor instruction cache usage because a
  1140. * function that should rarely be called (such as buffer exhaustion handling)
  1141. * will get inlined into the middle of a hot code path.
  1142. */
  1143. #if !MPACK_NO_BUILTINS
  1144. #if defined(_MSC_VER)
  1145. #define MPACK_NOINLINE __declspec(noinline)
  1146. #elif defined(__GNUC__) || defined(__clang__)
  1147. #define MPACK_NOINLINE __attribute__((__noinline__))
  1148. #endif
  1149. #endif
  1150. #ifndef MPACK_NOINLINE
  1151. #define MPACK_NOINLINE /* nothing */
  1152. #endif
  1153. /* restrict */
  1154. // We prefer the builtins even though e.g. MSVC's __restrict may not have
  1155. // exactly the same behaviour as the proper C99 restrict keyword because the
  1156. // builtins work in C++, so using the same keyword in both C and C++ prevents
  1157. // any incompatibilities when using MPack compiled as C in C++ code.
  1158. #if !MPACK_NO_BUILTINS
  1159. #if defined(__GNUC__)
  1160. #define MPACK_RESTRICT __restrict__
  1161. #elif defined(_MSC_VER)
  1162. #define MPACK_RESTRICT __restrict
  1163. #endif
  1164. #endif
  1165. #ifndef MPACK_RESTRICT
  1166. #ifdef __cplusplus
  1167. #define MPACK_RESTRICT /* nothing, unavailable in C++ */
  1168. #endif
  1169. #endif
  1170. #ifndef MPACK_RESTRICT
  1171. #ifdef _MSC_VER
  1172. // MSVC 2015 apparently doesn't properly support the restrict keyword
  1173. // in C. We're using builtins above which do work on 2015, but when
  1174. // MPACK_NO_BUILTINS is enabled we can't use it.
  1175. #if _MSC_VER < 1910
  1176. #define MPACK_RESTRICT /*nothing*/
  1177. #endif
  1178. #endif
  1179. #endif
  1180. #ifndef MPACK_RESTRICT
  1181. #define MPACK_RESTRICT restrict /* required in C99 */
  1182. #endif
  1183. /* Some compiler-specific keywords and builtins */
  1184. #if !MPACK_NO_BUILTINS
  1185. #if defined(__GNUC__) || defined(__clang__)
  1186. #define MPACK_UNREACHABLE __builtin_unreachable()
  1187. #define MPACK_NORETURN(fn) fn __attribute__((__noreturn__))
  1188. #elif defined(_MSC_VER)
  1189. #define MPACK_UNREACHABLE __assume(0)
  1190. #define MPACK_NORETURN(fn) __declspec(noreturn) fn
  1191. #endif
  1192. #endif
  1193. #ifndef MPACK_UNREACHABLE
  1194. #define MPACK_UNREACHABLE ((void)0)
  1195. #endif
  1196. #ifndef MPACK_NORETURN
  1197. #define MPACK_NORETURN(fn) fn
  1198. #endif
  1199. /*
  1200. * Likely/unlikely
  1201. *
  1202. * These should only really be used when a branch is taken (or not taken) less
  1203. * than 1/1000th of the time. Buffer flush checks when writing very small
  1204. * elements are a good example.
  1205. */
  1206. #if !MPACK_NO_BUILTINS
  1207. #if defined(__GNUC__) || defined(__clang__)
  1208. #ifndef MPACK_LIKELY
  1209. #define MPACK_LIKELY(x) __builtin_expect((x),1)
  1210. #endif
  1211. #ifndef MPACK_UNLIKELY
  1212. #define MPACK_UNLIKELY(x) __builtin_expect((x),0)
  1213. #endif
  1214. #endif
  1215. #endif
  1216. #ifndef MPACK_LIKELY
  1217. #define MPACK_LIKELY(x) (x)
  1218. #endif
  1219. #ifndef MPACK_UNLIKELY
  1220. #define MPACK_UNLIKELY(x) (x)
  1221. #endif
  1222. /* alignof */
  1223. #ifndef MPACK_ALIGNOF
  1224. #if defined(__STDC_VERSION__)
  1225. #if __STDC_VERSION__ >= 201112L
  1226. #define MPACK_ALIGNOF(T) (_Alignof(T))
  1227. #endif
  1228. #endif
  1229. #endif
  1230. #ifndef MPACK_ALIGNOF
  1231. #if defined(__cplusplus)
  1232. #if __cplusplus >= 201103L
  1233. #define MPACK_ALIGNOF(T) (alignof(T))
  1234. #endif
  1235. #endif
  1236. #endif
  1237. #ifndef MPACK_ALIGNOF
  1238. #if defined(__GNUC__) && !defined(MPACK_NO_BUILTINS)
  1239. #if defined(__clang__) || __GNUC__ >= 4
  1240. #define MPACK_ALIGNOF(T) (__alignof__(T))
  1241. #endif
  1242. #endif
  1243. #endif
  1244. #ifndef MPACK_ALIGNOF
  1245. #ifdef _MSC_VER
  1246. #define MPACK_ALIGNOF(T) __alignof(T)
  1247. #endif
  1248. #endif
  1249. // MPACK_ALIGNOF may not exist, in which case a workaround is used.
  1250. /* Static assert */
  1251. #ifndef MPACK_STATIC_ASSERT
  1252. #if defined(__cplusplus)
  1253. #if __cplusplus >= 201103L
  1254. #define MPACK_STATIC_ASSERT static_assert
  1255. #endif
  1256. #elif defined(__STDC_VERSION__)
  1257. #if __STDC_VERSION__ >= 201112L
  1258. #define MPACK_STATIC_ASSERT _Static_assert
  1259. #endif
  1260. #endif
  1261. #endif
  1262. #if !MPACK_NO_BUILTINS
  1263. #ifndef MPACK_STATIC_ASSERT
  1264. #if defined(__has_feature)
  1265. #if __has_feature(cxx_static_assert)
  1266. #define MPACK_STATIC_ASSERT static_assert
  1267. #elif __has_feature(c_static_assert)
  1268. #define MPACK_STATIC_ASSERT _Static_assert
  1269. #endif
  1270. #endif
  1271. #endif
  1272. #ifndef MPACK_STATIC_ASSERT
  1273. #if defined(__GNUC__)
  1274. /* Diagnostic push is not supported before GCC 4.6. */
  1275. #if defined(__clang__) || __GNUC__ > 4 || (__GNUC__ == 4 && __GNUC_MINOR__ >= 6)
  1276. #ifndef __cplusplus
  1277. #if defined(__clang__) || __GNUC__ >= 5
  1278. #define MPACK_IGNORE_PEDANTIC "GCC diagnostic ignored \"-Wpedantic\""
  1279. #else
  1280. #define MPACK_IGNORE_PEDANTIC "GCC diagnostic ignored \"-pedantic\""
  1281. #endif
  1282. #define MPACK_STATIC_ASSERT(expr, str) do { \
  1283. _Pragma ("GCC diagnostic push") \
  1284. _Pragma (MPACK_IGNORE_PEDANTIC) \
  1285. _Pragma ("GCC diagnostic ignored \"-Wc++-compat\"") \
  1286. _Static_assert(expr, str); \
  1287. _Pragma ("GCC diagnostic pop") \
  1288. } while (0)
  1289. #endif
  1290. #endif
  1291. #endif
  1292. #endif
  1293. #ifndef MPACK_STATIC_ASSERT
  1294. #ifdef _MSC_VER
  1295. #if _MSC_VER >= 1600
  1296. #define MPACK_STATIC_ASSERT static_assert
  1297. #endif
  1298. #endif
  1299. #endif
  1300. #endif
  1301. #ifndef MPACK_STATIC_ASSERT
  1302. #define MPACK_STATIC_ASSERT(expr, str) (MPACK_UNUSED(sizeof(char[1 - 2*!(expr)])))
  1303. #endif
  1304. /* _Generic */
  1305. #ifndef MPACK_HAS_GENERIC
  1306. #if defined(__clang__) && defined(__has_feature)
  1307. // With Clang we can test for _Generic support directly
  1308. // and ignore C/C++ version
  1309. #if __has_feature(c_generic_selections)
  1310. #define MPACK_HAS_GENERIC 1
  1311. #else
  1312. #define MPACK_HAS_GENERIC 0
  1313. #endif
  1314. #endif
  1315. #endif
  1316. #ifndef MPACK_HAS_GENERIC
  1317. #if defined(__STDC_VERSION__)
  1318. #if __STDC_VERSION__ >= 201112L
  1319. #if defined(__GNUC__) && !defined(__clang__)
  1320. // GCC does not have full C11 support in GCC 4.7 and 4.8
  1321. #if __GNUC__ > 4 || (__GNUC__ == 4 && __GNUC_MINOR__ >= 9)
  1322. #define MPACK_HAS_GENERIC 1
  1323. #endif
  1324. #else
  1325. // We hope other compilers aren't lying about C11/_Generic support
  1326. #define MPACK_HAS_GENERIC 1
  1327. #endif
  1328. #endif
  1329. #endif
  1330. #endif
  1331. #ifndef MPACK_HAS_GENERIC
  1332. #define MPACK_HAS_GENERIC 0
  1333. #endif
  1334. /*
  1335. * Finite Math
  1336. *
  1337. * -ffinite-math-only, included in -ffast-math, breaks functions that
  1338. * that check for non-finite real values such as isnan() and isinf().
  1339. *
  1340. * We should use this to trap errors when reading data that contains
  1341. * non-finite reals. This isn't currently implemented.
  1342. */
  1343. #ifndef MPACK_FINITE_MATH
  1344. #if defined(__FINITE_MATH_ONLY__) && __FINITE_MATH_ONLY__
  1345. #define MPACK_FINITE_MATH 1
  1346. #endif
  1347. #endif
  1348. #ifndef MPACK_FINITE_MATH
  1349. #define MPACK_FINITE_MATH 0
  1350. #endif
  1351. /*
  1352. * Endianness checks
  1353. *
  1354. * These define MPACK_NHSWAP*() which swap network<->host byte
  1355. * order when needed.
  1356. *
  1357. * We leave them undefined if we can't determine the endianness
  1358. * at compile-time, in which case we fall back to bit-shifts.
  1359. *
  1360. * See the notes in mpack-common.h.
  1361. */
  1362. #if defined(__BYTE_ORDER__) && defined(__ORDER_LITTLE_ENDIAN__) && defined(__ORDER_BIG_ENDIAN__)
  1363. #if __BYTE_ORDER__ == __ORDER_BIG_ENDIAN__
  1364. #define MPACK_NHSWAP16(x) (x)
  1365. #define MPACK_NHSWAP32(x) (x)
  1366. #define MPACK_NHSWAP64(x) (x)
  1367. #elif __BYTE_ORDER__ == __ORDER_LITTLE_ENDIAN__
  1368. #if !MPACK_NO_BUILTINS
  1369. #if defined(__clang__)
  1370. #ifdef __has_builtin
  1371. // Unlike the GCC builtins, the bswap builtins in Clang
  1372. // significantly improve ARM performance.
  1373. #if __has_builtin(__builtin_bswap16)
  1374. #define MPACK_NHSWAP16(x) __builtin_bswap16(x)
  1375. #endif
  1376. #if __has_builtin(__builtin_bswap32)
  1377. #define MPACK_NHSWAP32(x) __builtin_bswap32(x)
  1378. #endif
  1379. #if __has_builtin(__builtin_bswap64)
  1380. #define MPACK_NHSWAP64(x) __builtin_bswap64(x)
  1381. #endif
  1382. #endif
  1383. #elif defined(__GNUC__)
  1384. // The GCC bswap builtins are apparently poorly optimized on older
  1385. // versions of GCC, so we set a minimum version here just in case.
  1386. // http://hardwarebug.org/2010/01/14/beware-the-builtins/
  1387. #if __GNUC__ > 4 || (__GNUC__ == 4 && __GNUC_MINOR__ >= 5)
  1388. #define MPACK_NHSWAP64(x) __builtin_bswap64(x)
  1389. #endif
  1390. // __builtin_bswap16() was not implemented on all platforms
  1391. // until GCC 4.8.0:
  1392. // https://gcc.gnu.org/bugzilla/show_bug.cgi?id=52624
  1393. //
  1394. // The 16- and 32-bit versions in GCC significantly reduce performance
  1395. // on ARM with little effect on code size so we don't use them.
  1396. #endif
  1397. #endif
  1398. #endif
  1399. #elif defined(_MSC_VER) && defined(_WIN32) && MPACK_STDLIB && !MPACK_NO_BUILTINS
  1400. // On Windows, we assume x86 and x86_64 are always little-endian.
  1401. // We make no assumptions about ARM even though all current
  1402. // Windows Phone devices are little-endian in case Microsoft's
  1403. // compiler is ever used with a big-endian ARM device.
  1404. // These are functions in <stdlib.h> so we depend on MPACK_STDLIB.
  1405. // It's not clear if these are actually faster than just doing the
  1406. // swap manually; maybe we shouldn't bother with this.
  1407. #if defined(_M_IX86) || defined(_M_X64) || defined(_M_AMD64)
  1408. #define MPACK_NHSWAP16(x) _byteswap_ushort(x)
  1409. #define MPACK_NHSWAP32(x) _byteswap_ulong(x)
  1410. #define MPACK_NHSWAP64(x) _byteswap_uint64(x)
  1411. #endif
  1412. #endif
  1413. #if defined(__FLOAT_WORD_ORDER__) && defined(__BYTE_ORDER__)
  1414. // We check where possible that the float byte order matches the
  1415. // integer byte order. This is extremely unlikely to fail, but
  1416. // we check anyway just in case.
  1417. //
  1418. // (The static assert is placed in float/double encoders instead
  1419. // of here because our static assert fallback doesn't work at
  1420. // file scope)
  1421. #define MPACK_CHECK_FLOAT_ORDER() \
  1422. MPACK_STATIC_ASSERT(__FLOAT_WORD_ORDER__ == __BYTE_ORDER__, \
  1423. "float byte order does not match int byte order! float/double " \
  1424. "encoding is not properly implemented on this platform.")
  1425. #endif
  1426. #ifndef MPACK_CHECK_FLOAT_ORDER
  1427. #define MPACK_CHECK_FLOAT_ORDER() /* nothing */
  1428. #endif
  1429. /*
  1430. * Here we define mpack_assert() and mpack_break(). They both work like a normal
  1431. * assertion function in debug mode, causing a trap or abort. However, on some platforms
  1432. * you can safely resume execution from mpack_break(), whereas mpack_assert() is
  1433. * always fatal.
  1434. *
  1435. * In release mode, mpack_assert() is converted to an assurance to the compiler
  1436. * that the expression cannot be false (via e.g. __assume() or __builtin_unreachable())
  1437. * to improve optimization where supported. There is thus no point in "safely" handling
  1438. * the case of this being false. Writing mpack_assert(0) rarely makes sense (except
  1439. * possibly as a default handler in a switch) since the compiler will throw away any
  1440. * code after it. If at any time an mpack_assert() is not true, the behaviour is
  1441. * undefined. This also means the expression is evaluated even in release.
  1442. *
  1443. * mpack_break() on the other hand is compiled to nothing in release. It is
  1444. * used in situations where we want to highlight a programming error as early as
  1445. * possible (in the debugger), but we still handle the situation safely if it
  1446. * happens in release to avoid producing incorrect results (such as in
  1447. * MPACK_WRITE_TRACKING.) It does not take an expression to test because it
  1448. * belongs in a safe-handling block after its failing condition has been tested.
  1449. *
  1450. * If stdio is available, we can add a format string describing the error, and
  1451. * on some compilers we can declare it noreturn to get correct results from static
  1452. * analysis tools. Note that the format string and arguments are not evaluated unless
  1453. * the assertion is hit.
  1454. *
  1455. * Note that any arguments to mpack_assert() beyond the first are only evaluated
  1456. * if the expression is false (and are never evaluated in release.)
  1457. *
  1458. * mpack_assert_fail() and mpack_break_hit() are defined separately
  1459. * because assert is noreturn and break isn't. This distinction is very
  1460. * important for static analysis tools to give correct results.
  1461. */
  1462. #if MPACK_DEBUG
  1463. MPACK_NORETURN(void mpack_assert_fail_wrapper(const char* message));
  1464. #if MPACK_STDIO
  1465. MPACK_NORETURN(void mpack_assert_fail_format(const char* format, ...));
  1466. #define mpack_assert_fail_at(line, file, exprstr, format, ...) \
  1467. MPACK_EXPAND(mpack_assert_fail_format("mpack assertion failed at " file ":" #line "\n%s\n" format, exprstr, __VA_ARGS__))
  1468. #else
  1469. #define mpack_assert_fail_at(line, file, exprstr, format, ...) \
  1470. mpack_assert_fail_wrapper("mpack assertion failed at " file ":" #line "\n" exprstr "\n")
  1471. #endif
  1472. #define mpack_assert_fail_pos(line, file, exprstr, expr, ...) \
  1473. MPACK_EXPAND(mpack_assert_fail_at(line, file, exprstr, __VA_ARGS__))
  1474. // This contains a workaround to the pedantic C99 requirement of having at
  1475. // least one argument to a variadic macro. The first argument is the
  1476. // boolean expression, the optional second argument (if provided) must be a
  1477. // literal format string, and any additional arguments are the format
  1478. // argument list.
  1479. //
  1480. // Unfortunately this means macros are expanded in the expression before it
  1481. // gets stringified. I haven't found a workaround to this.
  1482. //
  1483. // This adds two unused arguments to the format argument list when a
  1484. // format string is provided, so this would complicate the use of
  1485. // -Wformat and __attribute__((__format__)) on mpack_assert_fail_format()
  1486. // if we ever bothered to implement it.
  1487. #define mpack_assert(...) \
  1488. MPACK_EXPAND(((!(MPACK_EXTRACT_ARG0(__VA_ARGS__))) ? \
  1489. mpack_assert_fail_pos(__LINE__, __FILE__, MPACK_STRINGIFY_ARG0(__VA_ARGS__) , __VA_ARGS__ , "", NULL) : \
  1490. (void)0))
  1491. void mpack_break_hit(const char* message);
  1492. #if MPACK_STDIO
  1493. void mpack_break_hit_format(const char* format, ...);
  1494. #define mpack_break_hit_at(line, file, ...) \
  1495. MPACK_EXPAND(mpack_break_hit_format("mpack breakpoint hit at " file ":" #line "\n" __VA_ARGS__))
  1496. #else
  1497. #define mpack_break_hit_at(line, file, ...) \
  1498. mpack_break_hit("mpack breakpoint hit at " file ":" #line )
  1499. #endif
  1500. #define mpack_break_hit_pos(line, file, ...) MPACK_EXPAND(mpack_break_hit_at(line, file, __VA_ARGS__))
  1501. #define mpack_break(...) MPACK_EXPAND(mpack_break_hit_pos(__LINE__, __FILE__, __VA_ARGS__))
  1502. #else
  1503. #define mpack_assert(...) \
  1504. (MPACK_EXPAND((!(MPACK_EXTRACT_ARG0(__VA_ARGS__))) ? \
  1505. (MPACK_UNREACHABLE, (void)0) : \
  1506. (void)0))
  1507. #define mpack_break(...) ((void)0)
  1508. #endif
  1509. // make sure we don't use the stdlib directly during development
  1510. #if MPACK_STDLIB && defined(MPACK_UNIT_TESTS) && MPACK_INTERNAL && defined(__GNUC__)
  1511. #undef memcmp
  1512. #undef memcpy
  1513. #undef memmove
  1514. #undef memset
  1515. #undef strlen
  1516. #undef malloc
  1517. #undef calloc
  1518. #undef realloc
  1519. #undef free
  1520. #pragma GCC poison memcmp
  1521. #pragma GCC poison memcpy
  1522. #pragma GCC poison memmove
  1523. #pragma GCC poison memset
  1524. #pragma GCC poison strlen
  1525. #pragma GCC poison malloc
  1526. #pragma GCC poison calloc
  1527. #pragma GCC poison realloc
  1528. #pragma GCC poison free
  1529. #endif
  1530. // If we don't have these stdlib functions, we need to define them ourselves.
  1531. // Either way we give them a lowercase name to make the code a bit nicer.
  1532. #ifdef MPACK_MEMCMP
  1533. #define mpack_memcmp MPACK_MEMCMP
  1534. #else
  1535. int mpack_memcmp(const void* s1, const void* s2, size_t n);
  1536. #endif
  1537. #ifdef MPACK_MEMCPY
  1538. #define mpack_memcpy MPACK_MEMCPY
  1539. #else
  1540. void* mpack_memcpy(void* MPACK_RESTRICT s1, const void* MPACK_RESTRICT s2, size_t n);
  1541. #endif
  1542. #ifdef MPACK_MEMMOVE
  1543. #define mpack_memmove MPACK_MEMMOVE
  1544. #else
  1545. void* mpack_memmove(void* s1, const void* s2, size_t n);
  1546. #endif
  1547. #ifdef MPACK_MEMSET
  1548. #define mpack_memset MPACK_MEMSET
  1549. #else
  1550. void* mpack_memset(void* s, int c, size_t n);
  1551. #endif
  1552. #ifdef MPACK_STRLEN
  1553. #define mpack_strlen MPACK_STRLEN
  1554. #else
  1555. size_t mpack_strlen(const char* s);
  1556. #endif
  1557. #if MPACK_STDIO
  1558. #if defined(WIN32)
  1559. #define mpack_snprintf _snprintf
  1560. #else
  1561. #define mpack_snprintf snprintf
  1562. #endif
  1563. #endif
  1564. /* Debug logging */
  1565. #if 0
  1566. #include <stdio.h>
  1567. #define mpack_log(...) (MPACK_EXPAND(printf(__VA_ARGS__)), fflush(stdout))
  1568. #else
  1569. #define mpack_log(...) ((void)0)
  1570. #endif
  1571. /* Make sure our configuration makes sense */
  1572. #ifndef MPACK_MALLOC
  1573. #if MPACK_STDIO
  1574. #error "MPACK_STDIO requires preprocessor definitions for MPACK_MALLOC and MPACK_FREE."
  1575. #endif
  1576. #if MPACK_READ_TRACKING
  1577. #error "MPACK_READ_TRACKING requires preprocessor definitions for MPACK_MALLOC and MPACK_FREE."
  1578. #endif
  1579. #if MPACK_WRITE_TRACKING
  1580. #error "MPACK_WRITE_TRACKING requires preprocessor definitions for MPACK_MALLOC and MPACK_FREE."
  1581. #endif
  1582. #endif
  1583. /* Implement realloc if unavailable */
  1584. #ifdef MPACK_MALLOC
  1585. #ifdef MPACK_REALLOC
  1586. MPACK_INLINE void* mpack_realloc(void* old_ptr, size_t used_size, size_t new_size) {
  1587. MPACK_UNUSED(used_size);
  1588. return MPACK_REALLOC(old_ptr, new_size);
  1589. }
  1590. #else
  1591. void* mpack_realloc(void* old_ptr, size_t used_size, size_t new_size);
  1592. #endif
  1593. #endif
  1594. /** @endcond */
  1595. /**
  1596. * @}
  1597. */
  1598. MPACK_EXTERN_C_END
  1599. MPACK_SILENCE_WARNINGS_END
  1600. #endif
  1601. /* mpack/mpack-common.h.h */
  1602. /**
  1603. * @file
  1604. *
  1605. * Defines types and functions shared by the MPack reader and writer.
  1606. */
  1607. #ifndef MPACK_COMMON_H
  1608. #define MPACK_COMMON_H 1
  1609. /* #include "mpack-platform.h" */
  1610. #ifndef MPACK_PRINT_BYTE_COUNT
  1611. #define MPACK_PRINT_BYTE_COUNT 12
  1612. #endif
  1613. MPACK_SILENCE_WARNINGS_BEGIN
  1614. MPACK_EXTERN_C_BEGIN
  1615. /**
  1616. * @defgroup common Tags and Common Elements
  1617. *
  1618. * Contains types, constants and functions shared by both the encoding
  1619. * and decoding portions of MPack.
  1620. *
  1621. * @{
  1622. */
  1623. /* Version information */
  1624. #define MPACK_VERSION_MAJOR 1 /**< The major version number of MPack. */
  1625. #define MPACK_VERSION_MINOR 1 /**< The minor version number of MPack. */
  1626. #define MPACK_VERSION_PATCH 1 /**< The patch version number of MPack. */
  1627. /** A number containing the version number of MPack for comparison purposes. */
  1628. #define MPACK_VERSION ((MPACK_VERSION_MAJOR * 10000) + \
  1629. (MPACK_VERSION_MINOR * 100) + MPACK_VERSION_PATCH)
  1630. /** A macro to test for a minimum version of MPack. */
  1631. #define MPACK_VERSION_AT_LEAST(major, minor, patch) \
  1632. (MPACK_VERSION >= (((major) * 10000) + ((minor) * 100) + (patch)))
  1633. /** @cond */
  1634. #if (MPACK_VERSION_PATCH > 0)
  1635. #define MPACK_VERSION_STRING_BASE \
  1636. MPACK_STRINGIFY(MPACK_VERSION_MAJOR) "." \
  1637. MPACK_STRINGIFY(MPACK_VERSION_MINOR) "." \
  1638. MPACK_STRINGIFY(MPACK_VERSION_PATCH)
  1639. #else
  1640. #define MPACK_VERSION_STRING_BASE \
  1641. MPACK_STRINGIFY(MPACK_VERSION_MAJOR) "." \
  1642. MPACK_STRINGIFY(MPACK_VERSION_MINOR)
  1643. #endif
  1644. /** @endcond */
  1645. /**
  1646. * @def MPACK_VERSION_STRING
  1647. * @hideinitializer
  1648. *
  1649. * A string containing the MPack version.
  1650. */
  1651. #if MPACK_RELEASE_VERSION
  1652. #define MPACK_VERSION_STRING MPACK_VERSION_STRING_BASE
  1653. #else
  1654. #define MPACK_VERSION_STRING MPACK_VERSION_STRING_BASE "dev"
  1655. #endif
  1656. /**
  1657. * @def MPACK_LIBRARY_STRING
  1658. * @hideinitializer
  1659. *
  1660. * A string describing MPack, containing the library name, version and debug mode.
  1661. */
  1662. #if MPACK_DEBUG
  1663. #define MPACK_LIBRARY_STRING "MPack " MPACK_VERSION_STRING "-debug"
  1664. #else
  1665. #define MPACK_LIBRARY_STRING "MPack " MPACK_VERSION_STRING
  1666. #endif
  1667. /** @cond */
  1668. /**
  1669. * @def MPACK_MAXIMUM_TAG_SIZE
  1670. *
  1671. * The maximum encoded size of a tag in bytes.
  1672. */
  1673. #define MPACK_MAXIMUM_TAG_SIZE 9
  1674. /** @endcond */
  1675. #if MPACK_EXTENSIONS
  1676. /**
  1677. * @def MPACK_TIMESTAMP_NANOSECONDS_MAX
  1678. *
  1679. * The maximum value of nanoseconds for a timestamp.
  1680. *
  1681. * @note This requires @ref MPACK_EXTENSIONS.
  1682. */
  1683. #define MPACK_TIMESTAMP_NANOSECONDS_MAX 999999999
  1684. #endif
  1685. #if MPACK_COMPATIBILITY
  1686. /**
  1687. * Versions of the MessagePack format.
  1688. *
  1689. * A reader, writer, or tree can be configured to serialize in an older
  1690. * version of the MessagePack spec. This is necessary to interface with
  1691. * older MessagePack libraries that do not support new MessagePack features.
  1692. *
  1693. * @note This requires @ref MPACK_COMPATIBILITY.
  1694. */
  1695. typedef enum mpack_version_t {
  1696. /**
  1697. * Version 1.0/v4, supporting only the @c raw type without @c str8.
  1698. */
  1699. mpack_version_v4 = 4,
  1700. /**
  1701. * Version 2.0/v5, supporting the @c str8, @c bin and @c ext types.
  1702. */
  1703. mpack_version_v5 = 5,
  1704. /**
  1705. * The most recent supported version of MessagePack. This is the default.
  1706. */
  1707. mpack_version_current = mpack_version_v5,
  1708. } mpack_version_t;
  1709. #endif
  1710. /**
  1711. * Error states for MPack objects.
  1712. *
  1713. * When a reader, writer, or tree is in an error state, all subsequent calls
  1714. * are ignored and their return values are nil/zero. You should check whether
  1715. * the source is in an error state before using such values.
  1716. */
  1717. typedef enum mpack_error_t {
  1718. mpack_ok = 0, /**< No error. */
  1719. mpack_error_io = 2, /**< The reader or writer failed to fill or flush, or some other file or socket error occurred. */
  1720. mpack_error_invalid, /**< The data read is not valid MessagePack. */
  1721. mpack_error_unsupported, /**< The data read is not supported by this configuration of MPack. (See @ref MPACK_EXTENSIONS.) */
  1722. mpack_error_type, /**< The type or value range did not match what was expected by the caller. */
  1723. mpack_error_too_big, /**< A read or write was bigger than the maximum size allowed for that operation. */
  1724. mpack_error_memory, /**< An allocation failure occurred. */
  1725. mpack_error_bug, /**< The MPack API was used incorrectly. (This will always assert in debug mode.) */
  1726. mpack_error_data, /**< The contained data is not valid. */
  1727. mpack_error_eof, /**< The reader failed to read because of file or socket EOF */
  1728. } mpack_error_t;
  1729. /**
  1730. * Converts an MPack error to a string. This function returns an empty
  1731. * string when MPACK_DEBUG is not set.
  1732. */
  1733. const char* mpack_error_to_string(mpack_error_t error);
  1734. /**
  1735. * Defines the type of a MessagePack tag.
  1736. *
  1737. * Note that extension types, both user defined and built-in, are represented
  1738. * in tags as @ref mpack_type_ext. The value for an extension type is stored
  1739. * separately.
  1740. */
  1741. typedef enum mpack_type_t {
  1742. mpack_type_missing = 0, /**< Special type indicating a missing optional value. */
  1743. mpack_type_nil, /**< A null value. */
  1744. mpack_type_bool, /**< A boolean (true or false.) */
  1745. mpack_type_int, /**< A 64-bit signed integer. */
  1746. mpack_type_uint, /**< A 64-bit unsigned integer. */
  1747. mpack_type_float, /**< A 32-bit IEEE 754 floating point number. */
  1748. mpack_type_double, /**< A 64-bit IEEE 754 floating point number. */
  1749. mpack_type_str, /**< A string. */
  1750. mpack_type_bin, /**< A chunk of binary data. */
  1751. mpack_type_array, /**< An array of MessagePack objects. */
  1752. mpack_type_map, /**< An ordered map of key/value pairs of MessagePack objects. */
  1753. #if MPACK_EXTENSIONS
  1754. /**
  1755. * A typed MessagePack extension object containing a chunk of binary data.
  1756. *
  1757. * @note This requires @ref MPACK_EXTENSIONS.
  1758. */
  1759. mpack_type_ext,
  1760. #endif
  1761. } mpack_type_t;
  1762. /**
  1763. * Converts an MPack type to a string. This function returns an empty
  1764. * string when MPACK_DEBUG is not set.
  1765. */
  1766. const char* mpack_type_to_string(mpack_type_t type);
  1767. #if MPACK_EXTENSIONS
  1768. /**
  1769. * A timestamp.
  1770. *
  1771. * @note This requires @ref MPACK_EXTENSIONS.
  1772. */
  1773. typedef struct mpack_timestamp_t {
  1774. int64_t seconds; /*< The number of seconds (signed) since 1970-01-01T00:00:00Z. */
  1775. uint32_t nanoseconds; /*< The number of additional nanoseconds, between 0 and 999,999,999. */
  1776. } mpack_timestamp_t;
  1777. #endif
  1778. /**
  1779. * An MPack tag is a MessagePack object header. It is a variant type
  1780. * representing any kind of object, and includes the length of compound types
  1781. * (e.g. map, array, string) or the value of non-compound types (e.g. boolean,
  1782. * integer, float.)
  1783. *
  1784. * If the type is compound (str, bin, ext, array or map), the contained
  1785. * elements or bytes are stored separately.
  1786. *
  1787. * This structure is opaque; its fields should not be accessed outside
  1788. * of MPack.
  1789. */
  1790. typedef struct mpack_tag_t mpack_tag_t;
  1791. /* Hide internals from documentation */
  1792. /** @cond */
  1793. struct mpack_tag_t {
  1794. mpack_type_t type; /*< The type of value. */
  1795. #if MPACK_EXTENSIONS
  1796. int8_t exttype; /*< The extension type if the type is @ref mpack_type_ext. */
  1797. #endif
  1798. /* The value for non-compound types. */
  1799. union {
  1800. uint64_t u; /*< The value if the type is unsigned int. */
  1801. int64_t i; /*< The value if the type is signed int. */
  1802. bool b; /*< The value if the type is bool. */
  1803. #if MPACK_FLOAT
  1804. float f; /*< The value if the type is float. */
  1805. #else
  1806. uint32_t f; /*< The raw value if the type is float. */
  1807. #endif
  1808. #if MPACK_DOUBLE
  1809. double d; /*< The value if the type is double. */
  1810. #else
  1811. uint64_t d; /*< The raw value if the type is double. */
  1812. #endif
  1813. /* The number of bytes if the type is str, bin or ext. */
  1814. uint32_t l;
  1815. /* The element count if the type is an array, or the number of
  1816. key/value pairs if the type is map. */
  1817. uint32_t n;
  1818. } v;
  1819. };
  1820. /** @endcond */
  1821. /**
  1822. * @name Tag Generators
  1823. * @{
  1824. */
  1825. /**
  1826. * @def MPACK_TAG_ZERO
  1827. *
  1828. * An @ref mpack_tag_t initializer that zeroes the given tag.
  1829. *
  1830. * @warning This does not make the tag nil! The tag's type is invalid when
  1831. * initialized this way. Use @ref mpack_tag_make_nil() to generate a nil tag.
  1832. */
  1833. #if MPACK_EXTENSIONS
  1834. #define MPACK_TAG_ZERO {(mpack_type_t)0, 0, {0}}
  1835. #else
  1836. #define MPACK_TAG_ZERO {(mpack_type_t)0, {0}}
  1837. #endif
  1838. /** Generates a nil tag. */
  1839. MPACK_INLINE mpack_tag_t mpack_tag_make_nil(void) {
  1840. mpack_tag_t ret = MPACK_TAG_ZERO;
  1841. ret.type = mpack_type_nil;
  1842. return ret;
  1843. }
  1844. /** Generates a bool tag. */
  1845. MPACK_INLINE mpack_tag_t mpack_tag_make_bool(bool value) {
  1846. mpack_tag_t ret = MPACK_TAG_ZERO;
  1847. ret.type = mpack_type_bool;
  1848. ret.v.b = value;
  1849. return ret;
  1850. }
  1851. /** Generates a bool tag with value true. */
  1852. MPACK_INLINE mpack_tag_t mpack_tag_make_true(void) {
  1853. mpack_tag_t ret = MPACK_TAG_ZERO;
  1854. ret.type = mpack_type_bool;
  1855. ret.v.b = true;
  1856. return ret;
  1857. }
  1858. /** Generates a bool tag with value false. */
  1859. MPACK_INLINE mpack_tag_t mpack_tag_make_false(void) {
  1860. mpack_tag_t ret = MPACK_TAG_ZERO;
  1861. ret.type = mpack_type_bool;
  1862. ret.v.b = false;
  1863. return ret;
  1864. }
  1865. /** Generates a signed int tag. */
  1866. MPACK_INLINE mpack_tag_t mpack_tag_make_int(int64_t value) {
  1867. mpack_tag_t ret = MPACK_TAG_ZERO;
  1868. ret.type = mpack_type_int;
  1869. ret.v.i = value;
  1870. return ret;
  1871. }
  1872. /** Generates an unsigned int tag. */
  1873. MPACK_INLINE mpack_tag_t mpack_tag_make_uint(uint64_t value) {
  1874. mpack_tag_t ret = MPACK_TAG_ZERO;
  1875. ret.type = mpack_type_uint;
  1876. ret.v.u = value;
  1877. return ret;
  1878. }
  1879. #if MPACK_FLOAT
  1880. /** Generates a float tag. */
  1881. MPACK_INLINE mpack_tag_t mpack_tag_make_float(float value)
  1882. #else
  1883. /** Generates a float tag from a raw uint32_t. */
  1884. MPACK_INLINE mpack_tag_t mpack_tag_make_raw_float(uint32_t value)
  1885. #endif
  1886. {
  1887. mpack_tag_t ret = MPACK_TAG_ZERO;
  1888. ret.type = mpack_type_float;
  1889. ret.v.f = value;
  1890. return ret;
  1891. }
  1892. #if MPACK_DOUBLE
  1893. /** Generates a double tag. */
  1894. MPACK_INLINE mpack_tag_t mpack_tag_make_double(double value)
  1895. #else
  1896. /** Generates a double tag from a raw uint64_t. */
  1897. MPACK_INLINE mpack_tag_t mpack_tag_make_raw_double(uint64_t value)
  1898. #endif
  1899. {
  1900. mpack_tag_t ret = MPACK_TAG_ZERO;
  1901. ret.type = mpack_type_double;
  1902. ret.v.d = value;
  1903. return ret;
  1904. }
  1905. /** Generates an array tag. */
  1906. MPACK_INLINE mpack_tag_t mpack_tag_make_array(uint32_t count) {
  1907. mpack_tag_t ret = MPACK_TAG_ZERO;
  1908. ret.type = mpack_type_array;
  1909. ret.v.n = count;
  1910. return ret;
  1911. }
  1912. /** Generates a map tag. */
  1913. MPACK_INLINE mpack_tag_t mpack_tag_make_map(uint32_t count) {
  1914. mpack_tag_t ret = MPACK_TAG_ZERO;
  1915. ret.type = mpack_type_map;
  1916. ret.v.n = count;
  1917. return ret;
  1918. }
  1919. /** Generates a str tag. */
  1920. MPACK_INLINE mpack_tag_t mpack_tag_make_str(uint32_t length) {
  1921. mpack_tag_t ret = MPACK_TAG_ZERO;
  1922. ret.type = mpack_type_str;
  1923. ret.v.l = length;
  1924. return ret;
  1925. }
  1926. /** Generates a bin tag. */
  1927. MPACK_INLINE mpack_tag_t mpack_tag_make_bin(uint32_t length) {
  1928. mpack_tag_t ret = MPACK_TAG_ZERO;
  1929. ret.type = mpack_type_bin;
  1930. ret.v.l = length;
  1931. return ret;
  1932. }
  1933. #if MPACK_EXTENSIONS
  1934. /**
  1935. * Generates an ext tag.
  1936. *
  1937. * @note This requires @ref MPACK_EXTENSIONS.
  1938. */
  1939. MPACK_INLINE mpack_tag_t mpack_tag_make_ext(int8_t exttype, uint32_t length) {
  1940. mpack_tag_t ret = MPACK_TAG_ZERO;
  1941. ret.type = mpack_type_ext;
  1942. ret.exttype = exttype;
  1943. ret.v.l = length;
  1944. return ret;
  1945. }
  1946. #endif
  1947. /**
  1948. * @}
  1949. */
  1950. /**
  1951. * @name Tag Querying Functions
  1952. * @{
  1953. */
  1954. /**
  1955. * Gets the type of a tag.
  1956. */
  1957. MPACK_INLINE mpack_type_t mpack_tag_type(mpack_tag_t* tag) {
  1958. return tag->type;
  1959. }
  1960. /**
  1961. * Gets the boolean value of a bool-type tag. The tag must be of type @ref
  1962. * mpack_type_bool.
  1963. *
  1964. * This asserts that the type in the tag is @ref mpack_type_bool. (No check is
  1965. * performed if MPACK_DEBUG is not set.)
  1966. */
  1967. MPACK_INLINE bool mpack_tag_bool_value(mpack_tag_t* tag) {
  1968. mpack_assert(tag->type == mpack_type_bool, "tag is not a bool!");
  1969. return tag->v.b;
  1970. }
  1971. /**
  1972. * Gets the signed integer value of an int-type tag.
  1973. *
  1974. * This asserts that the type in the tag is @ref mpack_type_int. (No check is
  1975. * performed if MPACK_DEBUG is not set.)
  1976. *
  1977. * @warning This does not convert between signed and unsigned tags! A positive
  1978. * integer may be stored in a tag as either @ref mpack_type_int or @ref
  1979. * mpack_type_uint. You must check the type first; this can only be used if the
  1980. * type is @ref mpack_type_int.
  1981. *
  1982. * @see mpack_type_int
  1983. */
  1984. MPACK_INLINE int64_t mpack_tag_int_value(mpack_tag_t* tag) {
  1985. mpack_assert(tag->type == mpack_type_int, "tag is not an int!");
  1986. return tag->v.i;
  1987. }
  1988. /**
  1989. * Gets the unsigned integer value of a uint-type tag.
  1990. *
  1991. * This asserts that the type in the tag is @ref mpack_type_uint. (No check is
  1992. * performed if MPACK_DEBUG is not set.)
  1993. *
  1994. * @warning This does not convert between signed and unsigned tags! A positive
  1995. * integer may be stored in a tag as either @ref mpack_type_int or @ref
  1996. * mpack_type_uint. You must check the type first; this can only be used if the
  1997. * type is @ref mpack_type_uint.
  1998. *
  1999. * @see mpack_type_uint
  2000. */
  2001. MPACK_INLINE uint64_t mpack_tag_uint_value(mpack_tag_t* tag) {
  2002. mpack_assert(tag->type == mpack_type_uint, "tag is not a uint!");
  2003. return tag->v.u;
  2004. }
  2005. /**
  2006. * Gets the float value of a float-type tag.
  2007. *
  2008. * This asserts that the type in the tag is @ref mpack_type_float. (No check is
  2009. * performed if MPACK_DEBUG is not set.)
  2010. *
  2011. * @warning This does not convert between float and double tags! This can only
  2012. * be used if the type is @ref mpack_type_float.
  2013. *
  2014. * @see mpack_type_float
  2015. */
  2016. MPACK_INLINE
  2017. #if MPACK_FLOAT
  2018. float mpack_tag_float_value(mpack_tag_t* tag)
  2019. #else
  2020. uint32_t mpack_tag_raw_float_value(mpack_tag_t* tag)
  2021. #endif
  2022. {
  2023. mpack_assert(tag->type == mpack_type_float, "tag is not a float!");
  2024. return tag->v.f;
  2025. }
  2026. /**
  2027. * Gets the double value of a double-type tag.
  2028. *
  2029. * This asserts that the type in the tag is @ref mpack_type_double. (No check
  2030. * is performed if MPACK_DEBUG is not set.)
  2031. *
  2032. * @warning This does not convert between float and double tags! This can only
  2033. * be used if the type is @ref mpack_type_double.
  2034. *
  2035. * @see mpack_type_double
  2036. */
  2037. MPACK_INLINE
  2038. #if MPACK_DOUBLE
  2039. double mpack_tag_double_value(mpack_tag_t* tag)
  2040. #else
  2041. uint64_t mpack_tag_raw_double_value(mpack_tag_t* tag)
  2042. #endif
  2043. {
  2044. mpack_assert(tag->type == mpack_type_double, "tag is not a double!");
  2045. return tag->v.d;
  2046. }
  2047. /**
  2048. * Gets the number of elements in an array tag.
  2049. *
  2050. * This asserts that the type in the tag is @ref mpack_type_array. (No check is
  2051. * performed if MPACK_DEBUG is not set.)
  2052. *
  2053. * @see mpack_type_array
  2054. */
  2055. MPACK_INLINE uint32_t mpack_tag_array_count(mpack_tag_t* tag) {
  2056. mpack_assert(tag->type == mpack_type_array, "tag is not an array!");
  2057. return tag->v.n;
  2058. }
  2059. /**
  2060. * Gets the number of key-value pairs in a map tag.
  2061. *
  2062. * This asserts that the type in the tag is @ref mpack_type_map. (No check is
  2063. * performed if MPACK_DEBUG is not set.)
  2064. *
  2065. * @see mpack_type_map
  2066. */
  2067. MPACK_INLINE uint32_t mpack_tag_map_count(mpack_tag_t* tag) {
  2068. mpack_assert(tag->type == mpack_type_map, "tag is not a map!");
  2069. return tag->v.n;
  2070. }
  2071. /**
  2072. * Gets the length in bytes of a str-type tag.
  2073. *
  2074. * This asserts that the type in the tag is @ref mpack_type_str. (No check is
  2075. * performed if MPACK_DEBUG is not set.)
  2076. *
  2077. * @see mpack_type_str
  2078. */
  2079. MPACK_INLINE uint32_t mpack_tag_str_length(mpack_tag_t* tag) {
  2080. mpack_assert(tag->type == mpack_type_str, "tag is not a str!");
  2081. return tag->v.l;
  2082. }
  2083. /**
  2084. * Gets the length in bytes of a bin-type tag.
  2085. *
  2086. * This asserts that the type in the tag is @ref mpack_type_bin. (No check is
  2087. * performed if MPACK_DEBUG is not set.)
  2088. *
  2089. * @see mpack_type_bin
  2090. */
  2091. MPACK_INLINE uint32_t mpack_tag_bin_length(mpack_tag_t* tag) {
  2092. mpack_assert(tag->type == mpack_type_bin, "tag is not a bin!");
  2093. return tag->v.l;
  2094. }
  2095. #if MPACK_EXTENSIONS
  2096. /**
  2097. * Gets the length in bytes of an ext-type tag.
  2098. *
  2099. * This asserts that the type in the tag is @ref mpack_type_ext. (No check is
  2100. * performed if MPACK_DEBUG is not set.)
  2101. *
  2102. * @note This requires @ref MPACK_EXTENSIONS.
  2103. *
  2104. * @see mpack_type_ext
  2105. */
  2106. MPACK_INLINE uint32_t mpack_tag_ext_length(mpack_tag_t* tag) {
  2107. mpack_assert(tag->type == mpack_type_ext, "tag is not an ext!");
  2108. return tag->v.l;
  2109. }
  2110. /**
  2111. * Gets the extension type (exttype) of an ext-type tag.
  2112. *
  2113. * This asserts that the type in the tag is @ref mpack_type_ext. (No check is
  2114. * performed if MPACK_DEBUG is not set.)
  2115. *
  2116. * @note This requires @ref MPACK_EXTENSIONS.
  2117. *
  2118. * @see mpack_type_ext
  2119. */
  2120. MPACK_INLINE int8_t mpack_tag_ext_exttype(mpack_tag_t* tag) {
  2121. mpack_assert(tag->type == mpack_type_ext, "tag is not an ext!");
  2122. return tag->exttype;
  2123. }
  2124. #endif
  2125. /**
  2126. * Gets the length in bytes of a str-, bin- or ext-type tag.
  2127. *
  2128. * This asserts that the type in the tag is @ref mpack_type_str, @ref
  2129. * mpack_type_bin or @ref mpack_type_ext. (No check is performed if MPACK_DEBUG
  2130. * is not set.)
  2131. *
  2132. * @see mpack_type_str
  2133. * @see mpack_type_bin
  2134. * @see mpack_type_ext
  2135. */
  2136. MPACK_INLINE uint32_t mpack_tag_bytes(mpack_tag_t* tag) {
  2137. #if MPACK_EXTENSIONS
  2138. mpack_assert(tag->type == mpack_type_str || tag->type == mpack_type_bin
  2139. || tag->type == mpack_type_ext, "tag is not a str, bin or ext!");
  2140. #else
  2141. mpack_assert(tag->type == mpack_type_str || tag->type == mpack_type_bin,
  2142. "tag is not a str or bin!");
  2143. #endif
  2144. return tag->v.l;
  2145. }
  2146. /**
  2147. * @}
  2148. */
  2149. /**
  2150. * @name Other tag functions
  2151. * @{
  2152. */
  2153. #if MPACK_EXTENSIONS
  2154. /**
  2155. * The extension type for a timestamp.
  2156. *
  2157. * @note This requires @ref MPACK_EXTENSIONS.
  2158. */
  2159. #define MPACK_EXTTYPE_TIMESTAMP ((int8_t)(-1))
  2160. #endif
  2161. /**
  2162. * Compares two tags with an arbitrary fixed ordering. Returns 0 if the tags are
  2163. * equal, a negative integer if left comes before right, or a positive integer
  2164. * otherwise.
  2165. *
  2166. * \warning The ordering is not guaranteed to be preserved across MPack versions; do
  2167. * not rely on it in persistent data.
  2168. *
  2169. * \warning Floating point numbers are compared bit-for-bit, not using the language's
  2170. * operator==. This means that NaNs with matching representation will compare equal.
  2171. * This behaviour is up for debate; see comments in the definition of mpack_tag_cmp().
  2172. *
  2173. * See mpack_tag_equal() for more information on when tags are considered equal.
  2174. */
  2175. int mpack_tag_cmp(mpack_tag_t left, mpack_tag_t right);
  2176. /**
  2177. * Compares two tags for equality. Tags are considered equal if the types are compatible
  2178. * and the values (for non-compound types) are equal.
  2179. *
  2180. * The field width of variable-width fields is ignored (and in fact is not stored
  2181. * in a tag), and positive numbers in signed integers are considered equal to their
  2182. * unsigned counterparts. So for example the value 1 stored as a positive fixint
  2183. * is equal to the value 1 stored in a 64-bit unsigned integer field.
  2184. *
  2185. * The "extension type" of an extension object is considered part of the value
  2186. * and must match exactly.
  2187. *
  2188. * \warning Floating point numbers are compared bit-for-bit, not using the language's
  2189. * operator==. This means that NaNs with matching representation will compare equal.
  2190. * This behaviour is up for debate; see comments in the definition of mpack_tag_cmp().
  2191. */
  2192. MPACK_INLINE bool mpack_tag_equal(mpack_tag_t left, mpack_tag_t right) {
  2193. return mpack_tag_cmp(left, right) == 0;
  2194. }
  2195. #if MPACK_DEBUG && MPACK_STDIO
  2196. /**
  2197. * Generates a json-like debug description of the given tag into the given buffer.
  2198. *
  2199. * This is only available in debug mode, and only if stdio is available (since
  2200. * it uses snprintf().) It's strictly for debugging purposes.
  2201. *
  2202. * The prefix is used to print the first few hexadecimal bytes of a bin or ext
  2203. * type. Pass NULL if not a bin or ext.
  2204. */
  2205. void mpack_tag_debug_pseudo_json(mpack_tag_t tag, char* buffer, size_t buffer_size,
  2206. const char* prefix, size_t prefix_size);
  2207. /**
  2208. * Generates a debug string description of the given tag into the given buffer.
  2209. *
  2210. * This is only available in debug mode, and only if stdio is available (since
  2211. * it uses snprintf().) It's strictly for debugging purposes.
  2212. */
  2213. void mpack_tag_debug_describe(mpack_tag_t tag, char* buffer, size_t buffer_size);
  2214. /** @cond */
  2215. /*
  2216. * A callback function for printing pseudo-JSON for debugging purposes.
  2217. *
  2218. * @see mpack_node_print_callback
  2219. */
  2220. typedef void (*mpack_print_callback_t)(void* context, const char* data, size_t count);
  2221. // helpers for printing debug output
  2222. // i feel a bit like i'm re-implementing a buffered writer again...
  2223. typedef struct mpack_print_t {
  2224. char* buffer;
  2225. size_t size;
  2226. size_t count;
  2227. mpack_print_callback_t callback;
  2228. void* context;
  2229. } mpack_print_t;
  2230. void mpack_print_append(mpack_print_t* print, const char* data, size_t count);
  2231. MPACK_INLINE void mpack_print_append_cstr(mpack_print_t* print, const char* cstr) {
  2232. mpack_print_append(print, cstr, mpack_strlen(cstr));
  2233. }
  2234. void mpack_print_flush(mpack_print_t* print);
  2235. void mpack_print_file_callback(void* context, const char* data, size_t count);
  2236. /** @endcond */
  2237. #endif
  2238. /**
  2239. * @}
  2240. */
  2241. /**
  2242. * @name Deprecated Tag Generators
  2243. * @{
  2244. */
  2245. /*
  2246. * "make" has been added to their names to disambiguate them from the
  2247. * value-fetching functions (e.g. mpack_tag_make_bool() vs
  2248. * mpack_tag_bool_value().)
  2249. *
  2250. * The length and count for all compound types was the wrong sign (int32_t
  2251. * instead of uint32_t.) These preserve the old behaviour; the new "make"
  2252. * functions have the correct sign.
  2253. */
  2254. /** \deprecated Renamed to mpack_tag_make_nil(). */
  2255. MPACK_INLINE mpack_tag_t mpack_tag_nil(void) {
  2256. return mpack_tag_make_nil();
  2257. }
  2258. /** \deprecated Renamed to mpack_tag_make_bool(). */
  2259. MPACK_INLINE mpack_tag_t mpack_tag_bool(bool value) {
  2260. return mpack_tag_make_bool(value);
  2261. }
  2262. /** \deprecated Renamed to mpack_tag_make_true(). */
  2263. MPACK_INLINE mpack_tag_t mpack_tag_true(void) {
  2264. return mpack_tag_make_true();
  2265. }
  2266. /** \deprecated Renamed to mpack_tag_make_false(). */
  2267. MPACK_INLINE mpack_tag_t mpack_tag_false(void) {
  2268. return mpack_tag_make_false();
  2269. }
  2270. /** \deprecated Renamed to mpack_tag_make_int(). */
  2271. MPACK_INLINE mpack_tag_t mpack_tag_int(int64_t value) {
  2272. return mpack_tag_make_int(value);
  2273. }
  2274. /** \deprecated Renamed to mpack_tag_make_uint(). */
  2275. MPACK_INLINE mpack_tag_t mpack_tag_uint(uint64_t value) {
  2276. return mpack_tag_make_uint(value);
  2277. }
  2278. #if MPACK_FLOAT
  2279. /** \deprecated Renamed to mpack_tag_make_float(). */
  2280. MPACK_INLINE mpack_tag_t mpack_tag_float(float value) {
  2281. return mpack_tag_make_float(value);
  2282. }
  2283. #endif
  2284. #if MPACK_DOUBLE
  2285. /** \deprecated Renamed to mpack_tag_make_double(). */
  2286. MPACK_INLINE mpack_tag_t mpack_tag_double(double value) {
  2287. return mpack_tag_make_double(value);
  2288. }
  2289. #endif
  2290. /** \deprecated Renamed to mpack_tag_make_array(). */
  2291. MPACK_INLINE mpack_tag_t mpack_tag_array(int32_t count) {
  2292. return mpack_tag_make_array((uint32_t)count);
  2293. }
  2294. /** \deprecated Renamed to mpack_tag_make_map(). */
  2295. MPACK_INLINE mpack_tag_t mpack_tag_map(int32_t count) {
  2296. return mpack_tag_make_map((uint32_t)count);
  2297. }
  2298. /** \deprecated Renamed to mpack_tag_make_str(). */
  2299. MPACK_INLINE mpack_tag_t mpack_tag_str(int32_t length) {
  2300. return mpack_tag_make_str((uint32_t)length);
  2301. }
  2302. /** \deprecated Renamed to mpack_tag_make_bin(). */
  2303. MPACK_INLINE mpack_tag_t mpack_tag_bin(int32_t length) {
  2304. return mpack_tag_make_bin((uint32_t)length);
  2305. }
  2306. #if MPACK_EXTENSIONS
  2307. /** \deprecated Renamed to mpack_tag_make_ext(). */
  2308. MPACK_INLINE mpack_tag_t mpack_tag_ext(int8_t exttype, int32_t length) {
  2309. return mpack_tag_make_ext(exttype, (uint32_t)length);
  2310. }
  2311. #endif
  2312. /**
  2313. * @}
  2314. */
  2315. /** @cond */
  2316. /*
  2317. * Helpers to perform unaligned network-endian loads and stores
  2318. * at arbitrary addresses. Byte-swapping builtins are used if they
  2319. * are available and if they improve performance.
  2320. *
  2321. * These will remain available in the public API so feel free to
  2322. * use them for other purposes, but they are undocumented.
  2323. */
  2324. MPACK_INLINE uint8_t mpack_load_u8(const char* p) {
  2325. return (uint8_t)p[0];
  2326. }
  2327. MPACK_INLINE uint16_t mpack_load_u16(const char* p) {
  2328. #ifdef MPACK_NHSWAP16
  2329. uint16_t val;
  2330. mpack_memcpy(&val, p, sizeof(val));
  2331. return MPACK_NHSWAP16(val);
  2332. #else
  2333. return (uint16_t)((((uint16_t)(uint8_t)p[0]) << 8) |
  2334. ((uint16_t)(uint8_t)p[1]));
  2335. #endif
  2336. }
  2337. MPACK_INLINE uint32_t mpack_load_u32(const char* p) {
  2338. #ifdef MPACK_NHSWAP32
  2339. uint32_t val;
  2340. mpack_memcpy(&val, p, sizeof(val));
  2341. return MPACK_NHSWAP32(val);
  2342. #else
  2343. return (((uint32_t)(uint8_t)p[0]) << 24) |
  2344. (((uint32_t)(uint8_t)p[1]) << 16) |
  2345. (((uint32_t)(uint8_t)p[2]) << 8) |
  2346. ((uint32_t)(uint8_t)p[3]);
  2347. #endif
  2348. }
  2349. MPACK_INLINE uint64_t mpack_load_u64(const char* p) {
  2350. #ifdef MPACK_NHSWAP64
  2351. uint64_t val;
  2352. mpack_memcpy(&val, p, sizeof(val));
  2353. return MPACK_NHSWAP64(val);
  2354. #else
  2355. return (((uint64_t)(uint8_t)p[0]) << 56) |
  2356. (((uint64_t)(uint8_t)p[1]) << 48) |
  2357. (((uint64_t)(uint8_t)p[2]) << 40) |
  2358. (((uint64_t)(uint8_t)p[3]) << 32) |
  2359. (((uint64_t)(uint8_t)p[4]) << 24) |
  2360. (((uint64_t)(uint8_t)p[5]) << 16) |
  2361. (((uint64_t)(uint8_t)p[6]) << 8) |
  2362. ((uint64_t)(uint8_t)p[7]);
  2363. #endif
  2364. }
  2365. MPACK_INLINE void mpack_store_u8(char* p, uint8_t val) {
  2366. uint8_t* u = (uint8_t*)p;
  2367. u[0] = val;
  2368. }
  2369. MPACK_INLINE void mpack_store_u16(char* p, uint16_t val) {
  2370. #ifdef MPACK_NHSWAP16
  2371. val = MPACK_NHSWAP16(val);
  2372. mpack_memcpy(p, &val, sizeof(val));
  2373. #else
  2374. uint8_t* u = (uint8_t*)p;
  2375. u[0] = (uint8_t)((val >> 8) & 0xFF);
  2376. u[1] = (uint8_t)( val & 0xFF);
  2377. #endif
  2378. }
  2379. MPACK_INLINE void mpack_store_u32(char* p, uint32_t val) {
  2380. #ifdef MPACK_NHSWAP32
  2381. val = MPACK_NHSWAP32(val);
  2382. mpack_memcpy(p, &val, sizeof(val));
  2383. #else
  2384. uint8_t* u = (uint8_t*)p;
  2385. u[0] = (uint8_t)((val >> 24) & 0xFF);
  2386. u[1] = (uint8_t)((val >> 16) & 0xFF);
  2387. u[2] = (uint8_t)((val >> 8) & 0xFF);
  2388. u[3] = (uint8_t)( val & 0xFF);
  2389. #endif
  2390. }
  2391. MPACK_INLINE void mpack_store_u64(char* p, uint64_t val) {
  2392. #ifdef MPACK_NHSWAP64
  2393. val = MPACK_NHSWAP64(val);
  2394. mpack_memcpy(p, &val, sizeof(val));
  2395. #else
  2396. uint8_t* u = (uint8_t*)p;
  2397. u[0] = (uint8_t)((val >> 56) & 0xFF);
  2398. u[1] = (uint8_t)((val >> 48) & 0xFF);
  2399. u[2] = (uint8_t)((val >> 40) & 0xFF);
  2400. u[3] = (uint8_t)((val >> 32) & 0xFF);
  2401. u[4] = (uint8_t)((val >> 24) & 0xFF);
  2402. u[5] = (uint8_t)((val >> 16) & 0xFF);
  2403. u[6] = (uint8_t)((val >> 8) & 0xFF);
  2404. u[7] = (uint8_t)( val & 0xFF);
  2405. #endif
  2406. }
  2407. MPACK_INLINE int8_t mpack_load_i8 (const char* p) {return (int8_t) mpack_load_u8 (p);}
  2408. MPACK_INLINE int16_t mpack_load_i16(const char* p) {return (int16_t)mpack_load_u16(p);}
  2409. MPACK_INLINE int32_t mpack_load_i32(const char* p) {return (int32_t)mpack_load_u32(p);}
  2410. MPACK_INLINE int64_t mpack_load_i64(const char* p) {return (int64_t)mpack_load_u64(p);}
  2411. MPACK_INLINE void mpack_store_i8 (char* p, int8_t val) {mpack_store_u8 (p, (uint8_t) val);}
  2412. MPACK_INLINE void mpack_store_i16(char* p, int16_t val) {mpack_store_u16(p, (uint16_t)val);}
  2413. MPACK_INLINE void mpack_store_i32(char* p, int32_t val) {mpack_store_u32(p, (uint32_t)val);}
  2414. MPACK_INLINE void mpack_store_i64(char* p, int64_t val) {mpack_store_u64(p, (uint64_t)val);}
  2415. #if MPACK_FLOAT
  2416. MPACK_INLINE float mpack_load_float(const char* p) {
  2417. MPACK_CHECK_FLOAT_ORDER();
  2418. MPACK_STATIC_ASSERT(sizeof(float) == sizeof(uint32_t), "float is wrong size??");
  2419. union {
  2420. float f;
  2421. uint32_t u;
  2422. } v;
  2423. v.u = mpack_load_u32(p);
  2424. return v.f;
  2425. }
  2426. #endif
  2427. #if MPACK_DOUBLE
  2428. MPACK_INLINE double mpack_load_double(const char* p) {
  2429. MPACK_CHECK_FLOAT_ORDER();
  2430. MPACK_STATIC_ASSERT(sizeof(double) == sizeof(uint64_t), "double is wrong size??");
  2431. union {
  2432. double d;
  2433. uint64_t u;
  2434. } v;
  2435. v.u = mpack_load_u64(p);
  2436. return v.d;
  2437. }
  2438. #endif
  2439. #if MPACK_FLOAT
  2440. MPACK_INLINE void mpack_store_float(char* p, float value) {
  2441. MPACK_CHECK_FLOAT_ORDER();
  2442. union {
  2443. float f;
  2444. uint32_t u;
  2445. } v;
  2446. v.f = value;
  2447. mpack_store_u32(p, v.u);
  2448. }
  2449. #endif
  2450. #if MPACK_DOUBLE
  2451. MPACK_INLINE void mpack_store_double(char* p, double value) {
  2452. MPACK_CHECK_FLOAT_ORDER();
  2453. union {
  2454. double d;
  2455. uint64_t u;
  2456. } v;
  2457. v.d = value;
  2458. mpack_store_u64(p, v.u);
  2459. }
  2460. #endif
  2461. #if MPACK_FLOAT && !MPACK_DOUBLE
  2462. /**
  2463. * Performs a manual shortening conversion on the raw 64-bit representation of
  2464. * a double. This is useful for parsing doubles on platforms that only support
  2465. * floats (such as AVR.)
  2466. *
  2467. * The significand is truncated rather than rounded and subnormal numbers are
  2468. * set to 0 so this may not be quite as accurate as a real double-to-float
  2469. * conversion.
  2470. */
  2471. MPACK_INLINE float mpack_shorten_raw_double_to_float(uint64_t d) {
  2472. MPACK_CHECK_FLOAT_ORDER();
  2473. union {
  2474. float f;
  2475. uint32_t u;
  2476. } v;
  2477. // float has 1 bit sign, 8 bits exponent, 23 bits significand
  2478. // double has 1 bit sign, 11 bits exponent, 52 bits significand
  2479. uint64_t d_sign = (uint64_t)(d >> 63);
  2480. uint64_t d_exponent = (uint32_t)(d >> 52) & ((1 << 11) - 1);
  2481. uint64_t d_significand = d & (((uint64_t)1 << 52) - 1);
  2482. uint32_t f_sign = (uint32_t)d_sign;
  2483. uint32_t f_exponent;
  2484. uint32_t f_significand;
  2485. if (MPACK_UNLIKELY(d_exponent == ((1 << 11) - 1))) {
  2486. // infinity or NAN. shift down to preserve the top bit since it
  2487. // indicates signaling NAN, but also set the low bit if any bits were
  2488. // set (that way we can't shift NAN to infinity.)
  2489. f_exponent = ((1 << 8) - 1);
  2490. f_significand = (uint32_t)(d_significand >> 29) | (d_significand ? 1 : 0);
  2491. } else {
  2492. int fix_bias = (int)d_exponent - ((1 << 10) - 1) + ((1 << 7) - 1);
  2493. if (MPACK_UNLIKELY(fix_bias <= 0)) {
  2494. // we don't currently handle subnormal numbers. just set it to zero.
  2495. f_exponent = 0;
  2496. f_significand = 0;
  2497. } else if (MPACK_UNLIKELY(fix_bias > 0xff)) {
  2498. // exponent is too large; saturate to infinity
  2499. f_exponent = 0xff;
  2500. f_significand = 0;
  2501. } else {
  2502. // a normal number that fits in a float. this is the usual case.
  2503. f_exponent = (uint32_t)fix_bias;
  2504. f_significand = (uint32_t)(d_significand >> 29);
  2505. }
  2506. }
  2507. #if 0
  2508. printf("\n===============\n");
  2509. for (size_t i = 0; i < 64; ++i)
  2510. printf("%i%s",(int)((d>>(63-i))&1),((i%8)==7)?" ":"");
  2511. printf("\n%lu %lu %lu\n", d_sign, d_exponent, d_significand);
  2512. printf("%u %u %u\n", f_sign, f_exponent, f_significand);
  2513. #endif
  2514. v.u = (f_sign << 31) | (f_exponent << 23) | f_significand;
  2515. return v.f;
  2516. }
  2517. #endif
  2518. /** @endcond */
  2519. /** @cond */
  2520. // Sizes in bytes for the various possible tags
  2521. #define MPACK_TAG_SIZE_FIXUINT 1
  2522. #define MPACK_TAG_SIZE_U8 2
  2523. #define MPACK_TAG_SIZE_U16 3
  2524. #define MPACK_TAG_SIZE_U32 5
  2525. #define MPACK_TAG_SIZE_U64 9
  2526. #define MPACK_TAG_SIZE_FIXINT 1
  2527. #define MPACK_TAG_SIZE_I8 2
  2528. #define MPACK_TAG_SIZE_I16 3
  2529. #define MPACK_TAG_SIZE_I32 5
  2530. #define MPACK_TAG_SIZE_I64 9
  2531. #define MPACK_TAG_SIZE_FLOAT 5
  2532. #define MPACK_TAG_SIZE_DOUBLE 9
  2533. #define MPACK_TAG_SIZE_FIXARRAY 1
  2534. #define MPACK_TAG_SIZE_ARRAY16 3
  2535. #define MPACK_TAG_SIZE_ARRAY32 5
  2536. #define MPACK_TAG_SIZE_FIXMAP 1
  2537. #define MPACK_TAG_SIZE_MAP16 3
  2538. #define MPACK_TAG_SIZE_MAP32 5
  2539. #define MPACK_TAG_SIZE_FIXSTR 1
  2540. #define MPACK_TAG_SIZE_STR8 2
  2541. #define MPACK_TAG_SIZE_STR16 3
  2542. #define MPACK_TAG_SIZE_STR32 5
  2543. #define MPACK_TAG_SIZE_BIN8 2
  2544. #define MPACK_TAG_SIZE_BIN16 3
  2545. #define MPACK_TAG_SIZE_BIN32 5
  2546. #define MPACK_TAG_SIZE_FIXEXT1 2
  2547. #define MPACK_TAG_SIZE_FIXEXT2 2
  2548. #define MPACK_TAG_SIZE_FIXEXT4 2
  2549. #define MPACK_TAG_SIZE_FIXEXT8 2
  2550. #define MPACK_TAG_SIZE_FIXEXT16 2
  2551. #define MPACK_TAG_SIZE_EXT8 3
  2552. #define MPACK_TAG_SIZE_EXT16 4
  2553. #define MPACK_TAG_SIZE_EXT32 6
  2554. // size in bytes for complete ext types
  2555. #define MPACK_EXT_SIZE_TIMESTAMP4 (MPACK_TAG_SIZE_FIXEXT4 + 4)
  2556. #define MPACK_EXT_SIZE_TIMESTAMP8 (MPACK_TAG_SIZE_FIXEXT8 + 8)
  2557. #define MPACK_EXT_SIZE_TIMESTAMP12 (MPACK_TAG_SIZE_EXT8 + 12)
  2558. /** @endcond */
  2559. #if MPACK_READ_TRACKING || MPACK_WRITE_TRACKING
  2560. /* Tracks the write state of compound elements (maps, arrays, */
  2561. /* strings, binary blobs and extension types) */
  2562. /** @cond */
  2563. typedef struct mpack_track_element_t {
  2564. mpack_type_t type;
  2565. uint32_t left;
  2566. // indicates that a value still needs to be read/written for an already
  2567. // read/written key. left is not decremented until both key and value are
  2568. // read/written.
  2569. bool key_needs_value;
  2570. // tracks whether the map/array being written is using a builder. if true,
  2571. // the number of elements is automatic, and left is 0.
  2572. bool builder;
  2573. } mpack_track_element_t;
  2574. typedef struct mpack_track_t {
  2575. size_t count;
  2576. size_t capacity;
  2577. mpack_track_element_t* elements;
  2578. } mpack_track_t;
  2579. #if MPACK_INTERNAL
  2580. mpack_error_t mpack_track_init(mpack_track_t* track);
  2581. mpack_error_t mpack_track_grow(mpack_track_t* track);
  2582. mpack_error_t mpack_track_push(mpack_track_t* track, mpack_type_t type, uint32_t count);
  2583. mpack_error_t mpack_track_push_builder(mpack_track_t* track, mpack_type_t type);
  2584. mpack_error_t mpack_track_pop(mpack_track_t* track, mpack_type_t type);
  2585. mpack_error_t mpack_track_pop_builder(mpack_track_t* track, mpack_type_t type);
  2586. mpack_error_t mpack_track_element(mpack_track_t* track, bool read);
  2587. mpack_error_t mpack_track_peek_element(mpack_track_t* track, bool read);
  2588. mpack_error_t mpack_track_bytes(mpack_track_t* track, bool read, size_t count);
  2589. mpack_error_t mpack_track_str_bytes_all(mpack_track_t* track, bool read, size_t count);
  2590. mpack_error_t mpack_track_check_empty(mpack_track_t* track);
  2591. mpack_error_t mpack_track_destroy(mpack_track_t* track, bool cancel);
  2592. #endif
  2593. /** @endcond */
  2594. #endif
  2595. #if MPACK_INTERNAL
  2596. /** @cond */
  2597. /* Miscellaneous string functions */
  2598. /**
  2599. * Returns true if the given UTF-8 string is valid.
  2600. */
  2601. bool mpack_utf8_check(const char* str, size_t bytes);
  2602. /**
  2603. * Returns true if the given UTF-8 string is valid and contains no null characters.
  2604. */
  2605. bool mpack_utf8_check_no_null(const char* str, size_t bytes);
  2606. /**
  2607. * Returns true if the given string has no null bytes.
  2608. */
  2609. bool mpack_str_check_no_null(const char* str, size_t bytes);
  2610. /** @endcond */
  2611. #endif
  2612. /**
  2613. * @}
  2614. */
  2615. MPACK_EXTERN_C_END
  2616. MPACK_SILENCE_WARNINGS_END
  2617. #endif
  2618. /* mpack/mpack-writer.h.h */
  2619. /**
  2620. * @file
  2621. *
  2622. * Declares the MPack Writer.
  2623. */
  2624. #ifndef MPACK_WRITER_H
  2625. #define MPACK_WRITER_H 1
  2626. /* #include "mpack-common.h" */
  2627. #if MPACK_WRITER
  2628. MPACK_SILENCE_WARNINGS_BEGIN
  2629. MPACK_EXTERN_C_BEGIN
  2630. #if MPACK_WRITE_TRACKING
  2631. struct mpack_track_t;
  2632. #endif
  2633. /**
  2634. * @defgroup writer Write API
  2635. *
  2636. * The MPack Write API encodes structured data of a fixed (hardcoded) schema to MessagePack.
  2637. *
  2638. * @{
  2639. */
  2640. /**
  2641. * @def MPACK_WRITER_MINIMUM_BUFFER_SIZE
  2642. *
  2643. * The minimum buffer size for a writer with a flush function.
  2644. */
  2645. #define MPACK_WRITER_MINIMUM_BUFFER_SIZE 32
  2646. /**
  2647. * A buffered MessagePack encoder.
  2648. *
  2649. * The encoder wraps an existing buffer and, optionally, a flush function.
  2650. * This allows efficiently encoding to an in-memory buffer or to a stream.
  2651. *
  2652. * All write operations are synchronous; they will block until the
  2653. * data is fully written, or an error occurs.
  2654. */
  2655. typedef struct mpack_writer_t mpack_writer_t;
  2656. /**
  2657. * The MPack writer's flush function to flush the buffer to the output stream.
  2658. * It should flag an appropriate error on the writer if flushing fails (usually
  2659. * mpack_error_io or mpack_error_memory.)
  2660. *
  2661. * The specified context for callbacks is at writer->context.
  2662. */
  2663. typedef void (*mpack_writer_flush_t)(mpack_writer_t* writer, const char* buffer, size_t count);
  2664. /**
  2665. * An error handler function to be called when an error is flagged on
  2666. * the writer.
  2667. *
  2668. * The error handler will only be called once on the first error flagged;
  2669. * any subsequent writes and errors are ignored, and the writer is
  2670. * permanently in that error state.
  2671. *
  2672. * MPack is safe against non-local jumps out of error handler callbacks.
  2673. * This means you are allowed to longjmp or throw an exception (in C++,
  2674. * Objective-C, or with SEH) out of this callback.
  2675. *
  2676. * Bear in mind when using longjmp that local non-volatile variables that
  2677. * have changed are undefined when setjmp() returns, so you can't put the
  2678. * writer on the stack in the same activation frame as the setjmp without
  2679. * declaring it volatile.
  2680. *
  2681. * You must still eventually destroy the writer. It is not destroyed
  2682. * automatically when an error is flagged. It is safe to destroy the
  2683. * writer within this error callback, but you will either need to perform
  2684. * a non-local jump, or store something in your context to identify
  2685. * that the writer is destroyed since any future accesses to it cause
  2686. * undefined behavior.
  2687. */
  2688. typedef void (*mpack_writer_error_t)(mpack_writer_t* writer, mpack_error_t error);
  2689. /**
  2690. * A teardown function to be called when the writer is destroyed.
  2691. */
  2692. typedef void (*mpack_writer_teardown_t)(mpack_writer_t* writer);
  2693. /* Hide internals from documentation */
  2694. /** @cond */
  2695. #if MPACK_BUILDER
  2696. /**
  2697. * Build buffer pages form a linked list.
  2698. *
  2699. * They don't always fill up. If there is not enough space within them to write
  2700. * a tag or place an mpack_build_t, a new page is allocated. For this reason
  2701. * they store the number of used bytes.
  2702. */
  2703. typedef struct mpack_builder_page_t {
  2704. struct mpack_builder_page_t* next;
  2705. size_t bytes_used;
  2706. } mpack_builder_page_t;
  2707. /**
  2708. * Builds form a linked list of mpack_build_t, interleaved with their encoded
  2709. * contents directly in the paged builder buffer.
  2710. */
  2711. typedef struct mpack_build_t {
  2712. //mpack_builder_page_t* page;
  2713. struct mpack_build_t* parent;
  2714. //struct mpack_build_t* next;
  2715. size_t bytes; // number of bytes between this build and the next one
  2716. uint32_t count; // number of elements (or key/value pairs) in this map/array
  2717. mpack_type_t type;
  2718. // depth of nested non-build compound elements within this
  2719. // build.
  2720. uint32_t nested_compound_elements;
  2721. // indicates that a value still needs to be written for an already
  2722. // written key. count is not incremented until both key and value are
  2723. // written.
  2724. bool key_needs_value;
  2725. } mpack_build_t;
  2726. /**
  2727. * The builder state. This is stored within mpack_writer_t.
  2728. */
  2729. typedef struct mpack_builder_t {
  2730. mpack_build_t* current_build; // build which is accumulating elements
  2731. mpack_build_t* latest_build; // build which is accumulating bytes
  2732. mpack_builder_page_t* current_page;
  2733. mpack_builder_page_t* pages;
  2734. char* stash_buffer;
  2735. char* stash_position;
  2736. char* stash_end;
  2737. #if MPACK_BUILDER_INTERNAL_STORAGE
  2738. char internal[MPACK_BUILDER_INTERNAL_STORAGE_SIZE];
  2739. #endif
  2740. } mpack_builder_t;
  2741. #endif
  2742. struct mpack_writer_t {
  2743. #if MPACK_COMPATIBILITY
  2744. mpack_version_t version; /* Version of the MessagePack spec to write */
  2745. #endif
  2746. mpack_writer_flush_t flush; /* Function to write bytes to the output stream */
  2747. mpack_writer_error_t error_fn; /* Function to call on error */
  2748. mpack_writer_teardown_t teardown; /* Function to teardown the context on destroy */
  2749. void* context; /* Context for writer callbacks */
  2750. char* buffer; /* Byte buffer */
  2751. char* position; /* Current position within the buffer */
  2752. char* end; /* The end of the buffer */
  2753. mpack_error_t error; /* Error state */
  2754. #if MPACK_WRITE_TRACKING
  2755. mpack_track_t track; /* Stack of map/array/str/bin/ext writes */
  2756. #endif
  2757. #ifdef MPACK_MALLOC
  2758. /* Reserved. You can use this space to allocate a custom
  2759. * context in order to reduce heap allocations. */
  2760. void* reserved[2];
  2761. #endif
  2762. #if MPACK_BUILDER
  2763. mpack_builder_t builder;
  2764. #endif
  2765. };
  2766. #if MPACK_WRITE_TRACKING
  2767. void mpack_writer_track_push(mpack_writer_t* writer, mpack_type_t type, uint32_t count);
  2768. void mpack_writer_track_push_builder(mpack_writer_t* writer, mpack_type_t type);
  2769. void mpack_writer_track_pop(mpack_writer_t* writer, mpack_type_t type);
  2770. void mpack_writer_track_pop_builder(mpack_writer_t* writer, mpack_type_t type);
  2771. void mpack_writer_track_bytes(mpack_writer_t* writer, size_t count);
  2772. #else
  2773. MPACK_INLINE void mpack_writer_track_push(mpack_writer_t* writer, mpack_type_t type, uint32_t count) {
  2774. MPACK_UNUSED(writer);
  2775. MPACK_UNUSED(type);
  2776. MPACK_UNUSED(count);
  2777. }
  2778. MPACK_INLINE void mpack_writer_track_push_builder(mpack_writer_t* writer, mpack_type_t type) {
  2779. MPACK_UNUSED(writer);
  2780. MPACK_UNUSED(type);
  2781. }
  2782. MPACK_INLINE void mpack_writer_track_pop(mpack_writer_t* writer, mpack_type_t type) {
  2783. MPACK_UNUSED(writer);
  2784. MPACK_UNUSED(type);
  2785. }
  2786. MPACK_INLINE void mpack_writer_track_pop_builder(mpack_writer_t* writer, mpack_type_t type) {
  2787. MPACK_UNUSED(writer);
  2788. MPACK_UNUSED(type);
  2789. }
  2790. MPACK_INLINE void mpack_writer_track_bytes(mpack_writer_t* writer, size_t count) {
  2791. MPACK_UNUSED(writer);
  2792. MPACK_UNUSED(count);
  2793. }
  2794. #endif
  2795. /** @endcond */
  2796. /**
  2797. * @name Lifecycle Functions
  2798. * @{
  2799. */
  2800. /**
  2801. * Initializes an MPack writer with the given buffer. The writer
  2802. * does not assume ownership of the buffer.
  2803. *
  2804. * Trying to write past the end of the buffer will result in mpack_error_too_big
  2805. * unless a flush function is set with mpack_writer_set_flush(). To use the data
  2806. * without flushing, call mpack_writer_buffer_used() to determine the number of
  2807. * bytes written.
  2808. *
  2809. * @param writer The MPack writer.
  2810. * @param buffer The buffer into which to write MessagePack data.
  2811. * @param size The size of the buffer.
  2812. */
  2813. void mpack_writer_init(mpack_writer_t* writer, char* buffer, size_t size);
  2814. #ifdef MPACK_MALLOC
  2815. /**
  2816. * Initializes an MPack writer using a growable buffer.
  2817. *
  2818. * The data is placed in the given data pointer if and when the writer
  2819. * is destroyed without error. The data pointer is NULL during writing,
  2820. * and will remain NULL if an error occurs.
  2821. *
  2822. * The allocated data must be freed with MPACK_FREE() (or simply free()
  2823. * if MPack's allocator hasn't been customized.)
  2824. *
  2825. * @throws mpack_error_memory if the buffer fails to grow when
  2826. * flushing.
  2827. *
  2828. * @param writer The MPack writer.
  2829. * @param data Where to place the allocated data.
  2830. * @param size Where to write the size of the data.
  2831. */
  2832. void mpack_writer_init_growable(mpack_writer_t* writer, char** data, size_t* size);
  2833. #endif
  2834. /**
  2835. * Initializes an MPack writer directly into an error state. Use this if you
  2836. * are writing a wrapper to mpack_writer_init() which can fail its setup.
  2837. */
  2838. void mpack_writer_init_error(mpack_writer_t* writer, mpack_error_t error);
  2839. #if MPACK_STDIO
  2840. /**
  2841. * Initializes an MPack writer that writes to a file.
  2842. *
  2843. * @throws mpack_error_memory if allocation fails
  2844. * @throws mpack_error_io if the file cannot be opened
  2845. */
  2846. void mpack_writer_init_filename(mpack_writer_t* writer, const char* filename);
  2847. /**
  2848. * Deprecated.
  2849. *
  2850. * \deprecated Renamed to mpack_writer_init_filename().
  2851. */
  2852. MPACK_INLINE void mpack_writer_init_file(mpack_writer_t* writer, const char* filename) {
  2853. mpack_writer_init_filename(writer, filename);
  2854. }
  2855. /**
  2856. * Initializes an MPack writer that writes to a libc FILE. This can be used to
  2857. * write to stdout or stderr, or to a file opened separately.
  2858. *
  2859. * @param writer The MPack writer.
  2860. * @param stdfile The FILE.
  2861. * @param close_when_done If true, fclose() will be called on the FILE when it
  2862. * is no longer needed. If false, the file will not be flushed or
  2863. * closed when writing is done.
  2864. *
  2865. * @note The writer is buffered. If you want to write other data to the FILE in
  2866. * between messages, you must flush it first.
  2867. *
  2868. * @see mpack_writer_flush_message
  2869. */
  2870. void mpack_writer_init_stdfile(mpack_writer_t* writer, FILE* stdfile, bool close_when_done);
  2871. #endif
  2872. /** @cond */
  2873. #define mpack_writer_init_stack_line_ex(line, writer) \
  2874. char mpack_buf_##line[MPACK_STACK_SIZE]; \
  2875. mpack_writer_init(writer, mpack_buf_##line, sizeof(mpack_buf_##line))
  2876. #define mpack_writer_init_stack_line(line, writer) \
  2877. mpack_writer_init_stack_line_ex(line, writer)
  2878. /*
  2879. * Initializes an MPack writer using stack space as a buffer. A flush function
  2880. * should be added to the writer to flush the buffer.
  2881. *
  2882. * This is currently undocumented since it's not entirely useful on its own.
  2883. */
  2884. #define mpack_writer_init_stack(writer) \
  2885. mpack_writer_init_stack_line(__LINE__, (writer))
  2886. /** @endcond */
  2887. /**
  2888. * Cleans up the MPack writer, flushing and closing the underlying stream,
  2889. * if any. Returns the final error state of the writer.
  2890. *
  2891. * No flushing is performed if the writer is in an error state. The attached
  2892. * teardown function is called whether or not the writer is in an error state.
  2893. *
  2894. * This will assert in tracking mode if the writer is not in an error
  2895. * state and has any unclosed compound types. If you want to cancel
  2896. * writing in the middle of a document, you need to flag an error on
  2897. * the writer before destroying it (such as mpack_error_data).
  2898. *
  2899. * Note that a writer may raise an error and call your error handler during
  2900. * the final flush. It is safe to longjmp or throw out of this error handler,
  2901. * but if you do, the writer will not be destroyed, and the teardown function
  2902. * will not be called. You can still get the writer's error state, and you
  2903. * must call @ref mpack_writer_destroy() again. (The second call is guaranteed
  2904. * not to call your error handler again since the writer is already in an error
  2905. * state.)
  2906. *
  2907. * @see mpack_writer_set_error_handler
  2908. * @see mpack_writer_set_flush
  2909. * @see mpack_writer_set_teardown
  2910. * @see mpack_writer_flag_error
  2911. * @see mpack_error_data
  2912. */
  2913. mpack_error_t mpack_writer_destroy(mpack_writer_t* writer);
  2914. /**
  2915. * @}
  2916. */
  2917. /**
  2918. * @name Configuration
  2919. * @{
  2920. */
  2921. #if MPACK_COMPATIBILITY
  2922. /**
  2923. * Sets the version of the MessagePack spec that will be generated.
  2924. *
  2925. * This can be used to interface with older libraries that do not support
  2926. * the newest MessagePack features (such as the @c str8 type.)
  2927. *
  2928. * @note This requires @ref MPACK_COMPATIBILITY.
  2929. */
  2930. MPACK_INLINE void mpack_writer_set_version(mpack_writer_t* writer, mpack_version_t version) {
  2931. writer->version = version;
  2932. }
  2933. #endif
  2934. /**
  2935. * Sets the custom pointer to pass to the writer callbacks, such as flush
  2936. * or teardown.
  2937. *
  2938. * @param writer The MPack writer.
  2939. * @param context User data to pass to the writer callbacks.
  2940. *
  2941. * @see mpack_writer_context()
  2942. */
  2943. MPACK_INLINE void mpack_writer_set_context(mpack_writer_t* writer, void* context) {
  2944. writer->context = context;
  2945. }
  2946. /**
  2947. * Returns the custom context for writer callbacks.
  2948. *
  2949. * @see mpack_writer_set_context
  2950. * @see mpack_writer_set_flush
  2951. */
  2952. MPACK_INLINE void* mpack_writer_context(mpack_writer_t* writer) {
  2953. return writer->context;
  2954. }
  2955. /**
  2956. * Sets the flush function to write out the data when the buffer is full.
  2957. *
  2958. * If no flush function is used, trying to write past the end of the
  2959. * buffer will result in mpack_error_too_big.
  2960. *
  2961. * This should normally be used with mpack_writer_set_context() to register
  2962. * a custom pointer to pass to the flush function.
  2963. *
  2964. * @param writer The MPack writer.
  2965. * @param flush The function to write out data from the buffer.
  2966. *
  2967. * @see mpack_writer_context()
  2968. */
  2969. void mpack_writer_set_flush(mpack_writer_t* writer, mpack_writer_flush_t flush);
  2970. /**
  2971. * Sets the error function to call when an error is flagged on the writer.
  2972. *
  2973. * This should normally be used with mpack_writer_set_context() to register
  2974. * a custom pointer to pass to the error function.
  2975. *
  2976. * See the definition of mpack_writer_error_t for more information about
  2977. * what you can do from an error callback.
  2978. *
  2979. * @see mpack_writer_error_t
  2980. * @param writer The MPack writer.
  2981. * @param error_fn The function to call when an error is flagged on the writer.
  2982. */
  2983. MPACK_INLINE void mpack_writer_set_error_handler(mpack_writer_t* writer, mpack_writer_error_t error_fn) {
  2984. writer->error_fn = error_fn;
  2985. }
  2986. /**
  2987. * Sets the teardown function to call when the writer is destroyed.
  2988. *
  2989. * This should normally be used with mpack_writer_set_context() to register
  2990. * a custom pointer to pass to the teardown function.
  2991. *
  2992. * @param writer The MPack writer.
  2993. * @param teardown The function to call when the writer is destroyed.
  2994. */
  2995. MPACK_INLINE void mpack_writer_set_teardown(mpack_writer_t* writer, mpack_writer_teardown_t teardown) {
  2996. writer->teardown = teardown;
  2997. }
  2998. /**
  2999. * @}
  3000. */
  3001. /**
  3002. * @name Core Writer Functions
  3003. * @{
  3004. */
  3005. /**
  3006. * Flushes any buffered data to the underlying stream.
  3007. *
  3008. * If the writer is connected to a socket and you are keeping it open,
  3009. * you will want to call this after writing a message (or set of
  3010. * messages) so that the data is actually sent.
  3011. *
  3012. * It is not necessary to call this if you are not keeping the writer
  3013. * open afterwards. You can just call `mpack_writer_destroy()` and it
  3014. * will flush before cleaning up.
  3015. *
  3016. * This will assert if no flush function is assigned to the writer.
  3017. *
  3018. * If write tracking is enabled, this will break and flag @ref
  3019. * mpack_error_bug if the writer has any open compound types, ensuring
  3020. * that no compound types are still open. This prevents a "missing
  3021. * finish" bug from causing a never-ending message.
  3022. */
  3023. void mpack_writer_flush_message(mpack_writer_t* writer);
  3024. /**
  3025. * Returns the number of bytes currently stored in the buffer. This
  3026. * may be less than the total number of bytes written if bytes have
  3027. * been flushed to an underlying stream.
  3028. */
  3029. MPACK_INLINE size_t mpack_writer_buffer_used(mpack_writer_t* writer) {
  3030. return (size_t)(writer->position - writer->buffer);
  3031. }
  3032. /**
  3033. * Returns the amount of space left in the buffer. This may be reset
  3034. * after a write if bytes are flushed to an underlying stream.
  3035. */
  3036. MPACK_INLINE size_t mpack_writer_buffer_left(mpack_writer_t* writer) {
  3037. return (size_t)(writer->end - writer->position);
  3038. }
  3039. /**
  3040. * Returns the (current) size of the buffer. This may change after a write if
  3041. * the flush callback changes the buffer.
  3042. */
  3043. MPACK_INLINE size_t mpack_writer_buffer_size(mpack_writer_t* writer) {
  3044. return (size_t)(writer->end - writer->buffer);
  3045. }
  3046. /**
  3047. * Places the writer in the given error state, calling the error callback if one
  3048. * is set.
  3049. *
  3050. * This allows you to externally flag errors, for example if you are validating
  3051. * data as you write it, or if you want to cancel writing in the middle of a
  3052. * document. (The writer will assert if you try to destroy it without error and
  3053. * with unclosed compound types. In this case you should flag mpack_error_data
  3054. * before destroying it.)
  3055. *
  3056. * If the writer is already in an error state, this call is ignored and no
  3057. * error callback is called.
  3058. *
  3059. * @see mpack_writer_destroy
  3060. * @see mpack_error_data
  3061. */
  3062. void mpack_writer_flag_error(mpack_writer_t* writer, mpack_error_t error);
  3063. /**
  3064. * Queries the error state of the MPack writer.
  3065. *
  3066. * If a writer is in an error state, you should discard all data since the
  3067. * last time the error flag was checked. The error flag cannot be cleared.
  3068. */
  3069. MPACK_INLINE mpack_error_t mpack_writer_error(mpack_writer_t* writer) {
  3070. return writer->error;
  3071. }
  3072. /**
  3073. * Writes a MessagePack object header (an MPack Tag.)
  3074. *
  3075. * If the value is a map, array, string, binary or extension type, the
  3076. * containing elements or bytes must be written separately and the
  3077. * appropriate finish function must be called (as though one of the
  3078. * mpack_start_*() functions was called.)
  3079. *
  3080. * @see mpack_write_bytes()
  3081. * @see mpack_finish_map()
  3082. * @see mpack_finish_array()
  3083. * @see mpack_finish_str()
  3084. * @see mpack_finish_bin()
  3085. * @see mpack_finish_ext()
  3086. * @see mpack_finish_type()
  3087. */
  3088. void mpack_write_tag(mpack_writer_t* writer, mpack_tag_t tag);
  3089. /**
  3090. * @}
  3091. */
  3092. /**
  3093. * @name Integers
  3094. * @{
  3095. */
  3096. /** Writes an 8-bit integer in the most efficient packing available. */
  3097. void mpack_write_i8(mpack_writer_t* writer, int8_t value);
  3098. /** Writes a 16-bit integer in the most efficient packing available. */
  3099. void mpack_write_i16(mpack_writer_t* writer, int16_t value);
  3100. /** Writes a 32-bit integer in the most efficient packing available. */
  3101. void mpack_write_i32(mpack_writer_t* writer, int32_t value);
  3102. /** Writes a 64-bit integer in the most efficient packing available. */
  3103. void mpack_write_i64(mpack_writer_t* writer, int64_t value);
  3104. /** Writes an integer in the most efficient packing available. */
  3105. MPACK_INLINE void mpack_write_int(mpack_writer_t* writer, int64_t value) {
  3106. mpack_write_i64(writer, value);
  3107. }
  3108. /** Writes an 8-bit unsigned integer in the most efficient packing available. */
  3109. void mpack_write_u8(mpack_writer_t* writer, uint8_t value);
  3110. /** Writes an 16-bit unsigned integer in the most efficient packing available. */
  3111. void mpack_write_u16(mpack_writer_t* writer, uint16_t value);
  3112. /** Writes an 32-bit unsigned integer in the most efficient packing available. */
  3113. void mpack_write_u32(mpack_writer_t* writer, uint32_t value);
  3114. /** Writes an 64-bit unsigned integer in the most efficient packing available. */
  3115. void mpack_write_u64(mpack_writer_t* writer, uint64_t value);
  3116. /** Writes an unsigned integer in the most efficient packing available. */
  3117. MPACK_INLINE void mpack_write_uint(mpack_writer_t* writer, uint64_t value) {
  3118. mpack_write_u64(writer, value);
  3119. }
  3120. /**
  3121. * @}
  3122. */
  3123. /**
  3124. * @name Other Basic Types
  3125. * @{
  3126. */
  3127. #if MPACK_FLOAT
  3128. /** Writes a float. */
  3129. void mpack_write_float(mpack_writer_t* writer, float value);
  3130. #else
  3131. /** Writes a float from a raw uint32_t. */
  3132. void mpack_write_raw_float(mpack_writer_t* writer, uint32_t raw_value);
  3133. #endif
  3134. #if MPACK_DOUBLE
  3135. /** Writes a double. */
  3136. void mpack_write_double(mpack_writer_t* writer, double value);
  3137. #else
  3138. /** Writes a double from a raw uint64_t. */
  3139. void mpack_write_raw_double(mpack_writer_t* writer, uint64_t raw_value);
  3140. #endif
  3141. /** Writes a boolean. */
  3142. void mpack_write_bool(mpack_writer_t* writer, bool value);
  3143. /** Writes a boolean with value true. */
  3144. void mpack_write_true(mpack_writer_t* writer);
  3145. /** Writes a boolean with value false. */
  3146. void mpack_write_false(mpack_writer_t* writer);
  3147. /** Writes a nil. */
  3148. void mpack_write_nil(mpack_writer_t* writer);
  3149. /** Write a pre-encoded messagepack object */
  3150. void mpack_write_object_bytes(mpack_writer_t* writer, const char* data, size_t bytes);
  3151. #if MPACK_EXTENSIONS
  3152. /**
  3153. * Writes a timestamp.
  3154. *
  3155. * @note This requires @ref MPACK_EXTENSIONS.
  3156. *
  3157. * @param writer The writer
  3158. * @param seconds The (signed) number of seconds since 1970-01-01T00:00:00Z.
  3159. * @param nanoseconds The additional number of nanoseconds from 0 to 999,999,999 inclusive.
  3160. */
  3161. void mpack_write_timestamp(mpack_writer_t* writer, int64_t seconds, uint32_t nanoseconds);
  3162. /**
  3163. * Writes a timestamp with the given number of seconds (and zero nanoseconds).
  3164. *
  3165. * @note This requires @ref MPACK_EXTENSIONS.
  3166. *
  3167. * @param writer The writer
  3168. * @param seconds The (signed) number of seconds since 1970-01-01T00:00:00Z.
  3169. */
  3170. MPACK_INLINE void mpack_write_timestamp_seconds(mpack_writer_t* writer, int64_t seconds) {
  3171. mpack_write_timestamp(writer, seconds, 0);
  3172. }
  3173. /**
  3174. * Writes a timestamp.
  3175. *
  3176. * @note This requires @ref MPACK_EXTENSIONS.
  3177. */
  3178. MPACK_INLINE void mpack_write_timestamp_struct(mpack_writer_t* writer, mpack_timestamp_t timestamp) {
  3179. mpack_write_timestamp(writer, timestamp.seconds, timestamp.nanoseconds);
  3180. }
  3181. #endif
  3182. /**
  3183. * @}
  3184. */
  3185. /**
  3186. * @name Map and Array Functions
  3187. * @{
  3188. */
  3189. /**
  3190. * Opens an array.
  3191. *
  3192. * `count` elements must follow, and mpack_finish_array() must be called
  3193. * when done.
  3194. *
  3195. * If you do not know the number of elements to be written ahead of time, call
  3196. * mpack_build_array() instead.
  3197. *
  3198. * @see mpack_finish_array()
  3199. * @see mpack_build_array() to count the number of elements automatically
  3200. */
  3201. void mpack_start_array(mpack_writer_t* writer, uint32_t count);
  3202. /**
  3203. * Opens a map.
  3204. *
  3205. * `count * 2` elements must follow, and mpack_finish_map() must be called
  3206. * when done.
  3207. *
  3208. * If you do not know the number of elements to be written ahead of time, call
  3209. * mpack_build_map() instead.
  3210. *
  3211. * Remember that while map elements in MessagePack are implicitly ordered,
  3212. * they are not ordered in JSON. If you need elements to be read back
  3213. * in the order they are written, consider use an array instead.
  3214. *
  3215. * @see mpack_finish_map()
  3216. * @see mpack_build_map() to count the number of key/value pairs automatically
  3217. */
  3218. void mpack_start_map(mpack_writer_t* writer, uint32_t count);
  3219. MPACK_INLINE void mpack_builder_compound_push(mpack_writer_t* writer) {
  3220. MPACK_UNUSED(writer);
  3221. #if MPACK_BUILDER
  3222. mpack_build_t* build = writer->builder.current_build;
  3223. if (build != NULL) {
  3224. ++build->nested_compound_elements;
  3225. }
  3226. #endif
  3227. }
  3228. MPACK_INLINE void mpack_builder_compound_pop(mpack_writer_t* writer) {
  3229. MPACK_UNUSED(writer);
  3230. #if MPACK_BUILDER
  3231. mpack_build_t* build = writer->builder.current_build;
  3232. if (build != NULL) {
  3233. mpack_assert(build->nested_compound_elements > 0);
  3234. --build->nested_compound_elements;
  3235. }
  3236. #endif
  3237. }
  3238. /**
  3239. * Finishes writing an array.
  3240. *
  3241. * This should be called only after a corresponding call to mpack_start_array()
  3242. * and after the array contents are written.
  3243. *
  3244. * In debug mode (or if MPACK_WRITE_TRACKING is not 0), this will track writes
  3245. * to ensure that the correct number of elements are written.
  3246. *
  3247. * @see mpack_start_array()
  3248. */
  3249. MPACK_INLINE void mpack_finish_array(mpack_writer_t* writer) {
  3250. mpack_writer_track_pop(writer, mpack_type_array);
  3251. mpack_builder_compound_pop(writer);
  3252. }
  3253. /**
  3254. * Finishes writing a map.
  3255. *
  3256. * This should be called only after a corresponding call to mpack_start_map()
  3257. * and after the map contents are written.
  3258. *
  3259. * In debug mode (or if MPACK_WRITE_TRACKING is not 0), this will track writes
  3260. * to ensure that the correct number of elements are written.
  3261. *
  3262. * @see mpack_start_map()
  3263. */
  3264. MPACK_INLINE void mpack_finish_map(mpack_writer_t* writer) {
  3265. mpack_writer_track_pop(writer, mpack_type_map);
  3266. mpack_builder_compound_pop(writer);
  3267. }
  3268. /**
  3269. * Starts building an array.
  3270. *
  3271. * Elements must follow, and mpack_complete_array() must be called when done. The
  3272. * number of elements is determined automatically.
  3273. *
  3274. * If you know ahead of time the number of elements in the array, it is more
  3275. * efficient to call mpack_start_array() instead, even if you are already
  3276. * within another open build.
  3277. *
  3278. * Builder containers can be nested within normal (known size) containers and
  3279. * vice versa. You can call mpack_build_array(), then mpack_start_array()
  3280. * inside it, then mpack_build_array() inside that, and so forth.
  3281. *
  3282. * @see mpack_complete_array() to complete this array
  3283. * @see mpack_start_array() if you already know the size of the array
  3284. * @see mpack_build_map() for implementation details
  3285. */
  3286. void mpack_build_array(struct mpack_writer_t* writer);
  3287. /**
  3288. * Starts building a map.
  3289. *
  3290. * An even number of elements must follow, and mpack_complete_map() must be
  3291. * called when done. The number of elements is determined automatically.
  3292. *
  3293. * If you know ahead of time the number of elements in the map, it is more
  3294. * efficient to call mpack_start_map() instead, even if you are already within
  3295. * another open build.
  3296. *
  3297. * Builder containers can be nested within normal (known size) containers and
  3298. * vice versa. You can call mpack_build_map(), then mpack_start_map() inside
  3299. * it, then mpack_build_map() inside that, and so forth.
  3300. *
  3301. * A writer in build mode diverts writes to a builder buffer that allocates as
  3302. * needed. Once the last map or array being built is completed, the deferred
  3303. * message is composed with computed array and map sizes into the writer.
  3304. * Builder maps and arrays are encoded exactly the same as ordinary maps and
  3305. * arrays in the final message.
  3306. *
  3307. * This indirect encoding is costly, as it incurs at least an extra copy of all
  3308. * data written within a builder (but not additional copies for nested
  3309. * builders.) Expect a speed penalty of half or more.
  3310. *
  3311. * A good strategy is to use this during early development when your messages
  3312. * are constantly changing, and then closer to release when your message
  3313. * formats have stabilized, replace all your build calls with start calls with
  3314. * pre-computed sizes. Or don't, if you find the builder has little impact on
  3315. * performance, because even with builders MPack is extremely fast.
  3316. *
  3317. * @note When an array or map starts being built, nothing will be flushed
  3318. * until it is completed. If you are building a large message that
  3319. * does not fit in the output stream, you won't get an error about it
  3320. * until everything is written.
  3321. *
  3322. * @see mpack_complete_map() to complete this map
  3323. * @see mpack_start_map() if you already know the size of the map
  3324. */
  3325. void mpack_build_map(struct mpack_writer_t* writer);
  3326. /**
  3327. * Completes an array being built.
  3328. *
  3329. * @see mpack_build_array()
  3330. */
  3331. void mpack_complete_array(struct mpack_writer_t* writer);
  3332. /**
  3333. * Completes a map being built.
  3334. *
  3335. * @see mpack_build_map()
  3336. */
  3337. void mpack_complete_map(struct mpack_writer_t* writer);
  3338. /**
  3339. * @}
  3340. */
  3341. /**
  3342. * @name Data Helpers
  3343. * @{
  3344. */
  3345. /**
  3346. * Writes a string.
  3347. *
  3348. * To stream a string in chunks, use mpack_start_str() instead.
  3349. *
  3350. * MPack does not care about the underlying encoding, but UTF-8 is highly
  3351. * recommended, especially for compatibility with JSON. You should consider
  3352. * calling mpack_write_utf8() instead, especially if you will be reading
  3353. * it back as UTF-8.
  3354. *
  3355. * You should not call mpack_finish_str() after calling this; this
  3356. * performs both start and finish.
  3357. */
  3358. void mpack_write_str(mpack_writer_t* writer, const char* str, uint32_t length);
  3359. /**
  3360. * Writes a string, ensuring that it is valid UTF-8.
  3361. *
  3362. * This does not accept any UTF-8 variant such as Modified UTF-8, CESU-8 or
  3363. * WTF-8. Only pure UTF-8 is allowed.
  3364. *
  3365. * You should not call mpack_finish_str() after calling this; this
  3366. * performs both start and finish.
  3367. *
  3368. * @throws mpack_error_invalid if the string is not valid UTF-8
  3369. */
  3370. void mpack_write_utf8(mpack_writer_t* writer, const char* str, uint32_t length);
  3371. /**
  3372. * Writes a null-terminated string. (The null-terminator is not written.)
  3373. *
  3374. * MPack does not care about the underlying encoding, but UTF-8 is highly
  3375. * recommended, especially for compatibility with JSON. You should consider
  3376. * calling mpack_write_utf8_cstr() instead, especially if you will be reading
  3377. * it back as UTF-8.
  3378. *
  3379. * You should not call mpack_finish_str() after calling this; this
  3380. * performs both start and finish.
  3381. */
  3382. void mpack_write_cstr(mpack_writer_t* writer, const char* cstr);
  3383. /**
  3384. * Writes a null-terminated string, or a nil node if the given cstr pointer
  3385. * is NULL. (The null-terminator is not written.)
  3386. *
  3387. * MPack does not care about the underlying encoding, but UTF-8 is highly
  3388. * recommended, especially for compatibility with JSON. You should consider
  3389. * calling mpack_write_utf8_cstr_or_nil() instead, especially if you will
  3390. * be reading it back as UTF-8.
  3391. *
  3392. * You should not call mpack_finish_str() after calling this; this
  3393. * performs both start and finish.
  3394. */
  3395. void mpack_write_cstr_or_nil(mpack_writer_t* writer, const char* cstr);
  3396. /**
  3397. * Writes a null-terminated string, ensuring that it is valid UTF-8. (The
  3398. * null-terminator is not written.)
  3399. *
  3400. * This does not accept any UTF-8 variant such as Modified UTF-8, CESU-8 or
  3401. * WTF-8. Only pure UTF-8 is allowed.
  3402. *
  3403. * You should not call mpack_finish_str() after calling this; this
  3404. * performs both start and finish.
  3405. *
  3406. * @throws mpack_error_invalid if the string is not valid UTF-8
  3407. */
  3408. void mpack_write_utf8_cstr(mpack_writer_t* writer, const char* cstr);
  3409. /**
  3410. * Writes a null-terminated string ensuring that it is valid UTF-8, or
  3411. * writes nil if the given cstr pointer is NULL. (The null-terminator
  3412. * is not written.)
  3413. *
  3414. * This does not accept any UTF-8 variant such as Modified UTF-8, CESU-8 or
  3415. * WTF-8. Only pure UTF-8 is allowed.
  3416. *
  3417. * You should not call mpack_finish_str() after calling this; this
  3418. * performs both start and finish.
  3419. *
  3420. * @throws mpack_error_invalid if the string is not valid UTF-8
  3421. */
  3422. void mpack_write_utf8_cstr_or_nil(mpack_writer_t* writer, const char* cstr);
  3423. /**
  3424. * Writes a binary blob.
  3425. *
  3426. * To stream a binary blob in chunks, use mpack_start_bin() instead.
  3427. *
  3428. * You should not call mpack_finish_bin() after calling this; this
  3429. * performs both start and finish.
  3430. */
  3431. void mpack_write_bin(mpack_writer_t* writer, const char* data, uint32_t count);
  3432. #if MPACK_EXTENSIONS
  3433. /**
  3434. * Writes an extension type.
  3435. *
  3436. * To stream an extension blob in chunks, use mpack_start_ext() instead.
  3437. *
  3438. * Extension types [0, 127] are available for application-specific types. Extension
  3439. * types [-128, -1] are reserved for future extensions of MessagePack.
  3440. *
  3441. * You should not call mpack_finish_ext() after calling this; this
  3442. * performs both start and finish.
  3443. *
  3444. * @note This requires @ref MPACK_EXTENSIONS.
  3445. */
  3446. void mpack_write_ext(mpack_writer_t* writer, int8_t exttype, const char* data, uint32_t count);
  3447. #endif
  3448. /**
  3449. * @}
  3450. */
  3451. /**
  3452. * @name Chunked Data Functions
  3453. * @{
  3454. */
  3455. /**
  3456. * Opens a string. `count` bytes should be written with calls to
  3457. * mpack_write_bytes(), and mpack_finish_str() should be called
  3458. * when done.
  3459. *
  3460. * To write an entire string at once, use mpack_write_str() or
  3461. * mpack_write_cstr() instead.
  3462. *
  3463. * MPack does not care about the underlying encoding, but UTF-8 is highly
  3464. * recommended, especially for compatibility with JSON.
  3465. */
  3466. void mpack_start_str(mpack_writer_t* writer, uint32_t count);
  3467. /**
  3468. * Opens a binary blob. `count` bytes should be written with calls to
  3469. * mpack_write_bytes(), and mpack_finish_bin() should be called
  3470. * when done.
  3471. */
  3472. void mpack_start_bin(mpack_writer_t* writer, uint32_t count);
  3473. #if MPACK_EXTENSIONS
  3474. /**
  3475. * Opens an extension type. `count` bytes should be written with calls
  3476. * to mpack_write_bytes(), and mpack_finish_ext() should be called
  3477. * when done.
  3478. *
  3479. * Extension types [0, 127] are available for application-specific types. Extension
  3480. * types [-128, -1] are reserved for future extensions of MessagePack.
  3481. *
  3482. * @note This requires @ref MPACK_EXTENSIONS.
  3483. */
  3484. void mpack_start_ext(mpack_writer_t* writer, int8_t exttype, uint32_t count);
  3485. #endif
  3486. /**
  3487. * Writes a portion of bytes for a string, binary blob or extension type which
  3488. * was opened by mpack_write_tag() or one of the mpack_start_*() functions.
  3489. *
  3490. * This can be called multiple times to write the data in chunks, as long as
  3491. * the total amount of bytes written matches the count given when the compound
  3492. * type was started.
  3493. *
  3494. * The corresponding mpack_finish_*() function must be called when done.
  3495. *
  3496. * To write an entire string, binary blob or extension type at
  3497. * once, use one of the mpack_write_*() functions instead.
  3498. *
  3499. * @see mpack_write_tag()
  3500. * @see mpack_start_str()
  3501. * @see mpack_start_bin()
  3502. * @see mpack_start_ext()
  3503. * @see mpack_finish_str()
  3504. * @see mpack_finish_bin()
  3505. * @see mpack_finish_ext()
  3506. * @see mpack_finish_type()
  3507. */
  3508. void mpack_write_bytes(mpack_writer_t* writer, const char* data, size_t count);
  3509. /**
  3510. * Finishes writing a string.
  3511. *
  3512. * This should be called only after a corresponding call to mpack_start_str()
  3513. * and after the string bytes are written with mpack_write_bytes().
  3514. *
  3515. * This will track writes to ensure that the correct number of elements are written.
  3516. *
  3517. * @see mpack_start_str()
  3518. * @see mpack_write_bytes()
  3519. */
  3520. MPACK_INLINE void mpack_finish_str(mpack_writer_t* writer) {
  3521. mpack_writer_track_pop(writer, mpack_type_str);
  3522. }
  3523. /**
  3524. * Finishes writing a binary blob.
  3525. *
  3526. * This should be called only after a corresponding call to mpack_start_bin()
  3527. * and after the binary bytes are written with mpack_write_bytes().
  3528. *
  3529. * This will track writes to ensure that the correct number of bytes are written.
  3530. *
  3531. * @see mpack_start_bin()
  3532. * @see mpack_write_bytes()
  3533. */
  3534. MPACK_INLINE void mpack_finish_bin(mpack_writer_t* writer) {
  3535. mpack_writer_track_pop(writer, mpack_type_bin);
  3536. }
  3537. #if MPACK_EXTENSIONS
  3538. /**
  3539. * Finishes writing an extended type binary data blob.
  3540. *
  3541. * This should be called only after a corresponding call to mpack_start_bin()
  3542. * and after the binary bytes are written with mpack_write_bytes().
  3543. *
  3544. * This will track writes to ensure that the correct number of bytes are written.
  3545. *
  3546. * @note This requires @ref MPACK_EXTENSIONS.
  3547. *
  3548. * @see mpack_start_ext()
  3549. * @see mpack_write_bytes()
  3550. */
  3551. MPACK_INLINE void mpack_finish_ext(mpack_writer_t* writer) {
  3552. mpack_writer_track_pop(writer, mpack_type_ext);
  3553. }
  3554. #endif
  3555. /**
  3556. * Finishes writing the given compound type.
  3557. *
  3558. * This will track writes to ensure that the correct number of elements
  3559. * or bytes are written.
  3560. *
  3561. * This can be called with the appropriate type instead the corresponding
  3562. * mpack_finish_*() function if you want to finish a dynamic type.
  3563. */
  3564. MPACK_INLINE void mpack_finish_type(mpack_writer_t* writer, mpack_type_t type) {
  3565. mpack_writer_track_pop(writer, type);
  3566. }
  3567. /**
  3568. * @}
  3569. */
  3570. #if MPACK_HAS_GENERIC && !defined(__cplusplus)
  3571. /**
  3572. * @name Type-Generic Writers
  3573. * @{
  3574. */
  3575. /**
  3576. * @def mpack_write(writer, value)
  3577. *
  3578. * Type-generic writer for primitive types.
  3579. *
  3580. * The compiler will dispatch to an appropriate write function based
  3581. * on the type of the @a value parameter.
  3582. *
  3583. * @note This requires C11 `_Generic` support. (A set of inline overloads
  3584. * are used in C++ to provide the same functionality.)
  3585. *
  3586. * @warning In C11, the indentifiers `true`, `false` and `NULL` are
  3587. * all of type `int`, not `bool` or `void*`! They will emit unexpected
  3588. * types when passed uncast, so be careful when using them.
  3589. */
  3590. #if MPACK_FLOAT
  3591. #define MPACK_WRITE_GENERIC_FLOAT float: mpack_write_float,
  3592. #else
  3593. #define MPACK_WRITE_GENERIC_FLOAT /*nothing*/
  3594. #endif
  3595. #if MPACK_DOUBLE
  3596. #define MPACK_WRITE_GENERIC_DOUBLE double: mpack_write_double,
  3597. #else
  3598. #define MPACK_WRITE_GENERIC_DOUBLE /*nothing*/
  3599. #endif
  3600. #define mpack_write(writer, value) \
  3601. _Generic(((void)0, value), \
  3602. int8_t: mpack_write_i8, \
  3603. int16_t: mpack_write_i16, \
  3604. int32_t: mpack_write_i32, \
  3605. int64_t: mpack_write_i64, \
  3606. uint8_t: mpack_write_u8, \
  3607. uint16_t: mpack_write_u16, \
  3608. uint32_t: mpack_write_u32, \
  3609. uint64_t: mpack_write_u64, \
  3610. bool: mpack_write_bool, \
  3611. MPACK_WRITE_GENERIC_FLOAT \
  3612. MPACK_WRITE_GENERIC_DOUBLE \
  3613. char *: mpack_write_cstr_or_nil, \
  3614. const char *: mpack_write_cstr_or_nil \
  3615. )(writer, value)
  3616. /**
  3617. * @def mpack_write_kv(writer, key, value)
  3618. *
  3619. * Type-generic writer for key-value pairs of null-terminated string
  3620. * keys and primitive values.
  3621. *
  3622. * @warning @a writer may be evaluated multiple times.
  3623. *
  3624. * @warning In C11, the indentifiers `true`, `false` and `NULL` are
  3625. * all of type `int`, not `bool` or `void*`! They will emit unexpected
  3626. * types when passed uncast, so be careful when using them.
  3627. *
  3628. * @param writer The writer.
  3629. * @param key A null-terminated C string.
  3630. * @param value A primitive type supported by mpack_write().
  3631. */
  3632. #define mpack_write_kv(writer, key, value) do { \
  3633. mpack_write_cstr(writer, key); \
  3634. mpack_write(writer, value); \
  3635. } while (0)
  3636. /**
  3637. * @}
  3638. */
  3639. #endif // MPACK_HAS_GENERIC && !defined(__cplusplus)
  3640. // The rest of this file contains C++ overloads, so we end extern "C" here.
  3641. MPACK_EXTERN_C_END
  3642. #if defined(__cplusplus) || defined(MPACK_DOXYGEN)
  3643. /**
  3644. * @name C++ write overloads
  3645. * @{
  3646. */
  3647. /*
  3648. * C++ generic writers for primitive values
  3649. */
  3650. #ifdef MPACK_DOXYGEN
  3651. #undef mpack_write
  3652. #undef mpack_write_kv
  3653. #endif
  3654. MPACK_INLINE void mpack_write(mpack_writer_t* writer, int8_t value) {
  3655. mpack_write_i8(writer, value);
  3656. }
  3657. MPACK_INLINE void mpack_write(mpack_writer_t* writer, int16_t value) {
  3658. mpack_write_i16(writer, value);
  3659. }
  3660. MPACK_INLINE void mpack_write(mpack_writer_t* writer, int32_t value) {
  3661. mpack_write_i32(writer, value);
  3662. }
  3663. MPACK_INLINE void mpack_write(mpack_writer_t* writer, int64_t value) {
  3664. mpack_write_i64(writer, value);
  3665. }
  3666. MPACK_INLINE void mpack_write(mpack_writer_t* writer, uint8_t value) {
  3667. mpack_write_u8(writer, value);
  3668. }
  3669. MPACK_INLINE void mpack_write(mpack_writer_t* writer, uint16_t value) {
  3670. mpack_write_u16(writer, value);
  3671. }
  3672. MPACK_INLINE void mpack_write(mpack_writer_t* writer, uint32_t value) {
  3673. mpack_write_u32(writer, value);
  3674. }
  3675. MPACK_INLINE void mpack_write(mpack_writer_t* writer, uint64_t value) {
  3676. mpack_write_u64(writer, value);
  3677. }
  3678. MPACK_INLINE void mpack_write(mpack_writer_t* writer, bool value) {
  3679. mpack_write_bool(writer, value);
  3680. }
  3681. MPACK_INLINE void mpack_write(mpack_writer_t* writer, float value) {
  3682. mpack_write_float(writer, value);
  3683. }
  3684. MPACK_INLINE void mpack_write(mpack_writer_t* writer, double value) {
  3685. mpack_write_double(writer, value);
  3686. }
  3687. MPACK_INLINE void mpack_write(mpack_writer_t* writer, char *value) {
  3688. mpack_write_cstr_or_nil(writer, value);
  3689. }
  3690. MPACK_INLINE void mpack_write(mpack_writer_t* writer, const char *value) {
  3691. mpack_write_cstr_or_nil(writer, value);
  3692. }
  3693. /* C++ generic write for key-value pairs */
  3694. MPACK_INLINE void mpack_write_kv(mpack_writer_t* writer, const char *key, int8_t value) {
  3695. mpack_write_cstr(writer, key);
  3696. mpack_write_i8(writer, value);
  3697. }
  3698. MPACK_INLINE void mpack_write_kv(mpack_writer_t* writer, const char *key, int16_t value) {
  3699. mpack_write_cstr(writer, key);
  3700. mpack_write_i16(writer, value);
  3701. }
  3702. MPACK_INLINE void mpack_write_kv(mpack_writer_t* writer, const char *key, int32_t value) {
  3703. mpack_write_cstr(writer, key);
  3704. mpack_write_i32(writer, value);
  3705. }
  3706. MPACK_INLINE void mpack_write_kv(mpack_writer_t* writer, const char *key, int64_t value) {
  3707. mpack_write_cstr(writer, key);
  3708. mpack_write_i64(writer, value);
  3709. }
  3710. MPACK_INLINE void mpack_write_kv(mpack_writer_t* writer, const char *key, uint8_t value) {
  3711. mpack_write_cstr(writer, key);
  3712. mpack_write_u8(writer, value);
  3713. }
  3714. MPACK_INLINE void mpack_write_kv(mpack_writer_t* writer, const char *key, uint16_t value) {
  3715. mpack_write_cstr(writer, key);
  3716. mpack_write_u16(writer, value);
  3717. }
  3718. MPACK_INLINE void mpack_write_kv(mpack_writer_t* writer, const char *key, uint32_t value) {
  3719. mpack_write_cstr(writer, key);
  3720. mpack_write_u32(writer, value);
  3721. }
  3722. MPACK_INLINE void mpack_write_kv(mpack_writer_t* writer, const char *key, uint64_t value) {
  3723. mpack_write_cstr(writer, key);
  3724. mpack_write_u64(writer, value);
  3725. }
  3726. MPACK_INLINE void mpack_write_kv(mpack_writer_t* writer, const char *key, bool value) {
  3727. mpack_write_cstr(writer, key);
  3728. mpack_write_bool(writer, value);
  3729. }
  3730. MPACK_INLINE void mpack_write_kv(mpack_writer_t* writer, const char *key, float value) {
  3731. mpack_write_cstr(writer, key);
  3732. mpack_write_float(writer, value);
  3733. }
  3734. MPACK_INLINE void mpack_write_kv(mpack_writer_t* writer, const char *key, double value) {
  3735. mpack_write_cstr(writer, key);
  3736. mpack_write_double(writer, value);
  3737. }
  3738. MPACK_INLINE void mpack_write_kv(mpack_writer_t* writer, const char *key, char *value) {
  3739. mpack_write_cstr(writer, key);
  3740. mpack_write_cstr_or_nil(writer, value);
  3741. }
  3742. MPACK_INLINE void mpack_write_kv(mpack_writer_t* writer, const char *key, const char *value) {
  3743. mpack_write_cstr(writer, key);
  3744. mpack_write_cstr_or_nil(writer, value);
  3745. }
  3746. /**
  3747. * @}
  3748. */
  3749. #endif /* __cplusplus */
  3750. /**
  3751. * @}
  3752. */
  3753. MPACK_SILENCE_WARNINGS_END
  3754. #endif // MPACK_WRITER
  3755. #endif
  3756. /* mpack/mpack-reader.h.h */
  3757. /**
  3758. * @file
  3759. *
  3760. * Declares the core MPack Tag Reader.
  3761. */
  3762. #ifndef MPACK_READER_H
  3763. #define MPACK_READER_H 1
  3764. /* #include "mpack-common.h" */
  3765. MPACK_SILENCE_WARNINGS_BEGIN
  3766. MPACK_EXTERN_C_BEGIN
  3767. #if MPACK_READER
  3768. #if MPACK_READ_TRACKING
  3769. struct mpack_track_t;
  3770. #endif
  3771. // The denominator to determine whether a read is a small
  3772. // fraction of the buffer size.
  3773. #define MPACK_READER_SMALL_FRACTION_DENOMINATOR 32
  3774. /**
  3775. * @defgroup reader Reader API
  3776. *
  3777. * The MPack Reader API contains functions for imperatively reading dynamically
  3778. * typed data from a MessagePack stream.
  3779. *
  3780. * See @ref docs/reader.md for examples.
  3781. *
  3782. * @note If you are not writing code for an embedded device (or otherwise do
  3783. * not need maximum performance with minimal memory usage), you should not use
  3784. * this. You probably want to use the @link node Node API@endlink instead.
  3785. *
  3786. * This forms the basis of the @link expect Expect API@endlink, which can be
  3787. * used to interpret the stream of elements in expected types and value ranges.
  3788. *
  3789. * @{
  3790. */
  3791. /**
  3792. * @def MPACK_READER_MINIMUM_BUFFER_SIZE
  3793. *
  3794. * The minimum buffer size for a reader with a fill function.
  3795. */
  3796. #define MPACK_READER_MINIMUM_BUFFER_SIZE 32
  3797. /**
  3798. * A buffered MessagePack decoder.
  3799. *
  3800. * The decoder wraps an existing buffer and, optionally, a fill function.
  3801. * This allows efficiently decoding data from existing memory buffers, files,
  3802. * streams, etc.
  3803. *
  3804. * All read operations are synchronous; they will block until the
  3805. * requested data is fully read, or an error occurs.
  3806. *
  3807. * This structure is opaque; its fields should not be accessed outside
  3808. * of MPack.
  3809. */
  3810. typedef struct mpack_reader_t mpack_reader_t;
  3811. /**
  3812. * The MPack reader's fill function. It should fill the buffer with at
  3813. * least one byte and at most the given @c count, returning the number
  3814. * of bytes written to the buffer.
  3815. *
  3816. * In case of error, it should flag an appropriate error on the reader
  3817. * (usually @ref mpack_error_io), or simply return zero. If zero is
  3818. * returned, mpack_error_io is raised.
  3819. *
  3820. * @note When reading from a stream, you should only copy and return
  3821. * the bytes that are immediately available. It is always safe to return
  3822. * less than the requested count as long as some non-zero number of bytes
  3823. * are read; if more bytes are needed, the read function will simply be
  3824. * called again.
  3825. *
  3826. * @see mpack_reader_context()
  3827. */
  3828. typedef size_t (*mpack_reader_fill_t)(mpack_reader_t* reader, char* buffer, size_t count);
  3829. /**
  3830. * The MPack reader's skip function. It should discard the given number
  3831. * of bytes from the source (for example by seeking forward.)
  3832. *
  3833. * In case of error, it should flag an appropriate error on the reader.
  3834. *
  3835. * @see mpack_reader_context()
  3836. */
  3837. typedef void (*mpack_reader_skip_t)(mpack_reader_t* reader, size_t count);
  3838. /**
  3839. * An error handler function to be called when an error is flagged on
  3840. * the reader.
  3841. *
  3842. * The error handler will only be called once on the first error flagged;
  3843. * any subsequent reads and errors are ignored, and the reader is
  3844. * permanently in that error state.
  3845. *
  3846. * MPack is safe against non-local jumps out of error handler callbacks.
  3847. * This means you are allowed to longjmp or throw an exception (in C++,
  3848. * Objective-C, or with SEH) out of this callback.
  3849. *
  3850. * Bear in mind when using longjmp that local non-volatile variables that
  3851. * have changed are undefined when setjmp() returns, so you can't put the
  3852. * reader on the stack in the same activation frame as the setjmp without
  3853. * declaring it volatile.
  3854. *
  3855. * You must still eventually destroy the reader. It is not destroyed
  3856. * automatically when an error is flagged. It is safe to destroy the
  3857. * reader within this error callback, but you will either need to perform
  3858. * a non-local jump, or store something in your context to identify
  3859. * that the reader is destroyed since any future accesses to it cause
  3860. * undefined behavior.
  3861. */
  3862. typedef void (*mpack_reader_error_t)(mpack_reader_t* reader, mpack_error_t error);
  3863. /**
  3864. * A teardown function to be called when the reader is destroyed.
  3865. */
  3866. typedef void (*mpack_reader_teardown_t)(mpack_reader_t* reader);
  3867. /* Hide internals from documentation */
  3868. /** @cond */
  3869. struct mpack_reader_t {
  3870. void* context; /* Context for reader callbacks */
  3871. mpack_reader_fill_t fill; /* Function to read bytes into the buffer */
  3872. mpack_reader_error_t error_fn; /* Function to call on error */
  3873. mpack_reader_teardown_t teardown; /* Function to teardown the context on destroy */
  3874. mpack_reader_skip_t skip; /* Function to skip bytes from the source */
  3875. char* buffer; /* Writeable byte buffer */
  3876. size_t size; /* Size of the buffer */
  3877. const char* data; /* Current data pointer (in the buffer, if it is used) */
  3878. const char* end; /* The end of available data (in the buffer, if it is used) */
  3879. mpack_error_t error; /* Error state */
  3880. #if MPACK_READ_TRACKING
  3881. mpack_track_t track; /* Stack of map/array/str/bin/ext reads */
  3882. #endif
  3883. };
  3884. /** @endcond */
  3885. /**
  3886. * @name Lifecycle Functions
  3887. * @{
  3888. */
  3889. /**
  3890. * Initializes an MPack reader with the given buffer. The reader does
  3891. * not assume ownership of the buffer, but the buffer must be writeable
  3892. * if a fill function will be used to refill it.
  3893. *
  3894. * @param reader The MPack reader.
  3895. * @param buffer The buffer with which to read MessagePack data.
  3896. * @param size The size of the buffer.
  3897. * @param count The number of bytes already in the buffer.
  3898. */
  3899. void mpack_reader_init(mpack_reader_t* reader, char* buffer, size_t size, size_t count);
  3900. /**
  3901. * Initializes an MPack reader directly into an error state. Use this if you
  3902. * are writing a wrapper to mpack_reader_init() which can fail its setup.
  3903. */
  3904. void mpack_reader_init_error(mpack_reader_t* reader, mpack_error_t error);
  3905. /**
  3906. * Initializes an MPack reader to parse a pre-loaded contiguous chunk of data. The
  3907. * reader does not assume ownership of the data.
  3908. *
  3909. * @param reader The MPack reader.
  3910. * @param data The data to parse.
  3911. * @param count The number of bytes pointed to by data.
  3912. */
  3913. void mpack_reader_init_data(mpack_reader_t* reader, const char* data, size_t count);
  3914. #if MPACK_STDIO
  3915. /**
  3916. * Initializes an MPack reader that reads from a file.
  3917. *
  3918. * The file will be automatically opened and closed by the reader.
  3919. */
  3920. void mpack_reader_init_filename(mpack_reader_t* reader, const char* filename);
  3921. /**
  3922. * Deprecated.
  3923. *
  3924. * \deprecated Renamed to mpack_reader_init_filename().
  3925. */
  3926. MPACK_INLINE void mpack_reader_init_file(mpack_reader_t* reader, const char* filename) {
  3927. mpack_reader_init_filename(reader, filename);
  3928. }
  3929. /**
  3930. * Initializes an MPack reader that reads from a libc FILE. This can be used to
  3931. * read from stdin, or from a file opened separately.
  3932. *
  3933. * @param reader The MPack reader.
  3934. * @param stdfile The FILE.
  3935. * @param close_when_done If true, fclose() will be called on the FILE when it
  3936. * is no longer needed. If false, the file will not be closed when
  3937. * reading is done.
  3938. *
  3939. * @warning The reader is buffered. It will read data in advance of parsing it,
  3940. * and it may read more data than it parsed. See mpack_reader_remaining() to
  3941. * access the extra data.
  3942. */
  3943. void mpack_reader_init_stdfile(mpack_reader_t* reader, FILE* stdfile, bool close_when_done);
  3944. #endif
  3945. /**
  3946. * @def mpack_reader_init_stack(reader)
  3947. * @hideinitializer
  3948. *
  3949. * Initializes an MPack reader using stack space as a buffer. A fill function
  3950. * should be added to the reader to fill the buffer.
  3951. *
  3952. * @see mpack_reader_set_fill
  3953. */
  3954. /** @cond */
  3955. #define mpack_reader_init_stack_line_ex(line, reader) \
  3956. char mpack_buf_##line[MPACK_STACK_SIZE]; \
  3957. mpack_reader_init((reader), mpack_buf_##line, sizeof(mpack_buf_##line), 0)
  3958. #define mpack_reader_init_stack_line(line, reader) \
  3959. mpack_reader_init_stack_line_ex(line, reader)
  3960. /** @endcond */
  3961. #define mpack_reader_init_stack(reader) \
  3962. mpack_reader_init_stack_line(__LINE__, (reader))
  3963. /**
  3964. * Cleans up the MPack reader, ensuring that all compound elements
  3965. * have been completely read. Returns the final error state of the
  3966. * reader.
  3967. *
  3968. * This will assert in tracking mode if the reader is not in an error
  3969. * state and has any incomplete reads. If you want to cancel reading
  3970. * in the middle of a document, you need to flag an error on the reader
  3971. * before destroying it (such as mpack_error_data).
  3972. *
  3973. * @see mpack_read_tag()
  3974. * @see mpack_reader_flag_error()
  3975. * @see mpack_error_data
  3976. */
  3977. mpack_error_t mpack_reader_destroy(mpack_reader_t* reader);
  3978. /**
  3979. * @}
  3980. */
  3981. /**
  3982. * @name Callbacks
  3983. * @{
  3984. */
  3985. /**
  3986. * Sets the custom pointer to pass to the reader callbacks, such as fill
  3987. * or teardown.
  3988. *
  3989. * @param reader The MPack reader.
  3990. * @param context User data to pass to the reader callbacks.
  3991. *
  3992. * @see mpack_reader_context()
  3993. */
  3994. MPACK_INLINE void mpack_reader_set_context(mpack_reader_t* reader, void* context) {
  3995. reader->context = context;
  3996. }
  3997. /**
  3998. * Returns the custom context for reader callbacks.
  3999. *
  4000. * @see mpack_reader_set_context
  4001. * @see mpack_reader_set_fill
  4002. * @see mpack_reader_set_skip
  4003. */
  4004. MPACK_INLINE void* mpack_reader_context(mpack_reader_t* reader) {
  4005. return reader->context;
  4006. }
  4007. /**
  4008. * Sets the fill function to refill the data buffer when it runs out of data.
  4009. *
  4010. * If no fill function is used, truncated MessagePack data results in
  4011. * mpack_error_invalid (since the buffer is assumed to contain a
  4012. * complete MessagePack object.)
  4013. *
  4014. * If a fill function is used, truncated MessagePack data usually
  4015. * results in mpack_error_io (since the fill function fails to get
  4016. * the missing data.)
  4017. *
  4018. * This should normally be used with mpack_reader_set_context() to register
  4019. * a custom pointer to pass to the fill function.
  4020. *
  4021. * @param reader The MPack reader.
  4022. * @param fill The function to fetch additional data into the buffer.
  4023. */
  4024. void mpack_reader_set_fill(mpack_reader_t* reader, mpack_reader_fill_t fill);
  4025. /**
  4026. * Sets the skip function to discard bytes from the source stream.
  4027. *
  4028. * It's not necessary to implement this function. If the stream is not
  4029. * seekable, don't set a skip callback. The reader will fall back to
  4030. * using the fill function instead.
  4031. *
  4032. * This should normally be used with mpack_reader_set_context() to register
  4033. * a custom pointer to pass to the skip function.
  4034. *
  4035. * The skip function is ignored in size-optimized builds to reduce code
  4036. * size. Data will be skipped with the fill function when necessary.
  4037. *
  4038. * @param reader The MPack reader.
  4039. * @param skip The function to discard bytes from the source stream.
  4040. */
  4041. void mpack_reader_set_skip(mpack_reader_t* reader, mpack_reader_skip_t skip);
  4042. /**
  4043. * Sets the error function to call when an error is flagged on the reader.
  4044. *
  4045. * This should normally be used with mpack_reader_set_context() to register
  4046. * a custom pointer to pass to the error function.
  4047. *
  4048. * See the definition of mpack_reader_error_t for more information about
  4049. * what you can do from an error callback.
  4050. *
  4051. * @see mpack_reader_error_t
  4052. * @param reader The MPack reader.
  4053. * @param error_fn The function to call when an error is flagged on the reader.
  4054. */
  4055. MPACK_INLINE void mpack_reader_set_error_handler(mpack_reader_t* reader, mpack_reader_error_t error_fn) {
  4056. reader->error_fn = error_fn;
  4057. }
  4058. /**
  4059. * Sets the teardown function to call when the reader is destroyed.
  4060. *
  4061. * This should normally be used with mpack_reader_set_context() to register
  4062. * a custom pointer to pass to the teardown function.
  4063. *
  4064. * @param reader The MPack reader.
  4065. * @param teardown The function to call when the reader is destroyed.
  4066. */
  4067. MPACK_INLINE void mpack_reader_set_teardown(mpack_reader_t* reader, mpack_reader_teardown_t teardown) {
  4068. reader->teardown = teardown;
  4069. }
  4070. /**
  4071. * @}
  4072. */
  4073. /**
  4074. * @name Core Reader Functions
  4075. * @{
  4076. */
  4077. /**
  4078. * Queries the error state of the MPack reader.
  4079. *
  4080. * If a reader is in an error state, you should discard all data since the
  4081. * last time the error flag was checked. The error flag cannot be cleared.
  4082. */
  4083. MPACK_INLINE mpack_error_t mpack_reader_error(mpack_reader_t* reader) {
  4084. return reader->error;
  4085. }
  4086. /**
  4087. * Places the reader in the given error state, calling the error callback if one
  4088. * is set.
  4089. *
  4090. * This allows you to externally flag errors, for example if you are validating
  4091. * data as you read it.
  4092. *
  4093. * If the reader is already in an error state, this call is ignored and no
  4094. * error callback is called.
  4095. */
  4096. void mpack_reader_flag_error(mpack_reader_t* reader, mpack_error_t error);
  4097. /**
  4098. * Places the reader in the given error state if the given error is not mpack_ok,
  4099. * returning the resulting error state of the reader.
  4100. *
  4101. * This allows you to externally flag errors, for example if you are validating
  4102. * data as you read it.
  4103. *
  4104. * If the given error is mpack_ok or if the reader is already in an error state,
  4105. * this call is ignored and the actual error state of the reader is returned.
  4106. */
  4107. MPACK_INLINE mpack_error_t mpack_reader_flag_if_error(mpack_reader_t* reader, mpack_error_t error) {
  4108. if (error != mpack_ok)
  4109. mpack_reader_flag_error(reader, error);
  4110. return mpack_reader_error(reader);
  4111. }
  4112. /**
  4113. * Returns bytes left in the reader's buffer.
  4114. *
  4115. * If you are done reading MessagePack data but there is other interesting data
  4116. * following it, the reader may have buffered too much data. The number of bytes
  4117. * remaining in the buffer and a pointer to the position of those bytes can be
  4118. * queried here.
  4119. *
  4120. * If you know the length of the MPack chunk beforehand, it's better to instead
  4121. * have your fill function limit the data it reads so that the reader does not
  4122. * have extra data. In this case you can simply check that this returns zero.
  4123. *
  4124. * Returns 0 if the reader is in an error state.
  4125. *
  4126. * @param reader The MPack reader from which to query remaining data.
  4127. * @param data [out] A pointer to the remaining data, or NULL.
  4128. * @return The number of bytes remaining in the buffer.
  4129. */
  4130. size_t mpack_reader_remaining(mpack_reader_t* reader, const char** data);
  4131. /**
  4132. * Reads a MessagePack object header (an MPack tag.)
  4133. *
  4134. * If an error occurs, the reader is placed in an error state and a
  4135. * nil tag is returned. If the reader is already in an error state,
  4136. * a nil tag is returned.
  4137. *
  4138. * If the type is compound (i.e. is a map, array, string, binary or
  4139. * extension type), additional reads are required to get the contained
  4140. * data, and the corresponding done function must be called when done.
  4141. *
  4142. * @note Maps in JSON are unordered, so it is recommended not to expect
  4143. * a specific ordering for your map values in case your data is converted
  4144. * to/from JSON.
  4145. *
  4146. * @see mpack_read_bytes()
  4147. * @see mpack_done_array()
  4148. * @see mpack_done_map()
  4149. * @see mpack_done_str()
  4150. * @see mpack_done_bin()
  4151. * @see mpack_done_ext()
  4152. */
  4153. mpack_tag_t mpack_read_tag(mpack_reader_t* reader);
  4154. /**
  4155. * Parses the next MessagePack object header (an MPack tag) without
  4156. * advancing the reader.
  4157. *
  4158. * If an error occurs, the reader is placed in an error state and a
  4159. * nil tag is returned. If the reader is already in an error state,
  4160. * a nil tag is returned.
  4161. *
  4162. * @note Maps in JSON are unordered, so it is recommended not to expect
  4163. * a specific ordering for your map values in case your data is converted
  4164. * to/from JSON.
  4165. *
  4166. * @see mpack_read_tag()
  4167. * @see mpack_discard()
  4168. */
  4169. mpack_tag_t mpack_peek_tag(mpack_reader_t* reader);
  4170. /**
  4171. * @}
  4172. */
  4173. /**
  4174. * @name String and Data Functions
  4175. * @{
  4176. */
  4177. /**
  4178. * Skips bytes from the underlying stream. This is used only to
  4179. * skip the contents of a string, binary blob or extension object.
  4180. */
  4181. void mpack_skip_bytes(mpack_reader_t* reader, size_t count);
  4182. /**
  4183. * Reads bytes from a string, binary blob or extension object, copying
  4184. * them into the given buffer.
  4185. *
  4186. * A str, bin or ext must have been opened by a call to mpack_read_tag()
  4187. * which yielded one of these types, or by a call to an expect function
  4188. * such as mpack_expect_str() or mpack_expect_bin().
  4189. *
  4190. * If an error occurs, the buffer contents are undefined.
  4191. *
  4192. * This can be called multiple times for a single str, bin or ext
  4193. * to read the data in chunks. The total data read must add up
  4194. * to the size of the object.
  4195. *
  4196. * @param reader The MPack reader
  4197. * @param p The buffer in which to copy the bytes
  4198. * @param count The number of bytes to read
  4199. */
  4200. void mpack_read_bytes(mpack_reader_t* reader, char* p, size_t count);
  4201. /**
  4202. * Reads bytes from a string, ensures that the string is valid UTF-8,
  4203. * and copies the bytes into the given buffer.
  4204. *
  4205. * A string must have been opened by a call to mpack_read_tag() which
  4206. * yielded a string, or by a call to an expect function such as
  4207. * mpack_expect_str().
  4208. *
  4209. * The given byte count must match the complete size of the string as
  4210. * returned by the tag or expect function. You must ensure that the
  4211. * buffer fits the data.
  4212. *
  4213. * This does not accept any UTF-8 variant such as Modified UTF-8, CESU-8 or
  4214. * WTF-8. Only pure UTF-8 is allowed.
  4215. *
  4216. * If an error occurs, the buffer contents are undefined.
  4217. *
  4218. * Unlike mpack_read_bytes(), this cannot be used to read the data in
  4219. * chunks (since this might split a character's UTF-8 bytes, and the
  4220. * reader does not keep track of the UTF-8 decoding state between reads.)
  4221. *
  4222. * @throws mpack_error_type if the string contains invalid UTF-8.
  4223. */
  4224. void mpack_read_utf8(mpack_reader_t* reader, char* p, size_t byte_count);
  4225. /**
  4226. * Reads bytes from a string, ensures that the string contains no NUL
  4227. * bytes, copies the bytes into the given buffer and adds a null-terminator.
  4228. *
  4229. * A string must have been opened by a call to mpack_read_tag() which
  4230. * yielded a string, or by a call to an expect function such as
  4231. * mpack_expect_str().
  4232. *
  4233. * The given byte count must match the size of the string as returned
  4234. * by the tag or expect function. The string will only be copied if
  4235. * the buffer is large enough to store it.
  4236. *
  4237. * If an error occurs, the buffer will contain an empty string.
  4238. *
  4239. * @note If you know the object will be a string before reading it,
  4240. * it is highly recommended to use mpack_expect_cstr() instead.
  4241. * Alternatively you could use mpack_peek_tag() and call
  4242. * mpack_expect_cstr() if it's a string.
  4243. *
  4244. * @throws mpack_error_too_big if the string plus null-terminator is larger than the given buffer size
  4245. * @throws mpack_error_type if the string contains a null byte.
  4246. *
  4247. * @see mpack_peek_tag()
  4248. * @see mpack_expect_cstr()
  4249. * @see mpack_expect_utf8_cstr()
  4250. */
  4251. void mpack_read_cstr(mpack_reader_t* reader, char* buf, size_t buffer_size, size_t byte_count);
  4252. /**
  4253. * Reads bytes from a string, ensures that the string is valid UTF-8
  4254. * with no NUL bytes, copies the bytes into the given buffer and adds a
  4255. * null-terminator.
  4256. *
  4257. * A string must have been opened by a call to mpack_read_tag() which
  4258. * yielded a string, or by a call to an expect function such as
  4259. * mpack_expect_str().
  4260. *
  4261. * The given byte count must match the size of the string as returned
  4262. * by the tag or expect function. The string will only be copied if
  4263. * the buffer is large enough to store it.
  4264. *
  4265. * This does not accept any UTF-8 variant such as Modified UTF-8, CESU-8 or
  4266. * WTF-8. Only pure UTF-8 is allowed, but without the NUL character, since
  4267. * it cannot be represented in a null-terminated string.
  4268. *
  4269. * If an error occurs, the buffer will contain an empty string.
  4270. *
  4271. * @note If you know the object will be a string before reading it,
  4272. * it is highly recommended to use mpack_expect_utf8_cstr() instead.
  4273. * Alternatively you could use mpack_peek_tag() and call
  4274. * mpack_expect_utf8_cstr() if it's a string.
  4275. *
  4276. * @throws mpack_error_too_big if the string plus null-terminator is larger than the given buffer size
  4277. * @throws mpack_error_type if the string contains invalid UTF-8 or a null byte.
  4278. *
  4279. * @see mpack_peek_tag()
  4280. * @see mpack_expect_utf8_cstr()
  4281. */
  4282. void mpack_read_utf8_cstr(mpack_reader_t* reader, char* buf, size_t buffer_size, size_t byte_count);
  4283. #ifdef MPACK_MALLOC
  4284. /** @cond */
  4285. // This can optionally add a null-terminator, but it does not check
  4286. // whether the data contains null bytes. This must be done separately
  4287. // in a cstring read function (possibly as part of a UTF-8 check.)
  4288. char* mpack_read_bytes_alloc_impl(mpack_reader_t* reader, size_t count, bool null_terminated);
  4289. /** @endcond */
  4290. /**
  4291. * Reads bytes from a string, binary blob or extension object, allocating
  4292. * storage for them and returning the allocated pointer.
  4293. *
  4294. * The allocated string must be freed with MPACK_FREE() (or simply free()
  4295. * if MPack's allocator hasn't been customized.)
  4296. *
  4297. * Returns NULL if any error occurs, or if count is zero.
  4298. */
  4299. MPACK_INLINE char* mpack_read_bytes_alloc(mpack_reader_t* reader, size_t count) {
  4300. return mpack_read_bytes_alloc_impl(reader, count, false);
  4301. }
  4302. #endif
  4303. /**
  4304. * Reads bytes from a string, binary blob or extension object in-place in
  4305. * the buffer. This can be used to avoid copying the data.
  4306. *
  4307. * A str, bin or ext must have been opened by a call to mpack_read_tag()
  4308. * which yielded one of these types, or by a call to an expect function
  4309. * such as mpack_expect_str() or mpack_expect_bin().
  4310. *
  4311. * If the bytes are from a string, the string is not null-terminated! Use
  4312. * mpack_read_cstr() to copy the string into a buffer and add a null-terminator.
  4313. *
  4314. * The returned pointer is invalidated on the next read, or when the buffer
  4315. * is destroyed.
  4316. *
  4317. * The reader will move data around in the buffer if needed to ensure that
  4318. * the pointer can always be returned, so this should only be used if
  4319. * count is very small compared to the buffer size. If you need to check
  4320. * whether a small size is reasonable (for example you intend to handle small and
  4321. * large sizes differently), you can call mpack_should_read_bytes_inplace().
  4322. *
  4323. * This can be called multiple times for a single str, bin or ext
  4324. * to read the data in chunks. The total data read must add up
  4325. * to the size of the object.
  4326. *
  4327. * NULL is returned if the reader is in an error state.
  4328. *
  4329. * @throws mpack_error_too_big if the requested size is larger than the buffer size
  4330. *
  4331. * @see mpack_should_read_bytes_inplace()
  4332. */
  4333. const char* mpack_read_bytes_inplace(mpack_reader_t* reader, size_t count);
  4334. /**
  4335. * Reads bytes from a string in-place in the buffer and ensures they are
  4336. * valid UTF-8. This can be used to avoid copying the data.
  4337. *
  4338. * A string must have been opened by a call to mpack_read_tag() which
  4339. * yielded a string, or by a call to an expect function such as
  4340. * mpack_expect_str().
  4341. *
  4342. * The string is not null-terminated! Use mpack_read_utf8_cstr() to
  4343. * copy the string into a buffer and add a null-terminator.
  4344. *
  4345. * The returned pointer is invalidated on the next read, or when the buffer
  4346. * is destroyed.
  4347. *
  4348. * The reader will move data around in the buffer if needed to ensure that
  4349. * the pointer can always be returned, so this should only be used if
  4350. * count is very small compared to the buffer size. If you need to check
  4351. * whether a small size is reasonable (for example you intend to handle small and
  4352. * large sizes differently), you can call mpack_should_read_bytes_inplace().
  4353. *
  4354. * This does not accept any UTF-8 variant such as Modified UTF-8, CESU-8 or
  4355. * WTF-8. Only pure UTF-8 is allowed.
  4356. *
  4357. * Unlike mpack_read_bytes_inplace(), this cannot be used to read the data in
  4358. * chunks (since this might split a character's UTF-8 bytes, and the
  4359. * reader does not keep track of the UTF-8 decoding state between reads.)
  4360. *
  4361. * NULL is returned if the reader is in an error state.
  4362. *
  4363. * @throws mpack_error_type if the string contains invalid UTF-8
  4364. * @throws mpack_error_too_big if the requested size is larger than the buffer size
  4365. *
  4366. * @see mpack_should_read_bytes_inplace()
  4367. */
  4368. const char* mpack_read_utf8_inplace(mpack_reader_t* reader, size_t count);
  4369. /**
  4370. * Returns true if it's a good idea to read the given number of bytes
  4371. * in-place.
  4372. *
  4373. * If the read will be larger than some small fraction of the buffer size,
  4374. * this will return false to avoid shuffling too much data back and forth
  4375. * in the buffer.
  4376. *
  4377. * Use this if you're expecting arbitrary size data, and you want to read
  4378. * in-place for the best performance when possible but will fall back to
  4379. * a normal read if the data is too large.
  4380. *
  4381. * @see mpack_read_bytes_inplace()
  4382. */
  4383. MPACK_INLINE bool mpack_should_read_bytes_inplace(mpack_reader_t* reader, size_t count) {
  4384. return (reader->size == 0 || count <= reader->size / MPACK_READER_SMALL_FRACTION_DENOMINATOR);
  4385. }
  4386. #if MPACK_EXTENSIONS
  4387. /**
  4388. * Reads a timestamp contained in an ext object of the given size, closing the
  4389. * ext type.
  4390. *
  4391. * An ext object of exttype @ref MPACK_EXTTYPE_TIMESTAMP must have been opened
  4392. * by a call to e.g. mpack_read_tag() or mpack_expect_ext().
  4393. *
  4394. * You must NOT call mpack_done_ext() after calling this. A timestamp ext
  4395. * object can only contain a single timestamp value, so this calls
  4396. * mpack_done_ext() automatically.
  4397. *
  4398. * @note This requires @ref MPACK_EXTENSIONS.
  4399. *
  4400. * @throws mpack_error_invalid if the size is not one of the supported
  4401. * timestamp sizes, or if the nanoseconds are out of range.
  4402. */
  4403. mpack_timestamp_t mpack_read_timestamp(mpack_reader_t* reader, size_t size);
  4404. #endif
  4405. /**
  4406. * @}
  4407. */
  4408. /**
  4409. * @name Core Reader Functions
  4410. * @{
  4411. */
  4412. #if MPACK_READ_TRACKING
  4413. /**
  4414. * Finishes reading the given type.
  4415. *
  4416. * This will track reads to ensure that the correct number of elements
  4417. * or bytes are read.
  4418. */
  4419. void mpack_done_type(mpack_reader_t* reader, mpack_type_t type);
  4420. #else
  4421. MPACK_INLINE void mpack_done_type(mpack_reader_t* reader, mpack_type_t type) {
  4422. MPACK_UNUSED(reader);
  4423. MPACK_UNUSED(type);
  4424. }
  4425. #endif
  4426. /**
  4427. * Finishes reading an array.
  4428. *
  4429. * This will track reads to ensure that the correct number of elements are read.
  4430. */
  4431. MPACK_INLINE void mpack_done_array(mpack_reader_t* reader) {
  4432. mpack_done_type(reader, mpack_type_array);
  4433. }
  4434. /**
  4435. * @fn mpack_done_map(mpack_reader_t* reader)
  4436. *
  4437. * Finishes reading a map.
  4438. *
  4439. * This will track reads to ensure that the correct number of elements are read.
  4440. */
  4441. MPACK_INLINE void mpack_done_map(mpack_reader_t* reader) {
  4442. mpack_done_type(reader, mpack_type_map);
  4443. }
  4444. /**
  4445. * @fn mpack_done_str(mpack_reader_t* reader)
  4446. *
  4447. * Finishes reading a string.
  4448. *
  4449. * This will track reads to ensure that the correct number of bytes are read.
  4450. */
  4451. MPACK_INLINE void mpack_done_str(mpack_reader_t* reader) {
  4452. mpack_done_type(reader, mpack_type_str);
  4453. }
  4454. /**
  4455. * @fn mpack_done_bin(mpack_reader_t* reader)
  4456. *
  4457. * Finishes reading a binary data blob.
  4458. *
  4459. * This will track reads to ensure that the correct number of bytes are read.
  4460. */
  4461. MPACK_INLINE void mpack_done_bin(mpack_reader_t* reader) {
  4462. mpack_done_type(reader, mpack_type_bin);
  4463. }
  4464. #if MPACK_EXTENSIONS
  4465. /**
  4466. * @fn mpack_done_ext(mpack_reader_t* reader)
  4467. *
  4468. * Finishes reading an extended type binary data blob.
  4469. *
  4470. * This will track reads to ensure that the correct number of bytes are read.
  4471. *
  4472. * @note This requires @ref MPACK_EXTENSIONS.
  4473. */
  4474. MPACK_INLINE void mpack_done_ext(mpack_reader_t* reader) {
  4475. mpack_done_type(reader, mpack_type_ext);
  4476. }
  4477. #endif
  4478. /**
  4479. * Reads and discards the next object. This will read and discard all
  4480. * contained data as well if it is a compound type.
  4481. */
  4482. void mpack_discard(mpack_reader_t* reader);
  4483. /**
  4484. * @}
  4485. */
  4486. /** @cond */
  4487. #if MPACK_DEBUG && MPACK_STDIO
  4488. /**
  4489. * @name Debugging Functions
  4490. * @{
  4491. */
  4492. /*
  4493. * Converts a blob of MessagePack to a pseudo-JSON string for debugging
  4494. * purposes, placing the result in the given buffer with a null-terminator.
  4495. *
  4496. * If the buffer does not have enough space, the result will be truncated (but
  4497. * it is guaranteed to be null-terminated.)
  4498. *
  4499. * This is only available in debug mode, and only if stdio is available (since
  4500. * it uses snprintf().) It's strictly for debugging purposes.
  4501. */
  4502. void mpack_print_data_to_buffer(const char* data, size_t data_size, char* buffer, size_t buffer_size);
  4503. /*
  4504. * Converts a node to pseudo-JSON for debugging purposes, calling the given
  4505. * callback as many times as is necessary to output the character data.
  4506. *
  4507. * No null-terminator or trailing newline will be written.
  4508. *
  4509. * This is only available in debug mode, and only if stdio is available (since
  4510. * it uses snprintf().) It's strictly for debugging purposes.
  4511. */
  4512. void mpack_print_data_to_callback(const char* data, size_t size, mpack_print_callback_t callback, void* context);
  4513. /*
  4514. * Converts a blob of MessagePack to pseudo-JSON for debugging purposes
  4515. * and pretty-prints it to the given file.
  4516. */
  4517. void mpack_print_data_to_file(const char* data, size_t len, FILE* file);
  4518. /*
  4519. * Converts a blob of MessagePack to pseudo-JSON for debugging purposes
  4520. * and pretty-prints it to stdout.
  4521. */
  4522. MPACK_INLINE void mpack_print_data_to_stdout(const char* data, size_t len) {
  4523. mpack_print_data_to_file(data, len, stdout);
  4524. }
  4525. /*
  4526. * Converts the MessagePack contained in the given `FILE*` to pseudo-JSON for
  4527. * debugging purposes, calling the given callback as many times as is necessary
  4528. * to output the character data.
  4529. */
  4530. void mpack_print_stdfile_to_callback(FILE* file, mpack_print_callback_t callback, void* context);
  4531. /*
  4532. * Deprecated.
  4533. *
  4534. * \deprecated Renamed to mpack_print_data_to_stdout().
  4535. */
  4536. MPACK_INLINE void mpack_print(const char* data, size_t len) {
  4537. mpack_print_data_to_stdout(data, len);
  4538. }
  4539. /**
  4540. * @}
  4541. */
  4542. #endif
  4543. /** @endcond */
  4544. /**
  4545. * @}
  4546. */
  4547. #if MPACK_INTERNAL
  4548. bool mpack_reader_ensure_straddle(mpack_reader_t* reader, size_t count);
  4549. /*
  4550. * Ensures there are at least @c count bytes left in the
  4551. * data, raising an error and returning false if more
  4552. * data cannot be made available.
  4553. */
  4554. MPACK_INLINE bool mpack_reader_ensure(mpack_reader_t* reader, size_t count) {
  4555. mpack_assert(count != 0, "cannot ensure zero bytes!");
  4556. mpack_assert(reader->error == mpack_ok, "reader cannot be in an error state!");
  4557. if (count <= (size_t)(reader->end - reader->data))
  4558. return true;
  4559. return mpack_reader_ensure_straddle(reader, count);
  4560. }
  4561. void mpack_read_native_straddle(mpack_reader_t* reader, char* p, size_t count);
  4562. // Reads count bytes into p, deferring to mpack_read_native_straddle() if more
  4563. // bytes are needed than are available in the buffer.
  4564. MPACK_INLINE void mpack_read_native(mpack_reader_t* reader, char* p, size_t count) {
  4565. mpack_assert(count == 0 || p != NULL, "data pointer for %i bytes is NULL", (int)count);
  4566. if (count > (size_t)(reader->end - reader->data)) {
  4567. mpack_read_native_straddle(reader, p, count);
  4568. } else {
  4569. mpack_memcpy(p, reader->data, count);
  4570. reader->data += count;
  4571. }
  4572. }
  4573. #if MPACK_READ_TRACKING
  4574. #define MPACK_READER_TRACK(reader, error_expr) \
  4575. (((reader)->error == mpack_ok) ? mpack_reader_flag_if_error((reader), (error_expr)) : (reader)->error)
  4576. #else
  4577. #define MPACK_READER_TRACK(reader, error_expr) (MPACK_UNUSED(reader), mpack_ok)
  4578. #endif
  4579. MPACK_INLINE mpack_error_t mpack_reader_track_element(mpack_reader_t* reader) {
  4580. return MPACK_READER_TRACK(reader, mpack_track_element(&reader->track, true));
  4581. }
  4582. MPACK_INLINE mpack_error_t mpack_reader_track_peek_element(mpack_reader_t* reader) {
  4583. return MPACK_READER_TRACK(reader, mpack_track_peek_element(&reader->track, true));
  4584. }
  4585. MPACK_INLINE mpack_error_t mpack_reader_track_bytes(mpack_reader_t* reader, size_t count) {
  4586. MPACK_UNUSED(count);
  4587. return MPACK_READER_TRACK(reader, mpack_track_bytes(&reader->track, true, count));
  4588. }
  4589. MPACK_INLINE mpack_error_t mpack_reader_track_str_bytes_all(mpack_reader_t* reader, size_t count) {
  4590. MPACK_UNUSED(count);
  4591. return MPACK_READER_TRACK(reader, mpack_track_str_bytes_all(&reader->track, true, count));
  4592. }
  4593. #endif
  4594. #endif
  4595. MPACK_EXTERN_C_END
  4596. MPACK_SILENCE_WARNINGS_END
  4597. #endif
  4598. /* mpack/mpack-expect.h.h */
  4599. /**
  4600. * @file
  4601. *
  4602. * Declares the MPack static Expect API.
  4603. */
  4604. #ifndef MPACK_EXPECT_H
  4605. #define MPACK_EXPECT_H 1
  4606. /* #include "mpack-reader.h" */
  4607. MPACK_SILENCE_WARNINGS_BEGIN
  4608. MPACK_EXTERN_C_BEGIN
  4609. #if MPACK_EXPECT
  4610. #if !MPACK_READER
  4611. #error "MPACK_EXPECT requires MPACK_READER."
  4612. #endif
  4613. /**
  4614. * @defgroup expect Expect API
  4615. *
  4616. * The MPack Expect API allows you to easily read MessagePack data when you
  4617. * expect it to follow a predefined schema.
  4618. *
  4619. * @note If you are not writing code for an embedded device (or otherwise do
  4620. * not need maximum performance with minimal memory usage), you should not use
  4621. * this. You probably want to use the @link node Node API@endlink instead.
  4622. *
  4623. * See @ref docs/expect.md for examples.
  4624. *
  4625. * The main purpose of the Expect API is convenience, so the API is lax. It
  4626. * automatically converts between similar types where there is no loss of
  4627. * precision.
  4628. *
  4629. * When using any of the expect functions, if the type or value of what was
  4630. * read does not match what is expected, @ref mpack_error_type is raised.
  4631. *
  4632. * @{
  4633. */
  4634. /**
  4635. * @name Basic Number Functions
  4636. * @{
  4637. */
  4638. /**
  4639. * Reads an 8-bit unsigned integer.
  4640. *
  4641. * The underlying type may be an integer type of any size and signedness,
  4642. * as long as the value can be represented in an 8-bit unsigned int.
  4643. *
  4644. * Returns zero if an error occurs.
  4645. */
  4646. uint8_t mpack_expect_u8(mpack_reader_t* reader);
  4647. /**
  4648. * Reads a 16-bit unsigned integer.
  4649. *
  4650. * The underlying type may be an integer type of any size and signedness,
  4651. * as long as the value can be represented in a 16-bit unsigned int.
  4652. *
  4653. * Returns zero if an error occurs.
  4654. */
  4655. uint16_t mpack_expect_u16(mpack_reader_t* reader);
  4656. /**
  4657. * Reads a 32-bit unsigned integer.
  4658. *
  4659. * The underlying type may be an integer type of any size and signedness,
  4660. * as long as the value can be represented in a 32-bit unsigned int.
  4661. *
  4662. * Returns zero if an error occurs.
  4663. */
  4664. uint32_t mpack_expect_u32(mpack_reader_t* reader);
  4665. /**
  4666. * Reads a 64-bit unsigned integer.
  4667. *
  4668. * The underlying type may be an integer type of any size and signedness,
  4669. * as long as the value can be represented in a 64-bit unsigned int.
  4670. *
  4671. * Returns zero if an error occurs.
  4672. */
  4673. uint64_t mpack_expect_u64(mpack_reader_t* reader);
  4674. /**
  4675. * Reads an 8-bit signed integer.
  4676. *
  4677. * The underlying type may be an integer type of any size and signedness,
  4678. * as long as the value can be represented in an 8-bit signed int.
  4679. *
  4680. * Returns zero if an error occurs.
  4681. */
  4682. int8_t mpack_expect_i8(mpack_reader_t* reader);
  4683. /**
  4684. * Reads a 16-bit signed integer.
  4685. *
  4686. * The underlying type may be an integer type of any size and signedness,
  4687. * as long as the value can be represented in a 16-bit signed int.
  4688. *
  4689. * Returns zero if an error occurs.
  4690. */
  4691. int16_t mpack_expect_i16(mpack_reader_t* reader);
  4692. /**
  4693. * Reads a 32-bit signed integer.
  4694. *
  4695. * The underlying type may be an integer type of any size and signedness,
  4696. * as long as the value can be represented in a 32-bit signed int.
  4697. *
  4698. * Returns zero if an error occurs.
  4699. */
  4700. int32_t mpack_expect_i32(mpack_reader_t* reader);
  4701. /**
  4702. * Reads a 64-bit signed integer.
  4703. *
  4704. * The underlying type may be an integer type of any size and signedness,
  4705. * as long as the value can be represented in a 64-bit signed int.
  4706. *
  4707. * Returns zero if an error occurs.
  4708. */
  4709. int64_t mpack_expect_i64(mpack_reader_t* reader);
  4710. #if MPACK_FLOAT
  4711. /**
  4712. * Reads a number, returning the value as a float. The underlying value can be an
  4713. * integer, float or double; the value is converted to a float.
  4714. *
  4715. * @note Reading a double or a large integer with this function can incur a
  4716. * loss of precision.
  4717. *
  4718. * @throws mpack_error_type if the underlying value is not a float, double or integer.
  4719. */
  4720. float mpack_expect_float(mpack_reader_t* reader);
  4721. #endif
  4722. #if MPACK_DOUBLE
  4723. /**
  4724. * Reads a number, returning the value as a double. The underlying value can be an
  4725. * integer, float or double; the value is converted to a double.
  4726. *
  4727. * @note Reading a very large integer with this function can incur a
  4728. * loss of precision.
  4729. *
  4730. * @throws mpack_error_type if the underlying value is not a float, double or integer.
  4731. */
  4732. double mpack_expect_double(mpack_reader_t* reader);
  4733. #endif
  4734. #if MPACK_FLOAT
  4735. /**
  4736. * Reads a float. The underlying value must be a float, not a double or an integer.
  4737. * This ensures no loss of precision can occur.
  4738. *
  4739. * @throws mpack_error_type if the underlying value is not a float.
  4740. */
  4741. float mpack_expect_float_strict(mpack_reader_t* reader);
  4742. #endif
  4743. #if MPACK_DOUBLE
  4744. /**
  4745. * Reads a double. The underlying value must be a float or double, not an integer.
  4746. * This ensures no loss of precision can occur.
  4747. *
  4748. * @throws mpack_error_type if the underlying value is not a float or double.
  4749. */
  4750. double mpack_expect_double_strict(mpack_reader_t* reader);
  4751. #endif
  4752. #if !MPACK_FLOAT
  4753. /**
  4754. * Reads a float as a raw uint32_t. The underlying value must be a float, not a
  4755. * double or an integer.
  4756. *
  4757. * @throws mpack_error_type if the underlying value is not a float.
  4758. */
  4759. uint32_t mpack_expect_raw_float(mpack_reader_t* reader);
  4760. #endif
  4761. #if !MPACK_DOUBLE
  4762. /**
  4763. * Reads a double as a raw uint64_t. The underlying value must be a double, not a
  4764. * float or an integer.
  4765. *
  4766. * @throws mpack_error_type if the underlying value is not a double.
  4767. */
  4768. uint64_t mpack_expect_raw_double(mpack_reader_t* reader);
  4769. #endif
  4770. /**
  4771. * @}
  4772. */
  4773. /**
  4774. * @name Ranged Number Functions
  4775. * @{
  4776. */
  4777. /**
  4778. * Reads an 8-bit unsigned integer, ensuring that it falls within the given range.
  4779. *
  4780. * The underlying type may be an integer type of any size and signedness,
  4781. * as long as the value can be represented in an 8-bit unsigned int.
  4782. *
  4783. * Returns min_value if an error occurs.
  4784. */
  4785. uint8_t mpack_expect_u8_range(mpack_reader_t* reader, uint8_t min_value, uint8_t max_value);
  4786. /**
  4787. * Reads a 16-bit unsigned integer, ensuring that it falls within the given range.
  4788. *
  4789. * The underlying type may be an integer type of any size and signedness,
  4790. * as long as the value can be represented in a 16-bit unsigned int.
  4791. *
  4792. * Returns min_value if an error occurs.
  4793. */
  4794. uint16_t mpack_expect_u16_range(mpack_reader_t* reader, uint16_t min_value, uint16_t max_value);
  4795. /**
  4796. * Reads a 32-bit unsigned integer, ensuring that it falls within the given range.
  4797. *
  4798. * The underlying type may be an integer type of any size and signedness,
  4799. * as long as the value can be represented in a 32-bit unsigned int.
  4800. *
  4801. * Returns min_value if an error occurs.
  4802. */
  4803. uint32_t mpack_expect_u32_range(mpack_reader_t* reader, uint32_t min_value, uint32_t max_value);
  4804. /**
  4805. * Reads a 64-bit unsigned integer, ensuring that it falls within the given range.
  4806. *
  4807. * The underlying type may be an integer type of any size and signedness,
  4808. * as long as the value can be represented in a 64-bit unsigned int.
  4809. *
  4810. * Returns min_value if an error occurs.
  4811. */
  4812. uint64_t mpack_expect_u64_range(mpack_reader_t* reader, uint64_t min_value, uint64_t max_value);
  4813. /**
  4814. * Reads an unsigned integer, ensuring that it falls within the given range.
  4815. *
  4816. * The underlying type may be an integer type of any size and signedness,
  4817. * as long as the value can be represented in an unsigned int.
  4818. *
  4819. * Returns min_value if an error occurs.
  4820. */
  4821. MPACK_INLINE unsigned int mpack_expect_uint_range(mpack_reader_t* reader, unsigned int min_value, unsigned int max_value) {
  4822. // This should be true at compile-time, so this just wraps the 32-bit
  4823. // function. We fallback to 64-bit if for some reason sizeof(int) isn't 4.
  4824. if (sizeof(unsigned int) == 4)
  4825. return (unsigned int)mpack_expect_u32_range(reader, (uint32_t)min_value, (uint32_t)max_value);
  4826. return (unsigned int)mpack_expect_u64_range(reader, min_value, max_value);
  4827. }
  4828. /**
  4829. * Reads an 8-bit unsigned integer, ensuring that it is at most @a max_value.
  4830. *
  4831. * The underlying type may be an integer type of any size and signedness,
  4832. * as long as the value can be represented in an 8-bit unsigned int.
  4833. *
  4834. * Returns 0 if an error occurs.
  4835. */
  4836. MPACK_INLINE uint8_t mpack_expect_u8_max(mpack_reader_t* reader, uint8_t max_value) {
  4837. return mpack_expect_u8_range(reader, 0, max_value);
  4838. }
  4839. /**
  4840. * Reads a 16-bit unsigned integer, ensuring that it is at most @a max_value.
  4841. *
  4842. * The underlying type may be an integer type of any size and signedness,
  4843. * as long as the value can be represented in a 16-bit unsigned int.
  4844. *
  4845. * Returns 0 if an error occurs.
  4846. */
  4847. MPACK_INLINE uint16_t mpack_expect_u16_max(mpack_reader_t* reader, uint16_t max_value) {
  4848. return mpack_expect_u16_range(reader, 0, max_value);
  4849. }
  4850. /**
  4851. * Reads a 32-bit unsigned integer, ensuring that it is at most @a max_value.
  4852. *
  4853. * The underlying type may be an integer type of any size and signedness,
  4854. * as long as the value can be represented in a 32-bit unsigned int.
  4855. *
  4856. * Returns 0 if an error occurs.
  4857. */
  4858. MPACK_INLINE uint32_t mpack_expect_u32_max(mpack_reader_t* reader, uint32_t max_value) {
  4859. return mpack_expect_u32_range(reader, 0, max_value);
  4860. }
  4861. /**
  4862. * Reads a 64-bit unsigned integer, ensuring that it is at most @a max_value.
  4863. *
  4864. * The underlying type may be an integer type of any size and signedness,
  4865. * as long as the value can be represented in a 64-bit unsigned int.
  4866. *
  4867. * Returns 0 if an error occurs.
  4868. */
  4869. MPACK_INLINE uint64_t mpack_expect_u64_max(mpack_reader_t* reader, uint64_t max_value) {
  4870. return mpack_expect_u64_range(reader, 0, max_value);
  4871. }
  4872. /**
  4873. * Reads an unsigned integer, ensuring that it is at most @a max_value.
  4874. *
  4875. * The underlying type may be an integer type of any size and signedness,
  4876. * as long as the value can be represented in an unsigned int.
  4877. *
  4878. * Returns 0 if an error occurs.
  4879. */
  4880. MPACK_INLINE unsigned int mpack_expect_uint_max(mpack_reader_t* reader, unsigned int max_value) {
  4881. return mpack_expect_uint_range(reader, 0, max_value);
  4882. }
  4883. /**
  4884. * Reads an 8-bit signed integer, ensuring that it falls within the given range.
  4885. *
  4886. * The underlying type may be an integer type of any size and signedness,
  4887. * as long as the value can be represented in an 8-bit signed int.
  4888. *
  4889. * Returns min_value if an error occurs.
  4890. */
  4891. int8_t mpack_expect_i8_range(mpack_reader_t* reader, int8_t min_value, int8_t max_value);
  4892. /**
  4893. * Reads a 16-bit signed integer, ensuring that it falls within the given range.
  4894. *
  4895. * The underlying type may be an integer type of any size and signedness,
  4896. * as long as the value can be represented in a 16-bit signed int.
  4897. *
  4898. * Returns min_value if an error occurs.
  4899. */
  4900. int16_t mpack_expect_i16_range(mpack_reader_t* reader, int16_t min_value, int16_t max_value);
  4901. /**
  4902. * Reads a 32-bit signed integer, ensuring that it falls within the given range.
  4903. *
  4904. * The underlying type may be an integer type of any size and signedness,
  4905. * as long as the value can be represented in a 32-bit signed int.
  4906. *
  4907. * Returns min_value if an error occurs.
  4908. */
  4909. int32_t mpack_expect_i32_range(mpack_reader_t* reader, int32_t min_value, int32_t max_value);
  4910. /**
  4911. * Reads a 64-bit signed integer, ensuring that it falls within the given range.
  4912. *
  4913. * The underlying type may be an integer type of any size and signedness,
  4914. * as long as the value can be represented in a 64-bit signed int.
  4915. *
  4916. * Returns min_value if an error occurs.
  4917. */
  4918. int64_t mpack_expect_i64_range(mpack_reader_t* reader, int64_t min_value, int64_t max_value);
  4919. /**
  4920. * Reads a signed integer, ensuring that it falls within the given range.
  4921. *
  4922. * The underlying type may be an integer type of any size and signedness,
  4923. * as long as the value can be represented in a signed int.
  4924. *
  4925. * Returns min_value if an error occurs.
  4926. */
  4927. MPACK_INLINE int mpack_expect_int_range(mpack_reader_t* reader, int min_value, int max_value) {
  4928. // This should be true at compile-time, so this just wraps the 32-bit
  4929. // function. We fallback to 64-bit if for some reason sizeof(int) isn't 4.
  4930. if (sizeof(int) == 4)
  4931. return (int)mpack_expect_i32_range(reader, (int32_t)min_value, (int32_t)max_value);
  4932. return (int)mpack_expect_i64_range(reader, min_value, max_value);
  4933. }
  4934. /**
  4935. * Reads an 8-bit signed integer, ensuring that it is at least zero and at
  4936. * most @a max_value.
  4937. *
  4938. * The underlying type may be an integer type of any size and signedness,
  4939. * as long as the value can be represented in an 8-bit signed int.
  4940. *
  4941. * Returns 0 if an error occurs.
  4942. */
  4943. MPACK_INLINE int8_t mpack_expect_i8_max(mpack_reader_t* reader, int8_t max_value) {
  4944. return mpack_expect_i8_range(reader, 0, max_value);
  4945. }
  4946. /**
  4947. * Reads a 16-bit signed integer, ensuring that it is at least zero and at
  4948. * most @a max_value.
  4949. *
  4950. * The underlying type may be an integer type of any size and signedness,
  4951. * as long as the value can be represented in a 16-bit signed int.
  4952. *
  4953. * Returns 0 if an error occurs.
  4954. */
  4955. MPACK_INLINE int16_t mpack_expect_i16_max(mpack_reader_t* reader, int16_t max_value) {
  4956. return mpack_expect_i16_range(reader, 0, max_value);
  4957. }
  4958. /**
  4959. * Reads a 32-bit signed integer, ensuring that it is at least zero and at
  4960. * most @a max_value.
  4961. *
  4962. * The underlying type may be an integer type of any size and signedness,
  4963. * as long as the value can be represented in a 32-bit signed int.
  4964. *
  4965. * Returns 0 if an error occurs.
  4966. */
  4967. MPACK_INLINE int32_t mpack_expect_i32_max(mpack_reader_t* reader, int32_t max_value) {
  4968. return mpack_expect_i32_range(reader, 0, max_value);
  4969. }
  4970. /**
  4971. * Reads a 64-bit signed integer, ensuring that it is at least zero and at
  4972. * most @a max_value.
  4973. *
  4974. * The underlying type may be an integer type of any size and signedness,
  4975. * as long as the value can be represented in a 64-bit signed int.
  4976. *
  4977. * Returns 0 if an error occurs.
  4978. */
  4979. MPACK_INLINE int64_t mpack_expect_i64_max(mpack_reader_t* reader, int64_t max_value) {
  4980. return mpack_expect_i64_range(reader, 0, max_value);
  4981. }
  4982. /**
  4983. * Reads an int, ensuring that it is at least zero and at most @a max_value.
  4984. *
  4985. * The underlying type may be an integer type of any size and signedness,
  4986. * as long as the value can be represented in a signed int.
  4987. *
  4988. * Returns 0 if an error occurs.
  4989. */
  4990. MPACK_INLINE int mpack_expect_int_max(mpack_reader_t* reader, int max_value) {
  4991. return mpack_expect_int_range(reader, 0, max_value);
  4992. }
  4993. #if MPACK_FLOAT
  4994. /**
  4995. * Reads a number, ensuring that it falls within the given range and returning
  4996. * the value as a float. The underlying value can be an integer, float or
  4997. * double; the value is converted to a float.
  4998. *
  4999. * @note Reading a double or a large integer with this function can incur a
  5000. * loss of precision.
  5001. *
  5002. * @throws mpack_error_type if the underlying value is not a float, double or integer.
  5003. */
  5004. float mpack_expect_float_range(mpack_reader_t* reader, float min_value, float max_value);
  5005. #endif
  5006. #if MPACK_DOUBLE
  5007. /**
  5008. * Reads a number, ensuring that it falls within the given range and returning
  5009. * the value as a double. The underlying value can be an integer, float or
  5010. * double; the value is converted to a double.
  5011. *
  5012. * @note Reading a very large integer with this function can incur a
  5013. * loss of precision.
  5014. *
  5015. * @throws mpack_error_type if the underlying value is not a float, double or integer.
  5016. */
  5017. double mpack_expect_double_range(mpack_reader_t* reader, double min_value, double max_value);
  5018. #endif
  5019. /**
  5020. * @}
  5021. */
  5022. // These are additional Basic Number functions that wrap inline range functions.
  5023. /**
  5024. * @name Basic Number Functions
  5025. * @{
  5026. */
  5027. /**
  5028. * Reads an unsigned int.
  5029. *
  5030. * The underlying type may be an integer type of any size and signedness,
  5031. * as long as the value can be represented in an unsigned int.
  5032. *
  5033. * Returns zero if an error occurs.
  5034. */
  5035. MPACK_INLINE unsigned int mpack_expect_uint(mpack_reader_t* reader) {
  5036. // This should be true at compile-time, so this just wraps the 32-bit function.
  5037. if (sizeof(unsigned int) == 4)
  5038. return (unsigned int)mpack_expect_u32(reader);
  5039. // Otherwise we wrap the max function to ensure it fits.
  5040. return (unsigned int)mpack_expect_u64_max(reader, MPACK_UINT_MAX);
  5041. }
  5042. /**
  5043. * Reads a signed int.
  5044. *
  5045. * The underlying type may be an integer type of any size and signedness,
  5046. * as long as the value can be represented in a signed int.
  5047. *
  5048. * Returns zero if an error occurs.
  5049. */
  5050. MPACK_INLINE int mpack_expect_int(mpack_reader_t* reader) {
  5051. // This should be true at compile-time, so this just wraps the 32-bit function.
  5052. if (sizeof(int) == 4)
  5053. return (int)mpack_expect_i32(reader);
  5054. // Otherwise we wrap the range function to ensure it fits.
  5055. return (int)mpack_expect_i64_range(reader, MPACK_INT_MIN, MPACK_INT_MAX);
  5056. }
  5057. /**
  5058. * @}
  5059. */
  5060. /**
  5061. * @name Matching Number Functions
  5062. * @{
  5063. */
  5064. /**
  5065. * Reads an unsigned integer, ensuring that it exactly matches the given value.
  5066. *
  5067. * mpack_error_type is raised if the value is not representable as an unsigned
  5068. * integer or if it does not exactly match the given value.
  5069. */
  5070. void mpack_expect_uint_match(mpack_reader_t* reader, uint64_t value);
  5071. /**
  5072. * Reads a signed integer, ensuring that it exactly matches the given value.
  5073. *
  5074. * mpack_error_type is raised if the value is not representable as a signed
  5075. * integer or if it does not exactly match the given value.
  5076. */
  5077. void mpack_expect_int_match(mpack_reader_t* reader, int64_t value);
  5078. /**
  5079. * @}
  5080. */
  5081. /**
  5082. * @name Other Basic Types
  5083. * @{
  5084. */
  5085. /**
  5086. * Reads a nil, raising @ref mpack_error_type if the value is not nil.
  5087. */
  5088. void mpack_expect_nil(mpack_reader_t* reader);
  5089. /**
  5090. * Reads a boolean.
  5091. *
  5092. * @note Integers will raise mpack_error_type; the value must be strictly a boolean.
  5093. */
  5094. bool mpack_expect_bool(mpack_reader_t* reader);
  5095. /**
  5096. * Reads a boolean, raising @ref mpack_error_type if its value is not @c true.
  5097. */
  5098. void mpack_expect_true(mpack_reader_t* reader);
  5099. /**
  5100. * Reads a boolean, raising @ref mpack_error_type if its value is not @c false.
  5101. */
  5102. void mpack_expect_false(mpack_reader_t* reader);
  5103. /**
  5104. * @}
  5105. */
  5106. /**
  5107. * @name Extension Functions
  5108. * @{
  5109. */
  5110. #if MPACK_EXTENSIONS
  5111. /**
  5112. * Reads a timestamp.
  5113. *
  5114. * @note This requires @ref MPACK_EXTENSIONS.
  5115. */
  5116. mpack_timestamp_t mpack_expect_timestamp(mpack_reader_t* reader);
  5117. /**
  5118. * Reads a timestamp in seconds, truncating the nanoseconds (if any).
  5119. *
  5120. * @note This requires @ref MPACK_EXTENSIONS.
  5121. */
  5122. int64_t mpack_expect_timestamp_truncate(mpack_reader_t* reader);
  5123. #endif
  5124. /**
  5125. * @}
  5126. */
  5127. /**
  5128. * @name Compound Types
  5129. * @{
  5130. */
  5131. /**
  5132. * Reads the start of a map, returning its element count.
  5133. *
  5134. * A number of values follow equal to twice the element count of the map,
  5135. * alternating between keys and values. @ref mpack_done_map() must be called
  5136. * once all elements have been read.
  5137. *
  5138. * @note Maps in JSON are unordered, so it is recommended not to expect
  5139. * a specific ordering for your map values in case your data is converted
  5140. * to/from JSON.
  5141. *
  5142. * @warning This call is dangerous! It does not have a size limit, and it
  5143. * does not have any way of checking whether there is enough data in the
  5144. * message (since the data could be coming from a stream.) When looping
  5145. * through the map's contents, you must check for errors on each iteration
  5146. * of the loop. Otherwise an attacker could craft a message declaring a map
  5147. * of a billion elements which would throw your parsing code into an
  5148. * infinite loop! You should strongly consider using mpack_expect_map_max()
  5149. * with a safe maximum size instead.
  5150. *
  5151. * @throws mpack_error_type if the value is not a map.
  5152. */
  5153. uint32_t mpack_expect_map(mpack_reader_t* reader);
  5154. /**
  5155. * Reads the start of a map with a number of elements in the given range, returning
  5156. * its element count.
  5157. *
  5158. * A number of values follow equal to twice the element count of the map,
  5159. * alternating between keys and values. @ref mpack_done_map() must be called
  5160. * once all elements have been read.
  5161. *
  5162. * @note Maps in JSON are unordered, so it is recommended not to expect
  5163. * a specific ordering for your map values in case your data is converted
  5164. * to/from JSON.
  5165. *
  5166. * min_count is returned if an error occurs.
  5167. *
  5168. * @throws mpack_error_type if the value is not a map or if its size does
  5169. * not fall within the given range.
  5170. */
  5171. uint32_t mpack_expect_map_range(mpack_reader_t* reader, uint32_t min_count, uint32_t max_count);
  5172. /**
  5173. * Reads the start of a map with a number of elements at most @a max_count,
  5174. * returning its element count.
  5175. *
  5176. * A number of values follow equal to twice the element count of the map,
  5177. * alternating between keys and values. @ref mpack_done_map() must be called
  5178. * once all elements have been read.
  5179. *
  5180. * @note Maps in JSON are unordered, so it is recommended not to expect
  5181. * a specific ordering for your map values in case your data is converted
  5182. * to/from JSON.
  5183. *
  5184. * Zero is returned if an error occurs.
  5185. *
  5186. * @throws mpack_error_type if the value is not a map or if its size is
  5187. * greater than max_count.
  5188. */
  5189. MPACK_INLINE uint32_t mpack_expect_map_max(mpack_reader_t* reader, uint32_t max_count) {
  5190. return mpack_expect_map_range(reader, 0, max_count);
  5191. }
  5192. /**
  5193. * Reads the start of a map of the exact size given.
  5194. *
  5195. * A number of values follow equal to twice the element count of the map,
  5196. * alternating between keys and values. @ref mpack_done_map() must be called
  5197. * once all elements have been read.
  5198. *
  5199. * @note Maps in JSON are unordered, so it is recommended not to expect
  5200. * a specific ordering for your map values in case your data is converted
  5201. * to/from JSON.
  5202. *
  5203. * @throws mpack_error_type if the value is not a map or if its size
  5204. * does not match the given count.
  5205. */
  5206. void mpack_expect_map_match(mpack_reader_t* reader, uint32_t count);
  5207. /**
  5208. * Reads a nil node or the start of a map, returning whether a map was
  5209. * read and placing its number of key/value pairs in count.
  5210. *
  5211. * If a map was read, a number of values follow equal to twice the element count
  5212. * of the map, alternating between keys and values. @ref mpack_done_map() should
  5213. * also be called once all elements have been read (only if a map was read.)
  5214. *
  5215. * @note Maps in JSON are unordered, so it is recommended not to expect
  5216. * a specific ordering for your map values in case your data is converted
  5217. * to/from JSON.
  5218. *
  5219. * @warning This call is dangerous! It does not have a size limit, and it
  5220. * does not have any way of checking whether there is enough data in the
  5221. * message (since the data could be coming from a stream.) When looping
  5222. * through the map's contents, you must check for errors on each iteration
  5223. * of the loop. Otherwise an attacker could craft a message declaring a map
  5224. * of a billion elements which would throw your parsing code into an
  5225. * infinite loop! You should strongly consider using mpack_expect_map_max_or_nil()
  5226. * with a safe maximum size instead.
  5227. *
  5228. * @returns @c true if a map was read successfully; @c false if nil was read
  5229. * or an error occurred.
  5230. * @throws mpack_error_type if the value is not a nil or map.
  5231. */
  5232. bool mpack_expect_map_or_nil(mpack_reader_t* reader, uint32_t* count);
  5233. /**
  5234. * Reads a nil node or the start of a map with a number of elements at most
  5235. * max_count, returning whether a map was read and placing its number of
  5236. * key/value pairs in count.
  5237. *
  5238. * If a map was read, a number of values follow equal to twice the element count
  5239. * of the map, alternating between keys and values. @ref mpack_done_map() should
  5240. * anlso be called once all elements have been read (only if a map was read.)
  5241. *
  5242. * @note Maps in JSON are unordered, so it is recommended not to expect
  5243. * a specific ordering for your map values in case your data is converted
  5244. * to/from JSON. Consider using mpack_expect_key_cstr() or mpack_expect_key_uint()
  5245. * to switch on the key; see @ref docs/expect.md for examples.
  5246. *
  5247. * @returns @c true if a map was read successfully; @c false if nil was read
  5248. * or an error occurred.
  5249. * @throws mpack_error_type if the value is not a nil or map.
  5250. */
  5251. bool mpack_expect_map_max_or_nil(mpack_reader_t* reader, uint32_t max_count, uint32_t* count);
  5252. /**
  5253. * Reads the start of an array, returning its element count.
  5254. *
  5255. * A number of values follow equal to the element count of the array.
  5256. * @ref mpack_done_array() must be called once all elements have been read.
  5257. *
  5258. * @warning This call is dangerous! It does not have a size limit, and it
  5259. * does not have any way of checking whether there is enough data in the
  5260. * message (since the data could be coming from a stream.) When looping
  5261. * through the array's contents, you must check for errors on each iteration
  5262. * of the loop. Otherwise an attacker could craft a message declaring an array
  5263. * of a billion elements which would throw your parsing code into an
  5264. * infinite loop! You should strongly consider using mpack_expect_array_max()
  5265. * with a safe maximum size instead.
  5266. */
  5267. uint32_t mpack_expect_array(mpack_reader_t* reader);
  5268. /**
  5269. * Reads the start of an array with a number of elements in the given range,
  5270. * returning its element count.
  5271. *
  5272. * A number of values follow equal to the element count of the array.
  5273. * @ref mpack_done_array() must be called once all elements have been read.
  5274. *
  5275. * min_count is returned if an error occurs.
  5276. *
  5277. * @throws mpack_error_type if the value is not an array or if its size does
  5278. * not fall within the given range.
  5279. */
  5280. uint32_t mpack_expect_array_range(mpack_reader_t* reader, uint32_t min_count, uint32_t max_count);
  5281. /**
  5282. * Reads the start of an array with a number of elements at most @a max_count,
  5283. * returning its element count.
  5284. *
  5285. * A number of values follow equal to the element count of the array.
  5286. * @ref mpack_done_array() must be called once all elements have been read.
  5287. *
  5288. * Zero is returned if an error occurs.
  5289. *
  5290. * @throws mpack_error_type if the value is not an array or if its size is
  5291. * greater than max_count.
  5292. */
  5293. MPACK_INLINE uint32_t mpack_expect_array_max(mpack_reader_t* reader, uint32_t max_count) {
  5294. return mpack_expect_array_range(reader, 0, max_count);
  5295. }
  5296. /**
  5297. * Reads the start of an array of the exact size given.
  5298. *
  5299. * A number of values follow equal to the element count of the array.
  5300. * @ref mpack_done_array() must be called once all elements have been read.
  5301. *
  5302. * @throws mpack_error_type if the value is not an array or if its size does
  5303. * not match the given count.
  5304. */
  5305. void mpack_expect_array_match(mpack_reader_t* reader, uint32_t count);
  5306. /**
  5307. * Reads a nil node or the start of an array, returning whether an array was
  5308. * read and placing its number of elements in count.
  5309. *
  5310. * If an array was read, a number of values follow equal to the element count
  5311. * of the array. @ref mpack_done_array() should also be called once all elements
  5312. * have been read (only if an array was read.)
  5313. *
  5314. * @warning This call is dangerous! It does not have a size limit, and it
  5315. * does not have any way of checking whether there is enough data in the
  5316. * message (since the data could be coming from a stream.) When looping
  5317. * through the array's contents, you must check for errors on each iteration
  5318. * of the loop. Otherwise an attacker could craft a message declaring an array
  5319. * of a billion elements which would throw your parsing code into an
  5320. * infinite loop! You should strongly consider using mpack_expect_array_max_or_nil()
  5321. * with a safe maximum size instead.
  5322. *
  5323. * @returns @c true if an array was read successfully; @c false if nil was read
  5324. * or an error occurred.
  5325. * @throws mpack_error_type if the value is not a nil or array.
  5326. */
  5327. bool mpack_expect_array_or_nil(mpack_reader_t* reader, uint32_t* count);
  5328. /**
  5329. * Reads a nil node or the start of an array with a number of elements at most
  5330. * max_count, returning whether an array was read and placing its number of
  5331. * key/value pairs in count.
  5332. *
  5333. * If an array was read, a number of values follow equal to the element count
  5334. * of the array. @ref mpack_done_array() should also be called once all elements
  5335. * have been read (only if an array was read.)
  5336. *
  5337. * @returns @c true if an array was read successfully; @c false if nil was read
  5338. * or an error occurred.
  5339. * @throws mpack_error_type if the value is not a nil or array.
  5340. */
  5341. bool mpack_expect_array_max_or_nil(mpack_reader_t* reader, uint32_t max_count, uint32_t* count);
  5342. #ifdef MPACK_MALLOC
  5343. /**
  5344. * @hideinitializer
  5345. *
  5346. * Reads the start of an array and allocates storage for it, placing its
  5347. * size in out_count. A number of objects follow equal to the element count
  5348. * of the array. You must call @ref mpack_done_array() when done (even
  5349. * if the element count is zero.)
  5350. *
  5351. * If an error occurs, NULL is returned and the reader is placed in an
  5352. * error state.
  5353. *
  5354. * If the count is zero, NULL is returned. This does not indicate error.
  5355. * You should not check the return value for NULL to check for errors; only
  5356. * check the reader's error state.
  5357. *
  5358. * The allocated array must be freed with MPACK_FREE() (or simply free()
  5359. * if MPack's allocator hasn't been customized.)
  5360. *
  5361. * @throws mpack_error_type if the value is not an array or if its size is
  5362. * greater than max_count.
  5363. */
  5364. #define mpack_expect_array_alloc(reader, Type, max_count, out_count) \
  5365. ((Type*)mpack_expect_array_alloc_impl(reader, sizeof(Type), max_count, out_count, false))
  5366. /**
  5367. * @hideinitializer
  5368. *
  5369. * Reads a nil node or the start of an array and allocates storage for it,
  5370. * placing its size in out_count. A number of objects follow equal to the element
  5371. * count of the array if a non-empty array was read.
  5372. *
  5373. * If an error occurs, NULL is returned and the reader is placed in an
  5374. * error state.
  5375. *
  5376. * If a nil node was read, NULL is returned. If an empty array was read,
  5377. * mpack_done_array() is called automatically and NULL is returned. These
  5378. * do not indicate error. You should not check the return value for NULL
  5379. * to check for errors; only check the reader's error state.
  5380. *
  5381. * The allocated array must be freed with MPACK_FREE() (or simply free()
  5382. * if MPack's allocator hasn't been customized.)
  5383. *
  5384. * @warning You must call @ref mpack_done_array() if and only if a non-zero
  5385. * element count is read. This function does not differentiate between nil
  5386. * and an empty array.
  5387. *
  5388. * @throws mpack_error_type if the value is not an array or if its size is
  5389. * greater than max_count.
  5390. */
  5391. #define mpack_expect_array_or_nil_alloc(reader, Type, max_count, out_count) \
  5392. ((Type*)mpack_expect_array_alloc_impl(reader, sizeof(Type), max_count, out_count, true))
  5393. #endif
  5394. /**
  5395. * @}
  5396. */
  5397. /** @cond */
  5398. #ifdef MPACK_MALLOC
  5399. void* mpack_expect_array_alloc_impl(mpack_reader_t* reader,
  5400. size_t element_size, uint32_t max_count, uint32_t* out_count, bool allow_nil);
  5401. #endif
  5402. /** @endcond */
  5403. /**
  5404. * @name String Functions
  5405. * @{
  5406. */
  5407. /**
  5408. * Reads the start of a string, returning its size in bytes.
  5409. *
  5410. * The bytes follow and must be read separately with mpack_read_bytes()
  5411. * or mpack_read_bytes_inplace(). mpack_done_str() must be called
  5412. * once all bytes have been read.
  5413. *
  5414. * NUL bytes are allowed in the string, and no encoding checks are done.
  5415. *
  5416. * mpack_error_type is raised if the value is not a string.
  5417. */
  5418. uint32_t mpack_expect_str(mpack_reader_t* reader);
  5419. /**
  5420. * Reads a string of at most the given size, writing it into the
  5421. * given buffer and returning its size in bytes.
  5422. *
  5423. * This does not add a null-terminator! Use mpack_expect_cstr() to
  5424. * add a null-terminator.
  5425. *
  5426. * NUL bytes are allowed in the string, and no encoding checks are done.
  5427. */
  5428. size_t mpack_expect_str_buf(mpack_reader_t* reader, char* buf, size_t bufsize);
  5429. /**
  5430. * Reads a string into the given buffer, ensuring it is a valid UTF-8 string
  5431. * and returning its size in bytes.
  5432. *
  5433. * This does not add a null-terminator! Use mpack_expect_utf8_cstr() to
  5434. * add a null-terminator.
  5435. *
  5436. * This does not accept any UTF-8 variant such as Modified UTF-8, CESU-8 or
  5437. * WTF-8. Only pure UTF-8 is allowed.
  5438. *
  5439. * NUL bytes are allowed in the string (as they are in UTF-8.)
  5440. *
  5441. * Raises mpack_error_too_big if there is not enough room for the string.
  5442. * Raises mpack_error_type if the value is not a string or is not a valid UTF-8 string.
  5443. */
  5444. size_t mpack_expect_utf8(mpack_reader_t* reader, char* buf, size_t bufsize);
  5445. /**
  5446. * Reads the start of a string, raising an error if its length is not
  5447. * at most the given number of bytes (not including any null-terminator.)
  5448. *
  5449. * The bytes follow and must be read separately with mpack_read_bytes()
  5450. * or mpack_read_bytes_inplace(). @ref mpack_done_str() must be called
  5451. * once all bytes have been read.
  5452. *
  5453. * @throws mpack_error_type If the value is not a string.
  5454. * @throws mpack_error_too_big If the string's length in bytes is larger than the given maximum size.
  5455. */
  5456. MPACK_INLINE uint32_t mpack_expect_str_max(mpack_reader_t* reader, uint32_t maxsize) {
  5457. uint32_t length = mpack_expect_str(reader);
  5458. if (length > maxsize) {
  5459. mpack_reader_flag_error(reader, mpack_error_too_big);
  5460. return 0;
  5461. }
  5462. return length;
  5463. }
  5464. /**
  5465. * Reads the start of a string, raising an error if its length is not
  5466. * exactly the given number of bytes (not including any null-terminator.)
  5467. *
  5468. * The bytes follow and must be read separately with mpack_read_bytes()
  5469. * or mpack_read_bytes_inplace(). @ref mpack_done_str() must be called
  5470. * once all bytes have been read.
  5471. *
  5472. * mpack_error_type is raised if the value is not a string or if its
  5473. * length does not match.
  5474. */
  5475. MPACK_INLINE void mpack_expect_str_length(mpack_reader_t* reader, uint32_t count) {
  5476. if (mpack_expect_str(reader) != count)
  5477. mpack_reader_flag_error(reader, mpack_error_type);
  5478. }
  5479. /**
  5480. * Reads a string, ensuring it exactly matches the given string.
  5481. *
  5482. * Remember that maps are unordered in JSON. Don't use this for map keys
  5483. * unless the map has only a single key!
  5484. */
  5485. void mpack_expect_str_match(mpack_reader_t* reader, const char* str, size_t length);
  5486. /**
  5487. * Reads a string into the given buffer, ensures it has no null bytes,
  5488. * and adds a null-terminator at the end.
  5489. *
  5490. * Raises mpack_error_too_big if there is not enough room for the string and null-terminator.
  5491. * Raises mpack_error_type if the value is not a string or contains a null byte.
  5492. */
  5493. void mpack_expect_cstr(mpack_reader_t* reader, char* buf, size_t size);
  5494. /**
  5495. * Reads a string into the given buffer, ensures it is a valid UTF-8 string
  5496. * without NUL characters, and adds a null-terminator at the end.
  5497. *
  5498. * This does not accept any UTF-8 variant such as Modified UTF-8, CESU-8 or
  5499. * WTF-8. Only pure UTF-8 is allowed, but without the NUL character, since
  5500. * it cannot be represented in a null-terminated string.
  5501. *
  5502. * Raises mpack_error_too_big if there is not enough room for the string and null-terminator.
  5503. * Raises mpack_error_type if the value is not a string or is not a valid UTF-8 string.
  5504. */
  5505. void mpack_expect_utf8_cstr(mpack_reader_t* reader, char* buf, size_t size);
  5506. #ifdef MPACK_MALLOC
  5507. /**
  5508. * Reads a string with the given total maximum size (including space for a
  5509. * null-terminator), allocates storage for it, ensures it has no null-bytes,
  5510. * and adds a null-terminator at the end. You assume ownership of the
  5511. * returned pointer if reading succeeds.
  5512. *
  5513. * The allocated string must be freed with MPACK_FREE() (or simply free()
  5514. * if MPack's allocator hasn't been customized.)
  5515. *
  5516. * @throws mpack_error_too_big If the string plus null-terminator is larger than the given maxsize.
  5517. * @throws mpack_error_type If the value is not a string or contains a null byte.
  5518. */
  5519. char* mpack_expect_cstr_alloc(mpack_reader_t* reader, size_t maxsize);
  5520. /**
  5521. * Reads a string with the given total maximum size (including space for a
  5522. * null-terminator), allocates storage for it, ensures it is valid UTF-8
  5523. * with no null-bytes, and adds a null-terminator at the end. You assume
  5524. * ownership of the returned pointer if reading succeeds.
  5525. *
  5526. * The length in bytes of the string, not including the null-terminator,
  5527. * will be written to size.
  5528. *
  5529. * This does not accept any UTF-8 variant such as Modified UTF-8, CESU-8 or
  5530. * WTF-8. Only pure UTF-8 is allowed, but without the NUL character, since
  5531. * it cannot be represented in a null-terminated string.
  5532. *
  5533. * The allocated string must be freed with MPACK_FREE() (or simply free()
  5534. * if MPack's allocator hasn't been customized.)
  5535. * if you want a null-terminator.
  5536. *
  5537. * @throws mpack_error_too_big If the string plus null-terminator is larger
  5538. * than the given maxsize.
  5539. * @throws mpack_error_type If the value is not a string or contains
  5540. * invalid UTF-8 or a null byte.
  5541. */
  5542. char* mpack_expect_utf8_cstr_alloc(mpack_reader_t* reader, size_t maxsize);
  5543. #endif
  5544. /**
  5545. * Reads a string, ensuring it exactly matches the given null-terminated
  5546. * string.
  5547. *
  5548. * Remember that maps are unordered in JSON. Don't use this for map keys
  5549. * unless the map has only a single key!
  5550. */
  5551. MPACK_INLINE void mpack_expect_cstr_match(mpack_reader_t* reader, const char* cstr) {
  5552. mpack_assert(cstr != NULL, "cstr pointer is NULL");
  5553. mpack_expect_str_match(reader, cstr, mpack_strlen(cstr));
  5554. }
  5555. /**
  5556. * @}
  5557. */
  5558. /**
  5559. * @name Binary Data
  5560. * @{
  5561. */
  5562. /**
  5563. * Reads the start of a binary blob, returning its size in bytes.
  5564. *
  5565. * The bytes follow and must be read separately with mpack_read_bytes()
  5566. * or mpack_read_bytes_inplace(). @ref mpack_done_bin() must be called
  5567. * once all bytes have been read.
  5568. *
  5569. * mpack_error_type is raised if the value is not a binary blob.
  5570. */
  5571. uint32_t mpack_expect_bin(mpack_reader_t* reader);
  5572. /**
  5573. * Reads the start of a binary blob, raising an error if its length is not
  5574. * at most the given number of bytes.
  5575. *
  5576. * The bytes follow and must be read separately with mpack_read_bytes()
  5577. * or mpack_read_bytes_inplace(). @ref mpack_done_bin() must be called
  5578. * once all bytes have been read.
  5579. *
  5580. * mpack_error_type is raised if the value is not a binary blob or if its
  5581. * length does not match.
  5582. */
  5583. MPACK_INLINE uint32_t mpack_expect_bin_max(mpack_reader_t* reader, uint32_t maxsize) {
  5584. uint32_t length = mpack_expect_bin(reader);
  5585. if (length > maxsize) {
  5586. mpack_reader_flag_error(reader, mpack_error_type);
  5587. return 0;
  5588. }
  5589. return length;
  5590. }
  5591. /**
  5592. * Reads the start of a binary blob, raising an error if its length is not
  5593. * exactly the given number of bytes.
  5594. *
  5595. * The bytes follow and must be read separately with mpack_read_bytes()
  5596. * or mpack_read_bytes_inplace(). @ref mpack_done_bin() must be called
  5597. * once all bytes have been read.
  5598. *
  5599. * @throws mpack_error_type if the value is not a binary blob or if its size
  5600. * does not match.
  5601. */
  5602. MPACK_INLINE void mpack_expect_bin_size(mpack_reader_t* reader, uint32_t count) {
  5603. if (mpack_expect_bin(reader) != count)
  5604. mpack_reader_flag_error(reader, mpack_error_type);
  5605. }
  5606. /**
  5607. * Reads a binary blob into the given buffer, returning its size in bytes.
  5608. *
  5609. * For compatibility, this will accept if the underlying type is string or
  5610. * binary (since in MessagePack 1.0, strings and binary data were combined
  5611. * under the "raw" type which became string in 1.1.)
  5612. */
  5613. size_t mpack_expect_bin_buf(mpack_reader_t* reader, char* buf, size_t size);
  5614. /**
  5615. * Reads a binary blob with the exact given size into the given buffer.
  5616. *
  5617. * For compatibility, this will accept if the underlying type is string or
  5618. * binary (since in MessagePack 1.0, strings and binary data were combined
  5619. * under the "raw" type which became string in 1.1.)
  5620. *
  5621. * @throws mpack_error_type if the value is not a binary blob or if its size
  5622. * does not match.
  5623. */
  5624. void mpack_expect_bin_size_buf(mpack_reader_t* reader, char* buf, uint32_t size);
  5625. /**
  5626. * Reads a binary blob with the given total maximum size, allocating storage for it.
  5627. */
  5628. char* mpack_expect_bin_alloc(mpack_reader_t* reader, size_t maxsize, size_t* size);
  5629. /**
  5630. * @}
  5631. */
  5632. /**
  5633. * @name Extension Functions
  5634. * @{
  5635. */
  5636. #if MPACK_EXTENSIONS
  5637. /**
  5638. * Reads the start of an extension blob, returning its size in bytes and
  5639. * placing the type into @p type.
  5640. *
  5641. * The bytes follow and must be read separately with mpack_read_bytes()
  5642. * or mpack_read_bytes_inplace(). @ref mpack_done_ext() must be called
  5643. * once all bytes have been read.
  5644. *
  5645. * @p type will be a user-defined type in the range [0,127] or a reserved type
  5646. * in the range [-128,-2].
  5647. *
  5648. * mpack_error_type is raised if the value is not an extension blob. The @p
  5649. * type value is zero if an error occurs.
  5650. *
  5651. * @note This cannot be used to match a timestamp. @ref mpack_error_type will
  5652. * be flagged if the value is a timestamp. Use mpack_expect_timestamp() or
  5653. * mpack_expect_timestamp_truncate() instead.
  5654. *
  5655. * @note This requires @ref MPACK_EXTENSIONS.
  5656. *
  5657. * @warning Be careful when using reserved types. They may no longer be ext
  5658. * types in the future, and previously valid data containing reserved types may
  5659. * become invalid in the future.
  5660. */
  5661. uint32_t mpack_expect_ext(mpack_reader_t* reader, int8_t* type);
  5662. /**
  5663. * Reads the start of an extension blob, raising an error if its length is not
  5664. * at most the given number of bytes and placing the type into @p type.
  5665. *
  5666. * The bytes follow and must be read separately with mpack_read_bytes()
  5667. * or mpack_read_bytes_inplace(). @ref mpack_done_ext() must be called
  5668. * once all bytes have been read.
  5669. *
  5670. * mpack_error_type is raised if the value is not an extension blob or if its
  5671. * length does not match. The @p type value is zero if an error is raised.
  5672. *
  5673. * @p type will be a user-defined type in the range [0,127] or a reserved type
  5674. * in the range [-128,-2].
  5675. *
  5676. * @note This cannot be used to match a timestamp. @ref mpack_error_type will
  5677. * be flagged if the value is a timestamp. Use mpack_expect_timestamp() or
  5678. * mpack_expect_timestamp_truncate() instead.
  5679. *
  5680. * @note This requires @ref MPACK_EXTENSIONS.
  5681. *
  5682. * @warning Be careful when using reserved types. They may no longer be ext
  5683. * types in the future, and previously valid data containing reserved types may
  5684. * become invalid in the future.
  5685. *
  5686. * @see mpack_expect_ext()
  5687. */
  5688. MPACK_INLINE uint32_t mpack_expect_ext_max(mpack_reader_t* reader, int8_t* type, uint32_t maxsize) {
  5689. uint32_t length = mpack_expect_ext(reader, type);
  5690. if (length > maxsize) {
  5691. mpack_reader_flag_error(reader, mpack_error_type);
  5692. return 0;
  5693. }
  5694. return length;
  5695. }
  5696. /**
  5697. * Reads the start of an extension blob, raising an error if its length is not
  5698. * exactly the given number of bytes and placing the type into @p type.
  5699. *
  5700. * The bytes follow and must be read separately with mpack_read_bytes()
  5701. * or mpack_read_bytes_inplace(). @ref mpack_done_ext() must be called
  5702. * once all bytes have been read.
  5703. *
  5704. * mpack_error_type is raised if the value is not an extension blob or if its
  5705. * length does not match. The @p type value is zero if an error is raised.
  5706. *
  5707. * @p type will be a user-defined type in the range [0,127] or a reserved type
  5708. * in the range [-128,-2].
  5709. *
  5710. * @note This cannot be used to match a timestamp. @ref mpack_error_type will
  5711. * be flagged if the value is a timestamp. Use mpack_expect_timestamp() or
  5712. * mpack_expect_timestamp_truncate() instead.
  5713. *
  5714. * @note This requires @ref MPACK_EXTENSIONS.
  5715. *
  5716. * @warning Be careful when using reserved types. They may no longer be ext
  5717. * types in the future, and previously valid data containing reserved types may
  5718. * become invalid in the future.
  5719. *
  5720. * @see mpack_expect_ext()
  5721. */
  5722. MPACK_INLINE void mpack_expect_ext_size(mpack_reader_t* reader, int8_t* type, uint32_t count) {
  5723. if (mpack_expect_ext(reader, type) != count) {
  5724. *type = 0;
  5725. mpack_reader_flag_error(reader, mpack_error_type);
  5726. }
  5727. }
  5728. /**
  5729. * Reads an extension blob into the given buffer, returning its size in bytes
  5730. * and placing the type into @p type.
  5731. *
  5732. * mpack_error_type is raised if the value is not an extension blob or if its
  5733. * length does not match. The @p type value is zero if an error is raised.
  5734. *
  5735. * @p type will be a user-defined type in the range [0,127] or a reserved type
  5736. * in the range [-128,-2].
  5737. *
  5738. * @note This cannot be used to match a timestamp. @ref mpack_error_type will
  5739. * be flagged if the value is a timestamp. Use mpack_expect_timestamp() or
  5740. * mpack_expect_timestamp_truncate() instead.
  5741. *
  5742. * @warning Be careful when using reserved types. They may no longer be ext
  5743. * types in the future, and previously valid data containing reserved types may
  5744. * become invalid in the future.
  5745. *
  5746. * @note This requires @ref MPACK_EXTENSIONS.
  5747. *
  5748. * @see mpack_expect_ext()
  5749. */
  5750. size_t mpack_expect_ext_buf(mpack_reader_t* reader, int8_t* type, char* buf, size_t size);
  5751. #endif
  5752. #if MPACK_EXTENSIONS && defined(MPACK_MALLOC)
  5753. /**
  5754. * Reads an extension blob with the given total maximum size, allocating
  5755. * storage for it, and placing the type into @p type.
  5756. *
  5757. * mpack_error_type is raised if the value is not an extension blob or if its
  5758. * length does not match. The @p type value is zero if an error is raised.
  5759. *
  5760. * @p type will be a user-defined type in the range [0,127] or a reserved type
  5761. * in the range [-128,-2].
  5762. *
  5763. * @note This cannot be used to match a timestamp. @ref mpack_error_type will
  5764. * be flagged if the value is a timestamp. Use mpack_expect_timestamp() or
  5765. * mpack_expect_timestamp_truncate() instead.
  5766. *
  5767. * @warning Be careful when using reserved types. They may no longer be ext
  5768. * types in the future, and previously valid data containing reserved types may
  5769. * become invalid in the future.
  5770. *
  5771. * @note This requires @ref MPACK_EXTENSIONS and @ref MPACK_MALLOC.
  5772. *
  5773. * @see mpack_expect_ext()
  5774. */
  5775. char* mpack_expect_ext_alloc(mpack_reader_t* reader, int8_t* type, size_t maxsize, size_t* size);
  5776. #endif
  5777. /**
  5778. * @}
  5779. */
  5780. /**
  5781. * @name Special Functions
  5782. * @{
  5783. */
  5784. /**
  5785. * Reads a MessagePack object header (an MPack tag), expecting it to exactly
  5786. * match the given tag.
  5787. *
  5788. * If the type is compound (i.e. is a map, array, string, binary or
  5789. * extension type), additional reads are required to get the contained
  5790. * data, and the corresponding done function must be called when done.
  5791. *
  5792. * @throws mpack_error_type if the tag does not match
  5793. *
  5794. * @see mpack_read_bytes()
  5795. * @see mpack_done_array()
  5796. * @see mpack_done_map()
  5797. * @see mpack_done_str()
  5798. * @see mpack_done_bin()
  5799. * @see mpack_done_ext()
  5800. */
  5801. void mpack_expect_tag(mpack_reader_t* reader, mpack_tag_t tag);
  5802. /**
  5803. * Expects a string matching one of the strings in the given array,
  5804. * returning its array index.
  5805. *
  5806. * If the value does not match any of the given strings,
  5807. * @ref mpack_error_type is flagged. Use mpack_expect_enum_optional()
  5808. * if you want to allow other values than the given strings.
  5809. *
  5810. * If any error occurs or the reader is in an error state, @a count
  5811. * is returned.
  5812. *
  5813. * This can be used to quickly parse a string into an enum when the
  5814. * enum values range from 0 to @a count-1. If the last value in the
  5815. * enum is a special "count" value, it can be passed as the count,
  5816. * and the return value can be cast directly to the enum type.
  5817. *
  5818. * @code{.c}
  5819. * typedef enum { APPLE , BANANA , ORANGE , COUNT} fruit_t;
  5820. * const char* fruits[] = {"apple", "banana", "orange"};
  5821. *
  5822. * fruit_t fruit = (fruit_t)mpack_expect_enum(reader, fruits, COUNT);
  5823. * @endcode
  5824. *
  5825. * See @ref docs/expect.md for more examples.
  5826. *
  5827. * The maximum string length is the size of the buffer (strings are read in-place.)
  5828. *
  5829. * @param reader The reader
  5830. * @param strings An array of expected strings of length count
  5831. * @param count The number of strings
  5832. * @return The index of the matched string, or @a count in case of error
  5833. */
  5834. size_t mpack_expect_enum(mpack_reader_t* reader, const char* strings[], size_t count);
  5835. /**
  5836. * Expects a string matching one of the strings in the given array
  5837. * returning its array index, or @a count if no strings match.
  5838. *
  5839. * If the value is not a string, or it does not match any of the
  5840. * given strings, @a count is returned and no error is flagged.
  5841. *
  5842. * If any error occurs or the reader is in an error state, @a count
  5843. * is returned.
  5844. *
  5845. * This can be used to quickly parse a string into an enum when the
  5846. * enum values range from 0 to @a count-1. If the last value in the
  5847. * enum is a special "count" value, it can be passed as the count,
  5848. * and the return value can be cast directly to the enum type.
  5849. *
  5850. * @code{.c}
  5851. * typedef enum { APPLE , BANANA , ORANGE , COUNT} fruit_t;
  5852. * const char* fruits[] = {"apple", "banana", "orange"};
  5853. *
  5854. * fruit_t fruit = (fruit_t)mpack_expect_enum_optional(reader, fruits, COUNT);
  5855. * @endcode
  5856. *
  5857. * See @ref docs/expect.md for more examples.
  5858. *
  5859. * The maximum string length is the size of the buffer (strings are read in-place.)
  5860. *
  5861. * @param reader The reader
  5862. * @param strings An array of expected strings of length count
  5863. * @param count The number of strings
  5864. *
  5865. * @return The index of the matched string, or @a count if it does not
  5866. * match or an error occurs
  5867. */
  5868. size_t mpack_expect_enum_optional(mpack_reader_t* reader, const char* strings[], size_t count);
  5869. /**
  5870. * Expects an unsigned integer map key between 0 and count-1, marking it
  5871. * as found in the given bool array and returning it.
  5872. *
  5873. * This is a helper for switching among int keys in a map. It is
  5874. * typically used with an enum to define the key values. It should
  5875. * be called in the expression of a switch() statement. See @ref
  5876. * docs/expect.md for an example.
  5877. *
  5878. * The found array must be cleared before expecting the first key. If the
  5879. * flag for a given key is already set when found (i.e. the map contains a
  5880. * duplicate key), mpack_error_invalid is flagged.
  5881. *
  5882. * If the key is not a non-negative integer, or if the key is @a count or
  5883. * larger, @a count is returned and no error is flagged. If you want an error
  5884. * on unrecognized keys, flag an error in the default case in your switch;
  5885. * otherwise you must call mpack_discard() to discard its content.
  5886. *
  5887. * @param reader The reader
  5888. * @param found An array of bool flags of length count
  5889. * @param count The number of values in the found array, and one more than the
  5890. * maximum allowed key
  5891. *
  5892. * @see @ref docs/expect.md
  5893. */
  5894. size_t mpack_expect_key_uint(mpack_reader_t* reader, bool found[], size_t count);
  5895. /**
  5896. * Expects a string map key matching one of the strings in the given key list,
  5897. * marking it as found in the given bool array and returning its index.
  5898. *
  5899. * This is a helper for switching among string keys in a map. It is
  5900. * typically used with an enum with names matching the strings in the
  5901. * array to define the key indices. It should be called in the expression
  5902. * of a switch() statement. See @ref docs/expect.md for an example.
  5903. *
  5904. * The found array must be cleared before expecting the first key. If the
  5905. * flag for a given key is already set when found (i.e. the map contains a
  5906. * duplicate key), mpack_error_invalid is flagged.
  5907. *
  5908. * If the key is unrecognized, count is returned and no error is flagged. If
  5909. * you want an error on unrecognized keys, flag an error in the default case
  5910. * in your switch; otherwise you must call mpack_discard() to discard its content.
  5911. *
  5912. * The maximum key length is the size of the buffer (keys are read in-place.)
  5913. *
  5914. * @param reader The reader
  5915. * @param keys An array of expected string keys of length count
  5916. * @param found An array of bool flags of length count
  5917. * @param count The number of values in the keys and found arrays
  5918. *
  5919. * @see @ref docs/expect.md
  5920. */
  5921. size_t mpack_expect_key_cstr(mpack_reader_t* reader, const char* keys[],
  5922. bool found[], size_t count);
  5923. /**
  5924. * @}
  5925. */
  5926. /**
  5927. * @}
  5928. */
  5929. #endif
  5930. MPACK_EXTERN_C_END
  5931. MPACK_SILENCE_WARNINGS_END
  5932. #endif
  5933. /* mpack/mpack-node.h.h */
  5934. /**
  5935. * @file
  5936. *
  5937. * Declares the MPack dynamic Node API.
  5938. */
  5939. #ifndef MPACK_NODE_H
  5940. #define MPACK_NODE_H 1
  5941. /* #include "mpack-reader.h" */
  5942. MPACK_SILENCE_WARNINGS_BEGIN
  5943. MPACK_EXTERN_C_BEGIN
  5944. #if MPACK_NODE
  5945. /**
  5946. * @defgroup node Node API
  5947. *
  5948. * The MPack Node API allows you to parse a chunk of MessagePack into a
  5949. * dynamically typed data structure, providing random access to the parsed
  5950. * data.
  5951. *
  5952. * See @ref docs/node.md for examples.
  5953. *
  5954. * @{
  5955. */
  5956. /**
  5957. * A handle to node data in a parsed MPack tree.
  5958. *
  5959. * Nodes represent either primitive values or compound types. If a
  5960. * node is a compound type, it contains a pointer to its child nodes,
  5961. * or a pointer to its underlying data.
  5962. *
  5963. * Nodes are immutable.
  5964. *
  5965. * @note @ref mpack_node_t is an opaque reference to the node data, not the
  5966. * node data itself. (It contains pointers to both the node data and the tree.)
  5967. * It is passed by value in the Node API.
  5968. */
  5969. typedef struct mpack_node_t mpack_node_t;
  5970. /**
  5971. * The storage for nodes in an MPack tree.
  5972. *
  5973. * You only need to use this if you intend to provide your own storage
  5974. * for nodes instead of letting the tree allocate it.
  5975. *
  5976. * @ref mpack_node_data_t is 16 bytes on most common architectures (32-bit
  5977. * and 64-bit.)
  5978. */
  5979. typedef struct mpack_node_data_t mpack_node_data_t;
  5980. /**
  5981. * An MPack tree parser to parse a blob or stream of MessagePack.
  5982. *
  5983. * When a message is parsed, the tree contains a single root node which
  5984. * contains all parsed data. The tree and its nodes are immutable.
  5985. */
  5986. typedef struct mpack_tree_t mpack_tree_t;
  5987. /**
  5988. * An error handler function to be called when an error is flagged on
  5989. * the tree.
  5990. *
  5991. * The error handler will only be called once on the first error flagged;
  5992. * any subsequent node reads and errors are ignored, and the tree is
  5993. * permanently in that error state.
  5994. *
  5995. * MPack is safe against non-local jumps out of error handler callbacks.
  5996. * This means you are allowed to longjmp or throw an exception (in C++,
  5997. * Objective-C, or with SEH) out of this callback.
  5998. *
  5999. * Bear in mind when using longjmp that local non-volatile variables that
  6000. * have changed are undefined when setjmp() returns, so you can't put the
  6001. * tree on the stack in the same activation frame as the setjmp without
  6002. * declaring it volatile.
  6003. *
  6004. * You must still eventually destroy the tree. It is not destroyed
  6005. * automatically when an error is flagged. It is safe to destroy the
  6006. * tree within this error callback, but you will either need to perform
  6007. * a non-local jump, or store something in your context to identify
  6008. * that the tree is destroyed since any future accesses to it cause
  6009. * undefined behavior.
  6010. */
  6011. typedef void (*mpack_tree_error_t)(mpack_tree_t* tree, mpack_error_t error);
  6012. /**
  6013. * The MPack tree's read function. It should fill the buffer with as many bytes
  6014. * as are immediately available up to the given @c count, returning the number
  6015. * of bytes written to the buffer.
  6016. *
  6017. * In case of error, it should flag an appropriate error on the reader
  6018. * (usually @ref mpack_error_io.)
  6019. *
  6020. * The blocking or non-blocking behaviour of the read should match whether you
  6021. * are using mpack_tree_parse() or mpack_tree_try_parse().
  6022. *
  6023. * If you are using mpack_tree_parse(), the read should block until at least
  6024. * one byte is read. If you return 0, mpack_tree_parse() will raise @ref
  6025. * mpack_error_io.
  6026. *
  6027. * If you are using mpack_tree_try_parse(), the read function can always
  6028. * return 0, and must never block waiting for data (otherwise
  6029. * mpack_tree_try_parse() would be equivalent to mpack_tree_parse().)
  6030. * When you return 0, mpack_tree_try_parse() will return false without flagging
  6031. * an error.
  6032. */
  6033. typedef size_t (*mpack_tree_read_t)(mpack_tree_t* tree, char* buffer, size_t count);
  6034. /**
  6035. * A teardown function to be called when the tree is destroyed.
  6036. */
  6037. typedef void (*mpack_tree_teardown_t)(mpack_tree_t* tree);
  6038. /* Hide internals from documentation */
  6039. /** @cond */
  6040. struct mpack_node_t {
  6041. mpack_node_data_t* data;
  6042. mpack_tree_t* tree;
  6043. };
  6044. struct mpack_node_data_t {
  6045. mpack_type_t type;
  6046. /*
  6047. * The element count if the type is an array;
  6048. * the number of key/value pairs if the type is map;
  6049. * or the number of bytes if the type is str, bin or ext.
  6050. */
  6051. uint32_t len;
  6052. union {
  6053. bool b; /* The value if the type is bool. */
  6054. #if MPACK_FLOAT
  6055. float f; /* The value if the type is float. */
  6056. #else
  6057. uint32_t f; /*< The raw value if the type is float. */
  6058. #endif
  6059. #if MPACK_DOUBLE
  6060. double d; /* The value if the type is double. */
  6061. #else
  6062. uint64_t d; /*< The raw value if the type is double. */
  6063. #endif
  6064. int64_t i; /* The value if the type is signed int. */
  6065. uint64_t u; /* The value if the type is unsigned int. */
  6066. size_t offset; /* The byte offset for str, bin and ext */
  6067. mpack_node_data_t* children; /* The children for map or array */
  6068. } value;
  6069. };
  6070. typedef struct mpack_tree_page_t {
  6071. struct mpack_tree_page_t* next;
  6072. mpack_node_data_t nodes[1]; // variable size
  6073. } mpack_tree_page_t;
  6074. typedef enum mpack_tree_parse_state_t {
  6075. mpack_tree_parse_state_not_started,
  6076. mpack_tree_parse_state_in_progress,
  6077. mpack_tree_parse_state_parsed,
  6078. } mpack_tree_parse_state_t;
  6079. typedef struct mpack_level_t {
  6080. mpack_node_data_t* child;
  6081. size_t left; // children left in level
  6082. } mpack_level_t;
  6083. typedef struct mpack_tree_parser_t {
  6084. mpack_tree_parse_state_t state;
  6085. // We keep track of the number of "possible nodes" left in the data rather
  6086. // than the number of bytes.
  6087. //
  6088. // When a map or array is parsed, we ensure at least one byte for each child
  6089. // exists and subtract them right away. This ensures that if ever a map or
  6090. // array declares more elements than could possibly be contained in the data,
  6091. // we will error out immediately rather than allocating storage for them.
  6092. //
  6093. // For example malicious data that repeats 0xDE 0xFF 0xFF (start of a map
  6094. // with 65536 key-value pairs) would otherwise cause us to run out of
  6095. // memory. With this, the parser can allocate at most as many nodes as
  6096. // there are bytes in the data (plus the paging overhead, 12%.) An error
  6097. // will be flagged immediately if and when there isn't enough data left to
  6098. // fully read all children of all open compound types on the parsing stack.
  6099. //
  6100. // Once an entire message has been parsed (and there are no nodes left to
  6101. // parse whose bytes have been subtracted), this matches the number of left
  6102. // over bytes in the data.
  6103. size_t possible_nodes_left;
  6104. mpack_node_data_t* nodes; // next node in current page/pool
  6105. size_t nodes_left; // nodes left in current page/pool
  6106. size_t current_node_reserved;
  6107. size_t level;
  6108. #ifdef MPACK_MALLOC
  6109. // It's much faster to allocate the initial parsing stack inline within the
  6110. // parser. We replace it with a heap allocation if we need to grow it.
  6111. mpack_level_t* stack;
  6112. size_t stack_capacity;
  6113. bool stack_owned;
  6114. mpack_level_t stack_local[MPACK_NODE_INITIAL_DEPTH];
  6115. #else
  6116. // Without malloc(), we have to reserve a parsing stack the maximum allowed
  6117. // parsing depth.
  6118. mpack_level_t stack[MPACK_NODE_MAX_DEPTH_WITHOUT_MALLOC];
  6119. #endif
  6120. } mpack_tree_parser_t;
  6121. struct mpack_tree_t {
  6122. mpack_tree_error_t error_fn; /* Function to call on error */
  6123. mpack_tree_read_t read_fn; /* Function to call to read more data */
  6124. mpack_tree_teardown_t teardown; /* Function to teardown the context on destroy */
  6125. void* context; /* Context for tree callbacks */
  6126. mpack_node_data_t nil_node; /* a nil node to be returned in case of error */
  6127. mpack_node_data_t missing_node; /* a missing node to be returned in optional lookups */
  6128. mpack_error_t error;
  6129. #ifdef MPACK_MALLOC
  6130. char* buffer;
  6131. size_t buffer_capacity;
  6132. #endif
  6133. const char* data;
  6134. size_t data_length; // length of data (and content of buffer, if used)
  6135. size_t size; // size in bytes of tree (usually matches data_length, but not if tree has trailing data)
  6136. size_t node_count; // total number of nodes in tree (across all pages)
  6137. size_t max_size; // maximum message size
  6138. size_t max_nodes; // maximum nodes in a message
  6139. mpack_tree_parser_t parser;
  6140. mpack_node_data_t* root;
  6141. mpack_node_data_t* pool; // pool, or NULL if no pool provided
  6142. size_t pool_count;
  6143. #ifdef MPACK_MALLOC
  6144. mpack_tree_page_t* next;
  6145. #endif
  6146. };
  6147. // internal functions
  6148. MPACK_INLINE mpack_node_t mpack_node(mpack_tree_t* tree, mpack_node_data_t* data) {
  6149. mpack_node_t node;
  6150. node.data = data;
  6151. node.tree = tree;
  6152. return node;
  6153. }
  6154. MPACK_INLINE mpack_node_data_t* mpack_node_child(mpack_node_t node, size_t child) {
  6155. return node.data->value.children + child;
  6156. }
  6157. MPACK_INLINE mpack_node_t mpack_tree_nil_node(mpack_tree_t* tree) {
  6158. return mpack_node(tree, &tree->nil_node);
  6159. }
  6160. MPACK_INLINE mpack_node_t mpack_tree_missing_node(mpack_tree_t* tree) {
  6161. return mpack_node(tree, &tree->missing_node);
  6162. }
  6163. /** @endcond */
  6164. /**
  6165. * @name Tree Initialization
  6166. * @{
  6167. */
  6168. #ifdef MPACK_MALLOC
  6169. /**
  6170. * Initializes a tree parser with the given data.
  6171. *
  6172. * Configure the tree if desired, then call mpack_tree_parse() to parse it. The
  6173. * tree will allocate pages of nodes as needed and will free them when
  6174. * destroyed.
  6175. *
  6176. * The tree must be destroyed with mpack_tree_destroy().
  6177. *
  6178. * Any string or blob data types reference the original data, so the given data
  6179. * pointer must remain valid until after the tree is destroyed.
  6180. */
  6181. void mpack_tree_init_data(mpack_tree_t* tree, const char* data, size_t length);
  6182. /**
  6183. * Deprecated.
  6184. *
  6185. * \deprecated Renamed to mpack_tree_init_data().
  6186. */
  6187. MPACK_INLINE void mpack_tree_init(mpack_tree_t* tree, const char* data, size_t length) {
  6188. mpack_tree_init_data(tree, data, length);
  6189. }
  6190. /**
  6191. * Initializes a tree parser from an unbounded stream, or a stream of
  6192. * unknown length.
  6193. *
  6194. * The parser can be used to read a single message from a stream of unknown
  6195. * length, or multiple messages from an unbounded stream, allowing it to
  6196. * be used for RPC communication. Call @ref mpack_tree_parse() to parse
  6197. * a message from a blocking stream, or @ref mpack_tree_try_parse() for a
  6198. * non-blocking stream.
  6199. *
  6200. * The stream will use a growable internal buffer to store the most recent
  6201. * message, as well as allocated pages of nodes for the parse tree.
  6202. *
  6203. * Maximum allowances for message size and node count must be specified in this
  6204. * function (since the stream is unbounded.) They can be changed later with
  6205. * @ref mpack_tree_set_limits().
  6206. *
  6207. * @param tree The tree parser
  6208. * @param read_fn The read function
  6209. * @param context The context for the read function
  6210. * @param max_message_size The maximum size of a message in bytes
  6211. * @param max_message_nodes The maximum number of nodes per message. See
  6212. * @ref mpack_node_data_t for the size of nodes.
  6213. *
  6214. * @see mpack_tree_read_t
  6215. * @see mpack_reader_context()
  6216. */
  6217. void mpack_tree_init_stream(mpack_tree_t* tree, mpack_tree_read_t read_fn, void* context,
  6218. size_t max_message_size, size_t max_message_nodes);
  6219. #endif
  6220. /**
  6221. * Initializes a tree parser with the given data, using the given node data
  6222. * pool to store the results.
  6223. *
  6224. * Configure the tree if desired, then call mpack_tree_parse() to parse it.
  6225. *
  6226. * If the data does not fit in the pool, @ref mpack_error_too_big will be flagged
  6227. * on the tree.
  6228. *
  6229. * The tree must be destroyed with mpack_tree_destroy(), even if parsing fails.
  6230. */
  6231. void mpack_tree_init_pool(mpack_tree_t* tree, const char* data, size_t length,
  6232. mpack_node_data_t* node_pool, size_t node_pool_count);
  6233. /**
  6234. * Initializes an MPack tree directly into an error state. Use this if you
  6235. * are writing a wrapper to another <tt>mpack_tree_init*()</tt> function which
  6236. * can fail its setup.
  6237. */
  6238. void mpack_tree_init_error(mpack_tree_t* tree, mpack_error_t error);
  6239. #if MPACK_STDIO
  6240. /**
  6241. * Initializes a tree to parse the given file. The tree must be destroyed with
  6242. * mpack_tree_destroy(), even if parsing fails.
  6243. *
  6244. * The file is opened, loaded fully into memory, and closed before this call
  6245. * returns.
  6246. *
  6247. * @param tree The tree to initialize
  6248. * @param filename The filename passed to fopen() to read the file
  6249. * @param max_bytes The maximum size of file to load, or 0 for unlimited size.
  6250. */
  6251. void mpack_tree_init_filename(mpack_tree_t* tree, const char* filename, size_t max_bytes);
  6252. /**
  6253. * Deprecated.
  6254. *
  6255. * \deprecated Renamed to mpack_tree_init_filename().
  6256. */
  6257. MPACK_INLINE void mpack_tree_init_file(mpack_tree_t* tree, const char* filename, size_t max_bytes) {
  6258. mpack_tree_init_filename(tree, filename, max_bytes);
  6259. }
  6260. /**
  6261. * Initializes a tree to parse the given libc FILE. This can be used to
  6262. * read from stdin, or from a file opened separately.
  6263. *
  6264. * The tree must be destroyed with mpack_tree_destroy(), even if parsing fails.
  6265. *
  6266. * The FILE is fully loaded fully into memory (and closed if requested) before
  6267. * this call returns.
  6268. *
  6269. * @param tree The tree to initialize.
  6270. * @param stdfile The FILE.
  6271. * @param max_bytes The maximum size of file to load, or 0 for unlimited size.
  6272. * @param close_when_done If true, fclose() will be called on the FILE when it
  6273. * is no longer needed. If false, the file will not be closed when
  6274. * reading is done.
  6275. *
  6276. * @warning The tree will read all data in the FILE before parsing it. If this
  6277. * is used on stdin, the parser will block until it is closed, even if
  6278. * a complete message has been written to it!
  6279. */
  6280. void mpack_tree_init_stdfile(mpack_tree_t* tree, FILE* stdfile, size_t max_bytes, bool close_when_done);
  6281. #endif
  6282. /**
  6283. * @}
  6284. */
  6285. /**
  6286. * @name Tree Functions
  6287. * @{
  6288. */
  6289. /**
  6290. * Sets the maximum byte size and maximum number of nodes allowed per message.
  6291. *
  6292. * The default is SIZE_MAX (no limit) unless @ref mpack_tree_init_stream() is
  6293. * called (where maximums are required.)
  6294. *
  6295. * If a pool of nodes is used, the node limit is the lesser of this limit and
  6296. * the pool size.
  6297. *
  6298. * @param tree The tree parser
  6299. * @param max_message_size The maximum size of a message in bytes
  6300. * @param max_message_nodes The maximum number of nodes per message. See
  6301. * @ref mpack_node_data_t for the size of nodes.
  6302. */
  6303. void mpack_tree_set_limits(mpack_tree_t* tree, size_t max_message_size,
  6304. size_t max_message_nodes);
  6305. /**
  6306. * Parses a MessagePack message into a tree of immutable nodes.
  6307. *
  6308. * If successful, the root node will be available under @ref mpack_tree_root().
  6309. * If not, an appropriate error will be flagged.
  6310. *
  6311. * This can be called repeatedly to parse a series of messages from a data
  6312. * source. When this is called, all previous nodes from this tree and their
  6313. * contents (including the root node) are invalidated.
  6314. *
  6315. * If this is called with a stream (see @ref mpack_tree_init_stream()), the
  6316. * stream must block until data is available. (Otherwise, if this is called on
  6317. * a non-blocking stream, parsing will fail with @ref mpack_error_io when the
  6318. * fill function returns 0.)
  6319. *
  6320. * There is no way to recover a tree in an error state. It must be destroyed.
  6321. */
  6322. void mpack_tree_parse(mpack_tree_t* tree);
  6323. /**
  6324. * Attempts to parse a MessagePack message from a non-blocking stream into a
  6325. * tree of immutable nodes.
  6326. *
  6327. * A non-blocking read function must have been passed to the tree in
  6328. * mpack_tree_init_stream().
  6329. *
  6330. * If this returns true, a message is available under
  6331. * @ref mpack_tree_root(). The tree nodes and data will be valid until
  6332. * the next time a parse is started.
  6333. *
  6334. * If this returns false, no message is available, because either not enough
  6335. * data is available yet or an error has occurred. You must check the tree for
  6336. * errors whenever this returns false. If there is no error, you should try
  6337. * again later when more data is available. (You will want to select()/poll()
  6338. * on the underlying socket or use some other asynchronous mechanism to
  6339. * determine when it has data.)
  6340. *
  6341. * There is no way to recover a tree in an error state. It must be destroyed.
  6342. *
  6343. * @see mpack_tree_init_stream()
  6344. */
  6345. bool mpack_tree_try_parse(mpack_tree_t* tree);
  6346. /**
  6347. * Returns the root node of the tree, if the tree is not in an error state.
  6348. * Returns a nil node otherwise.
  6349. *
  6350. * @warning You must call mpack_tree_parse() before calling this. If
  6351. * @ref mpack_tree_parse() was never called, the tree will assert.
  6352. */
  6353. mpack_node_t mpack_tree_root(mpack_tree_t* tree);
  6354. /**
  6355. * Returns the error state of the tree.
  6356. */
  6357. MPACK_INLINE mpack_error_t mpack_tree_error(mpack_tree_t* tree) {
  6358. return tree->error;
  6359. }
  6360. /**
  6361. * Returns the size in bytes of the current parsed message.
  6362. *
  6363. * If there is something in the buffer after the MessagePack object, this can
  6364. * be used to find it.
  6365. *
  6366. * This is zero if an error occurred during tree parsing (since the
  6367. * portion of the data that the first complete object occupies cannot
  6368. * be determined if the data is invalid or corrupted.)
  6369. */
  6370. MPACK_INLINE size_t mpack_tree_size(mpack_tree_t* tree) {
  6371. return tree->size;
  6372. }
  6373. /**
  6374. * Destroys the tree.
  6375. */
  6376. mpack_error_t mpack_tree_destroy(mpack_tree_t* tree);
  6377. /**
  6378. * Sets the custom pointer to pass to the tree callbacks, such as teardown.
  6379. *
  6380. * @param tree The MPack tree.
  6381. * @param context User data to pass to the tree callbacks.
  6382. *
  6383. * @see mpack_reader_context()
  6384. */
  6385. MPACK_INLINE void mpack_tree_set_context(mpack_tree_t* tree, void* context) {
  6386. tree->context = context;
  6387. }
  6388. /**
  6389. * Returns the custom context for tree callbacks.
  6390. *
  6391. * @see mpack_tree_set_context
  6392. * @see mpack_tree_init_stream
  6393. */
  6394. MPACK_INLINE void* mpack_tree_context(mpack_tree_t* tree) {
  6395. return tree->context;
  6396. }
  6397. /**
  6398. * Sets the error function to call when an error is flagged on the tree.
  6399. *
  6400. * This should normally be used with mpack_tree_set_context() to register
  6401. * a custom pointer to pass to the error function.
  6402. *
  6403. * See the definition of mpack_tree_error_t for more information about
  6404. * what you can do from an error callback.
  6405. *
  6406. * @see mpack_tree_error_t
  6407. * @param tree The MPack tree.
  6408. * @param error_fn The function to call when an error is flagged on the tree.
  6409. */
  6410. MPACK_INLINE void mpack_tree_set_error_handler(mpack_tree_t* tree, mpack_tree_error_t error_fn) {
  6411. tree->error_fn = error_fn;
  6412. }
  6413. /**
  6414. * Sets the teardown function to call when the tree is destroyed.
  6415. *
  6416. * This should normally be used with mpack_tree_set_context() to register
  6417. * a custom pointer to pass to the teardown function.
  6418. *
  6419. * @param tree The MPack tree.
  6420. * @param teardown The function to call when the tree is destroyed.
  6421. */
  6422. MPACK_INLINE void mpack_tree_set_teardown(mpack_tree_t* tree, mpack_tree_teardown_t teardown) {
  6423. tree->teardown = teardown;
  6424. }
  6425. /**
  6426. * Places the tree in the given error state, calling the error callback if one
  6427. * is set.
  6428. *
  6429. * This allows you to externally flag errors, for example if you are validating
  6430. * data as you read it.
  6431. *
  6432. * If the tree is already in an error state, this call is ignored and no
  6433. * error callback is called.
  6434. */
  6435. void mpack_tree_flag_error(mpack_tree_t* tree, mpack_error_t error);
  6436. /**
  6437. * @}
  6438. */
  6439. /**
  6440. * @name Node Core Functions
  6441. * @{
  6442. */
  6443. /**
  6444. * Places the node's tree in the given error state, calling the error callback
  6445. * if one is set.
  6446. *
  6447. * This allows you to externally flag errors, for example if you are validating
  6448. * data as you read it.
  6449. *
  6450. * If the tree is already in an error state, this call is ignored and no
  6451. * error callback is called.
  6452. */
  6453. void mpack_node_flag_error(mpack_node_t node, mpack_error_t error);
  6454. /**
  6455. * Returns the error state of the node's tree.
  6456. */
  6457. MPACK_INLINE mpack_error_t mpack_node_error(mpack_node_t node) {
  6458. return mpack_tree_error(node.tree);
  6459. }
  6460. /**
  6461. * Returns a tag describing the given node, or a nil tag if the
  6462. * tree is in an error state.
  6463. */
  6464. mpack_tag_t mpack_node_tag(mpack_node_t node);
  6465. /** @cond */
  6466. #if MPACK_DEBUG && MPACK_STDIO
  6467. /*
  6468. * Converts a node to a pseudo-JSON string for debugging purposes, placing the
  6469. * result in the given buffer with a null-terminator.
  6470. *
  6471. * If the buffer does not have enough space, the result will be truncated (but
  6472. * it is guaranteed to be null-terminated.)
  6473. *
  6474. * This is only available in debug mode, and only if stdio is available (since
  6475. * it uses snprintf().) It's strictly for debugging purposes.
  6476. */
  6477. void mpack_node_print_to_buffer(mpack_node_t node, char* buffer, size_t buffer_size);
  6478. /*
  6479. * Converts a node to pseudo-JSON for debugging purposes, calling the given
  6480. * callback as many times as is necessary to output the character data.
  6481. *
  6482. * No null-terminator or trailing newline will be written.
  6483. *
  6484. * This is only available in debug mode, and only if stdio is available (since
  6485. * it uses snprintf().) It's strictly for debugging purposes.
  6486. */
  6487. void mpack_node_print_to_callback(mpack_node_t node, mpack_print_callback_t callback, void* context);
  6488. /*
  6489. * Converts a node to pseudo-JSON for debugging purposes
  6490. * and pretty-prints it to the given file.
  6491. *
  6492. * This is only available in debug mode, and only if stdio is available (since
  6493. * it uses snprintf().) It's strictly for debugging purposes.
  6494. */
  6495. void mpack_node_print_to_file(mpack_node_t node, FILE* file);
  6496. /*
  6497. * Converts a node to pseudo-JSON for debugging purposes
  6498. * and pretty-prints it to stdout.
  6499. *
  6500. * This is only available in debug mode, and only if stdio is available (since
  6501. * it uses snprintf().) It's strictly for debugging purposes.
  6502. */
  6503. MPACK_INLINE void mpack_node_print_to_stdout(mpack_node_t node) {
  6504. mpack_node_print_to_file(node, stdout);
  6505. }
  6506. /*
  6507. * Deprecated.
  6508. *
  6509. * \deprecated Renamed to mpack_node_print_to_stdout().
  6510. */
  6511. MPACK_INLINE void mpack_node_print(mpack_node_t node) {
  6512. mpack_node_print_to_stdout(node);
  6513. }
  6514. #endif
  6515. /** @endcond */
  6516. /**
  6517. * @}
  6518. */
  6519. /**
  6520. * @name Node Primitive Value Functions
  6521. * @{
  6522. */
  6523. /**
  6524. * Returns the type of the node.
  6525. */
  6526. mpack_type_t mpack_node_type(mpack_node_t node);
  6527. /**
  6528. * Returns true if the given node is a nil node; false otherwise.
  6529. *
  6530. * To ensure that a node is nil and flag an error otherwise, use
  6531. * mpack_node_nil().
  6532. */
  6533. bool mpack_node_is_nil(mpack_node_t node);
  6534. /**
  6535. * Returns true if the given node handle indicates a missing node; false otherwise.
  6536. *
  6537. * To ensure that a node is missing and flag an error otherwise, use
  6538. * mpack_node_missing().
  6539. */
  6540. bool mpack_node_is_missing(mpack_node_t node);
  6541. /**
  6542. * Checks that the given node is of nil type, raising @ref mpack_error_type
  6543. * otherwise.
  6544. *
  6545. * Use mpack_node_is_nil() to return whether the node is nil.
  6546. */
  6547. void mpack_node_nil(mpack_node_t node);
  6548. /**
  6549. * Checks that the given node indicates a missing node, raising @ref
  6550. * mpack_error_type otherwise.
  6551. *
  6552. * Use mpack_node_is_missing() to return whether the node is missing.
  6553. */
  6554. void mpack_node_missing(mpack_node_t node);
  6555. /**
  6556. * Returns the bool value of the node. If this node is not of the correct
  6557. * type, false is returned and mpack_error_type is raised.
  6558. */
  6559. bool mpack_node_bool(mpack_node_t node);
  6560. /**
  6561. * Checks if the given node is of bool type with value true, raising
  6562. * mpack_error_type otherwise.
  6563. */
  6564. void mpack_node_true(mpack_node_t node);
  6565. /**
  6566. * Checks if the given node is of bool type with value false, raising
  6567. * mpack_error_type otherwise.
  6568. */
  6569. void mpack_node_false(mpack_node_t node);
  6570. /**
  6571. * Returns the 8-bit unsigned value of the node. If this node is not
  6572. * of a compatible type, @ref mpack_error_type is raised and zero is returned.
  6573. */
  6574. uint8_t mpack_node_u8(mpack_node_t node);
  6575. /**
  6576. * Returns the 8-bit signed value of the node. If this node is not
  6577. * of a compatible type, @ref mpack_error_type is raised and zero is returned.
  6578. */
  6579. int8_t mpack_node_i8(mpack_node_t node);
  6580. /**
  6581. * Returns the 16-bit unsigned value of the node. If this node is not
  6582. * of a compatible type, @ref mpack_error_type is raised and zero is returned.
  6583. */
  6584. uint16_t mpack_node_u16(mpack_node_t node);
  6585. /**
  6586. * Returns the 16-bit signed value of the node. If this node is not
  6587. * of a compatible type, @ref mpack_error_type is raised and zero is returned.
  6588. */
  6589. int16_t mpack_node_i16(mpack_node_t node);
  6590. /**
  6591. * Returns the 32-bit unsigned value of the node. If this node is not
  6592. * of a compatible type, @ref mpack_error_type is raised and zero is returned.
  6593. */
  6594. uint32_t mpack_node_u32(mpack_node_t node);
  6595. /**
  6596. * Returns the 32-bit signed value of the node. If this node is not
  6597. * of a compatible type, @ref mpack_error_type is raised and zero is returned.
  6598. */
  6599. int32_t mpack_node_i32(mpack_node_t node);
  6600. /**
  6601. * Returns the 64-bit unsigned value of the node. If this node is not
  6602. * of a compatible type, @ref mpack_error_type is raised, and zero is returned.
  6603. */
  6604. uint64_t mpack_node_u64(mpack_node_t node);
  6605. /**
  6606. * Returns the 64-bit signed value of the node. If this node is not
  6607. * of a compatible type, @ref mpack_error_type is raised and zero is returned.
  6608. */
  6609. int64_t mpack_node_i64(mpack_node_t node);
  6610. /**
  6611. * Returns the unsigned int value of the node.
  6612. *
  6613. * Returns zero if an error occurs.
  6614. *
  6615. * @throws mpack_error_type If the node is not an integer type or does not fit in the range of an unsigned int
  6616. */
  6617. unsigned int mpack_node_uint(mpack_node_t node);
  6618. /**
  6619. * Returns the int value of the node.
  6620. *
  6621. * Returns zero if an error occurs.
  6622. *
  6623. * @throws mpack_error_type If the node is not an integer type or does not fit in the range of an int
  6624. */
  6625. int mpack_node_int(mpack_node_t node);
  6626. #if MPACK_FLOAT
  6627. /**
  6628. * Returns the float value of the node. The underlying value can be an
  6629. * integer, float or double; the value is converted to a float.
  6630. *
  6631. * @note Reading a double or a large integer with this function can incur a
  6632. * loss of precision.
  6633. *
  6634. * @throws mpack_error_type if the underlying value is not a float, double or integer.
  6635. */
  6636. float mpack_node_float(mpack_node_t node);
  6637. #endif
  6638. #if MPACK_DOUBLE
  6639. /**
  6640. * Returns the double value of the node. The underlying value can be an
  6641. * integer, float or double; the value is converted to a double.
  6642. *
  6643. * @note Reading a very large integer with this function can incur a
  6644. * loss of precision.
  6645. *
  6646. * @throws mpack_error_type if the underlying value is not a float, double or integer.
  6647. */
  6648. double mpack_node_double(mpack_node_t node);
  6649. #endif
  6650. #if MPACK_FLOAT
  6651. /**
  6652. * Returns the float value of the node. The underlying value must be a float,
  6653. * not a double or an integer. This ensures no loss of precision can occur.
  6654. *
  6655. * @throws mpack_error_type if the underlying value is not a float.
  6656. */
  6657. float mpack_node_float_strict(mpack_node_t node);
  6658. #endif
  6659. #if MPACK_DOUBLE
  6660. /**
  6661. * Returns the double value of the node. The underlying value must be a float
  6662. * or double, not an integer. This ensures no loss of precision can occur.
  6663. *
  6664. * @throws mpack_error_type if the underlying value is not a float or double.
  6665. */
  6666. double mpack_node_double_strict(mpack_node_t node);
  6667. #endif
  6668. #if !MPACK_FLOAT
  6669. /**
  6670. * Returns the float value of the node as a raw uint32_t. The underlying value
  6671. * must be a float, not a double or an integer.
  6672. *
  6673. * @throws mpack_error_type if the underlying value is not a float.
  6674. */
  6675. uint32_t mpack_node_raw_float(mpack_node_t node);
  6676. #endif
  6677. #if !MPACK_DOUBLE
  6678. /**
  6679. * Returns the double value of the node as a raw uint64_t. The underlying value
  6680. * must be a double, not a float or an integer.
  6681. *
  6682. * @throws mpack_error_type if the underlying value is not a float or double.
  6683. */
  6684. uint64_t mpack_node_raw_double(mpack_node_t node);
  6685. #endif
  6686. #if MPACK_EXTENSIONS
  6687. /**
  6688. * Returns a timestamp.
  6689. *
  6690. * @note This requires @ref MPACK_EXTENSIONS.
  6691. *
  6692. * @throws mpack_error_type if the underlying value is not a timestamp.
  6693. */
  6694. mpack_timestamp_t mpack_node_timestamp(mpack_node_t node);
  6695. /**
  6696. * Returns a timestamp's (signed) seconds since 1970-01-01T00:00:00Z.
  6697. *
  6698. * @note This requires @ref MPACK_EXTENSIONS.
  6699. *
  6700. * @throws mpack_error_type if the underlying value is not a timestamp.
  6701. */
  6702. int64_t mpack_node_timestamp_seconds(mpack_node_t node);
  6703. /**
  6704. * Returns a timestamp's additional nanoseconds.
  6705. *
  6706. * @note This requires @ref MPACK_EXTENSIONS.
  6707. *
  6708. * @return A nanosecond count between 0 and 999,999,999 inclusive.
  6709. * @throws mpack_error_type if the underlying value is not a timestamp.
  6710. */
  6711. uint32_t mpack_node_timestamp_nanoseconds(mpack_node_t node);
  6712. #endif
  6713. /**
  6714. * @}
  6715. */
  6716. /**
  6717. * @name Node String and Data Functions
  6718. * @{
  6719. */
  6720. /**
  6721. * Checks that the given node contains a valid UTF-8 string.
  6722. *
  6723. * If the string is invalid, this flags an error, which would cause subsequent calls
  6724. * to mpack_node_str() to return NULL and mpack_node_strlen() to return zero. So you
  6725. * can check the node for error immediately after calling this, or you can call those
  6726. * functions to use the data anyway and check for errors later.
  6727. *
  6728. * @throws mpack_error_type If this node is not a string or does not contain valid UTF-8.
  6729. *
  6730. * @param node The string node to test
  6731. *
  6732. * @see mpack_node_str()
  6733. * @see mpack_node_strlen()
  6734. */
  6735. void mpack_node_check_utf8(mpack_node_t node);
  6736. /**
  6737. * Checks that the given node contains a valid UTF-8 string with no NUL bytes.
  6738. *
  6739. * This does not check that the string has a null-terminator! It only checks whether
  6740. * the string could safely be represented as a C-string by appending a null-terminator.
  6741. * (If the string does already contain a null-terminator, this will flag an error.)
  6742. *
  6743. * This is performed automatically by other UTF-8 cstr helper functions. Only
  6744. * call this if you will do something else with the data directly, but you still
  6745. * want to ensure it will be valid as a UTF-8 C-string.
  6746. *
  6747. * @throws mpack_error_type If this node is not a string, does not contain valid UTF-8,
  6748. * or contains a NUL byte.
  6749. *
  6750. * @param node The string node to test
  6751. *
  6752. * @see mpack_node_str()
  6753. * @see mpack_node_strlen()
  6754. * @see mpack_node_copy_utf8_cstr()
  6755. * @see mpack_node_utf8_cstr_alloc()
  6756. */
  6757. void mpack_node_check_utf8_cstr(mpack_node_t node);
  6758. #if MPACK_EXTENSIONS
  6759. /**
  6760. * Returns the extension type of the given ext node.
  6761. *
  6762. * This returns zero if the tree is in an error state.
  6763. *
  6764. * @note This requires @ref MPACK_EXTENSIONS.
  6765. */
  6766. int8_t mpack_node_exttype(mpack_node_t node);
  6767. #endif
  6768. /**
  6769. * Returns the number of bytes in the given bin node.
  6770. *
  6771. * This returns zero if the tree is in an error state.
  6772. *
  6773. * If this node is not a bin, @ref mpack_error_type is raised and zero is returned.
  6774. */
  6775. size_t mpack_node_bin_size(mpack_node_t node);
  6776. /**
  6777. * Returns the length of the given str, bin or ext node.
  6778. *
  6779. * This returns zero if the tree is in an error state.
  6780. *
  6781. * If this node is not a str, bin or ext, @ref mpack_error_type is raised and zero
  6782. * is returned.
  6783. */
  6784. uint32_t mpack_node_data_len(mpack_node_t node);
  6785. /**
  6786. * Returns the length in bytes of the given string node. This does not
  6787. * include any null-terminator.
  6788. *
  6789. * This returns zero if the tree is in an error state.
  6790. *
  6791. * If this node is not a str, @ref mpack_error_type is raised and zero is returned.
  6792. */
  6793. size_t mpack_node_strlen(mpack_node_t node);
  6794. /**
  6795. * Returns a pointer to the data contained by this node, ensuring the node is a
  6796. * string.
  6797. *
  6798. * @warning Strings are not null-terminated! Use one of the cstr functions
  6799. * to get a null-terminated string.
  6800. *
  6801. * The pointer is valid as long as the data backing the tree is valid.
  6802. *
  6803. * If this node is not a string, @ref mpack_error_type is raised and @c NULL is returned.
  6804. *
  6805. * @see mpack_node_copy_cstr()
  6806. * @see mpack_node_cstr_alloc()
  6807. * @see mpack_node_utf8_cstr_alloc()
  6808. */
  6809. const char* mpack_node_str(mpack_node_t node);
  6810. /**
  6811. * Returns a pointer to the data contained by this node.
  6812. *
  6813. * @note Strings are not null-terminated! Use one of the cstr functions
  6814. * to get a null-terminated string.
  6815. *
  6816. * The pointer is valid as long as the data backing the tree is valid.
  6817. *
  6818. * If this node is not of a str, bin or ext, @ref mpack_error_type is raised, and
  6819. * @c NULL is returned.
  6820. *
  6821. * @see mpack_node_copy_cstr()
  6822. * @see mpack_node_cstr_alloc()
  6823. * @see mpack_node_utf8_cstr_alloc()
  6824. */
  6825. const char* mpack_node_data(mpack_node_t node);
  6826. /**
  6827. * Returns a pointer to the data contained by this bin node.
  6828. *
  6829. * The pointer is valid as long as the data backing the tree is valid.
  6830. *
  6831. * If this node is not a bin, @ref mpack_error_type is raised and @c NULL is
  6832. * returned.
  6833. */
  6834. const char* mpack_node_bin_data(mpack_node_t node);
  6835. /**
  6836. * Copies the bytes contained by this node into the given buffer, returning the
  6837. * number of bytes in the node.
  6838. *
  6839. * @throws mpack_error_type If this node is not a str, bin or ext type
  6840. * @throws mpack_error_too_big If the string does not fit in the given buffer
  6841. *
  6842. * @param node The string node from which to copy data
  6843. * @param buffer A buffer in which to copy the node's bytes
  6844. * @param bufsize The size of the given buffer
  6845. *
  6846. * @return The number of bytes in the node, or zero if an error occurs.
  6847. */
  6848. size_t mpack_node_copy_data(mpack_node_t node, char* buffer, size_t bufsize);
  6849. /**
  6850. * Checks that the given node contains a valid UTF-8 string and copies the
  6851. * string into the given buffer, returning the number of bytes in the string.
  6852. *
  6853. * @throws mpack_error_type If this node is not a string
  6854. * @throws mpack_error_too_big If the string does not fit in the given buffer
  6855. *
  6856. * @param node The string node from which to copy data
  6857. * @param buffer A buffer in which to copy the node's bytes
  6858. * @param bufsize The size of the given buffer
  6859. *
  6860. * @return The number of bytes in the node, or zero if an error occurs.
  6861. */
  6862. size_t mpack_node_copy_utf8(mpack_node_t node, char* buffer, size_t bufsize);
  6863. /**
  6864. * Checks that the given node contains a string with no NUL bytes, copies the string
  6865. * into the given buffer, and adds a null terminator.
  6866. *
  6867. * If this node is not of a string type, @ref mpack_error_type is raised. If the string
  6868. * does not fit, @ref mpack_error_data is raised.
  6869. *
  6870. * If any error occurs, the buffer will contain an empty null-terminated string.
  6871. *
  6872. * @param node The string node from which to copy data
  6873. * @param buffer A buffer in which to copy the node's string
  6874. * @param size The size of the given buffer
  6875. */
  6876. void mpack_node_copy_cstr(mpack_node_t node, char* buffer, size_t size);
  6877. /**
  6878. * Checks that the given node contains a valid UTF-8 string with no NUL bytes,
  6879. * copies the string into the given buffer, and adds a null terminator.
  6880. *
  6881. * If this node is not of a string type, @ref mpack_error_type is raised. If the string
  6882. * does not fit, @ref mpack_error_data is raised.
  6883. *
  6884. * If any error occurs, the buffer will contain an empty null-terminated string.
  6885. *
  6886. * @param node The string node from which to copy data
  6887. * @param buffer A buffer in which to copy the node's string
  6888. * @param size The size of the given buffer
  6889. */
  6890. void mpack_node_copy_utf8_cstr(mpack_node_t node, char* buffer, size_t size);
  6891. #ifdef MPACK_MALLOC
  6892. /**
  6893. * Allocates a new chunk of data using MPACK_MALLOC() with the bytes
  6894. * contained by this node.
  6895. *
  6896. * The allocated data must be freed with MPACK_FREE() (or simply free()
  6897. * if MPack's allocator hasn't been customized.)
  6898. *
  6899. * @throws mpack_error_type If this node is not a str, bin or ext type
  6900. * @throws mpack_error_too_big If the size of the data is larger than the
  6901. * given maximum size
  6902. * @throws mpack_error_memory If an allocation failure occurs
  6903. *
  6904. * @param node The node from which to allocate and copy data
  6905. * @param maxsize The maximum size to allocate
  6906. *
  6907. * @return The allocated data, or NULL if any error occurs.
  6908. */
  6909. char* mpack_node_data_alloc(mpack_node_t node, size_t maxsize);
  6910. /**
  6911. * Allocates a new null-terminated string using MPACK_MALLOC() with the string
  6912. * contained by this node.
  6913. *
  6914. * The allocated string must be freed with MPACK_FREE() (or simply free()
  6915. * if MPack's allocator hasn't been customized.)
  6916. *
  6917. * @throws mpack_error_type If this node is not a string or contains NUL bytes
  6918. * @throws mpack_error_too_big If the size of the string plus null-terminator
  6919. * is larger than the given maximum size
  6920. * @throws mpack_error_memory If an allocation failure occurs
  6921. *
  6922. * @param node The node from which to allocate and copy string data
  6923. * @param maxsize The maximum size to allocate, including the null-terminator
  6924. *
  6925. * @return The allocated string, or NULL if any error occurs.
  6926. */
  6927. char* mpack_node_cstr_alloc(mpack_node_t node, size_t maxsize);
  6928. /**
  6929. * Allocates a new null-terminated string using MPACK_MALLOC() with the UTF-8
  6930. * string contained by this node.
  6931. *
  6932. * The allocated string must be freed with MPACK_FREE() (or simply free()
  6933. * if MPack's allocator hasn't been customized.)
  6934. *
  6935. * @throws mpack_error_type If this node is not a string, is not valid UTF-8,
  6936. * or contains NUL bytes
  6937. * @throws mpack_error_too_big If the size of the string plus null-terminator
  6938. * is larger than the given maximum size
  6939. * @throws mpack_error_memory If an allocation failure occurs
  6940. *
  6941. * @param node The node from which to allocate and copy string data
  6942. * @param maxsize The maximum size to allocate, including the null-terminator
  6943. *
  6944. * @return The allocated string, or NULL if any error occurs.
  6945. */
  6946. char* mpack_node_utf8_cstr_alloc(mpack_node_t node, size_t maxsize);
  6947. #endif
  6948. /**
  6949. * Searches the given string array for a string matching the given
  6950. * node and returns its index.
  6951. *
  6952. * If the node does not match any of the given strings,
  6953. * @ref mpack_error_type is flagged. Use mpack_node_enum_optional()
  6954. * if you want to allow values other than the given strings.
  6955. *
  6956. * If any error occurs or if the tree is in an error state, @a count
  6957. * is returned.
  6958. *
  6959. * This can be used to quickly parse a string into an enum when the
  6960. * enum values range from 0 to @a count-1. If the last value in the
  6961. * enum is a special "count" value, it can be passed as the count,
  6962. * and the return value can be cast directly to the enum type.
  6963. *
  6964. * @code{.c}
  6965. * typedef enum { APPLE , BANANA , ORANGE , COUNT} fruit_t;
  6966. * const char* fruits[] = {"apple", "banana", "orange"};
  6967. *
  6968. * fruit_t fruit = (fruit_t)mpack_node_enum(node, fruits, COUNT);
  6969. * @endcode
  6970. *
  6971. * @param node The node
  6972. * @param strings An array of expected strings of length count
  6973. * @param count The number of strings
  6974. * @return The index of the matched string, or @a count in case of error
  6975. */
  6976. size_t mpack_node_enum(mpack_node_t node, const char* strings[], size_t count);
  6977. /**
  6978. * Searches the given string array for a string matching the given node,
  6979. * returning its index or @a count if no strings match.
  6980. *
  6981. * If the value is not a string, or it does not match any of the
  6982. * given strings, @a count is returned and no error is flagged.
  6983. *
  6984. * If any error occurs or if the tree is in an error state, @a count
  6985. * is returned.
  6986. *
  6987. * This can be used to quickly parse a string into an enum when the
  6988. * enum values range from 0 to @a count-1. If the last value in the
  6989. * enum is a special "count" value, it can be passed as the count,
  6990. * and the return value can be cast directly to the enum type.
  6991. *
  6992. * @code{.c}
  6993. * typedef enum { APPLE , BANANA , ORANGE , COUNT} fruit_t;
  6994. * const char* fruits[] = {"apple", "banana", "orange"};
  6995. *
  6996. * fruit_t fruit = (fruit_t)mpack_node_enum_optional(node, fruits, COUNT);
  6997. * @endcode
  6998. *
  6999. * @param node The node
  7000. * @param strings An array of expected strings of length count
  7001. * @param count The number of strings
  7002. * @return The index of the matched string, or @a count in case of error
  7003. */
  7004. size_t mpack_node_enum_optional(mpack_node_t node, const char* strings[], size_t count);
  7005. /**
  7006. * @}
  7007. */
  7008. /**
  7009. * @name Compound Node Functions
  7010. * @{
  7011. */
  7012. /**
  7013. * Returns the length of the given array node. Raises mpack_error_type
  7014. * and returns 0 if the given node is not an array.
  7015. */
  7016. size_t mpack_node_array_length(mpack_node_t node);
  7017. /**
  7018. * Returns the node in the given array at the given index. If the node
  7019. * is not an array, @ref mpack_error_type is raised and a nil node is returned.
  7020. * If the given index is out of bounds, @ref mpack_error_data is raised and
  7021. * a nil node is returned.
  7022. */
  7023. mpack_node_t mpack_node_array_at(mpack_node_t node, size_t index);
  7024. /**
  7025. * Returns the number of key/value pairs in the given map node. Raises
  7026. * mpack_error_type and returns 0 if the given node is not a map.
  7027. */
  7028. size_t mpack_node_map_count(mpack_node_t node);
  7029. /**
  7030. * Returns the key node in the given map at the given index.
  7031. *
  7032. * A nil node is returned in case of error.
  7033. *
  7034. * @throws mpack_error_type if the node is not a map
  7035. * @throws mpack_error_data if the given index is out of bounds
  7036. */
  7037. mpack_node_t mpack_node_map_key_at(mpack_node_t node, size_t index);
  7038. /**
  7039. * Returns the value node in the given map at the given index.
  7040. *
  7041. * A nil node is returned in case of error.
  7042. *
  7043. * @throws mpack_error_type if the node is not a map
  7044. * @throws mpack_error_data if the given index is out of bounds
  7045. */
  7046. mpack_node_t mpack_node_map_value_at(mpack_node_t node, size_t index);
  7047. /**
  7048. * Returns the value node in the given map for the given integer key.
  7049. *
  7050. * The key must exist within the map. Use mpack_node_map_int_optional() to
  7051. * check for optional keys.
  7052. *
  7053. * The key must be unique. An error is flagged if the node has multiple
  7054. * entries with the given key.
  7055. *
  7056. * @throws mpack_error_type If the node is not a map
  7057. * @throws mpack_error_data If the node does not contain exactly one entry with the given key
  7058. *
  7059. * @return The value node for the given key, or a nil node in case of error
  7060. */
  7061. mpack_node_t mpack_node_map_int(mpack_node_t node, int64_t num);
  7062. /**
  7063. * Returns the value node in the given map for the given integer key, or a
  7064. * missing node if the map does not contain the given key.
  7065. *
  7066. * The key must be unique. An error is flagged if the node has multiple
  7067. * entries with the given key.
  7068. *
  7069. * @throws mpack_error_type If the node is not a map
  7070. * @throws mpack_error_data If the node contains more than one entry with the given key
  7071. *
  7072. * @return The value node for the given key, or a missing node if the key does
  7073. * not exist, or a nil node in case of error
  7074. *
  7075. * @see mpack_node_is_missing()
  7076. */
  7077. mpack_node_t mpack_node_map_int_optional(mpack_node_t node, int64_t num);
  7078. /**
  7079. * Returns the value node in the given map for the given unsigned integer key.
  7080. *
  7081. * The key must exist within the map. Use mpack_node_map_uint_optional() to
  7082. * check for optional keys.
  7083. *
  7084. * The key must be unique. An error is flagged if the node has multiple
  7085. * entries with the given key.
  7086. *
  7087. * @throws mpack_error_type If the node is not a map
  7088. * @throws mpack_error_data If the node does not contain exactly one entry with the given key
  7089. *
  7090. * @return The value node for the given key, or a nil node in case of error
  7091. */
  7092. mpack_node_t mpack_node_map_uint(mpack_node_t node, uint64_t num);
  7093. /**
  7094. * Returns the value node in the given map for the given unsigned integer
  7095. * key, or a missing node if the map does not contain the given key.
  7096. *
  7097. * The key must be unique. An error is flagged if the node has multiple
  7098. * entries with the given key.
  7099. *
  7100. * @throws mpack_error_type If the node is not a map
  7101. * @throws mpack_error_data If the node contains more than one entry with the given key
  7102. *
  7103. * @return The value node for the given key, or a missing node if the key does
  7104. * not exist, or a nil node in case of error
  7105. *
  7106. * @see mpack_node_is_missing()
  7107. */
  7108. mpack_node_t mpack_node_map_uint_optional(mpack_node_t node, uint64_t num);
  7109. /**
  7110. * Returns the value node in the given map for the given string key.
  7111. *
  7112. * The key must exist within the map. Use mpack_node_map_str_optional() to
  7113. * check for optional keys.
  7114. *
  7115. * The key must be unique. An error is flagged if the node has multiple
  7116. * entries with the given key.
  7117. *
  7118. * @throws mpack_error_type If the node is not a map
  7119. * @throws mpack_error_data If the node does not contain exactly one entry with the given key
  7120. *
  7121. * @return The value node for the given key, or a nil node in case of error
  7122. */
  7123. mpack_node_t mpack_node_map_str(mpack_node_t node, const char* str, size_t length);
  7124. /**
  7125. * Returns the value node in the given map for the given string key, or a missing
  7126. * node if the map does not contain the given key.
  7127. *
  7128. * The key must be unique. An error is flagged if the node has multiple
  7129. * entries with the given key.
  7130. *
  7131. * @throws mpack_error_type If the node is not a map
  7132. * @throws mpack_error_data If the node contains more than one entry with the given key
  7133. *
  7134. * @return The value node for the given key, or a missing node if the key does
  7135. * not exist, or a nil node in case of error
  7136. *
  7137. * @see mpack_node_is_missing()
  7138. */
  7139. mpack_node_t mpack_node_map_str_optional(mpack_node_t node, const char* str, size_t length);
  7140. /**
  7141. * Returns the value node in the given map for the given null-terminated
  7142. * string key.
  7143. *
  7144. * The key must exist within the map. Use mpack_node_map_cstr_optional() to
  7145. * check for optional keys.
  7146. *
  7147. * The key must be unique. An error is flagged if the node has multiple
  7148. * entries with the given key.
  7149. *
  7150. * @throws mpack_error_type If the node is not a map
  7151. * @throws mpack_error_data If the node does not contain exactly one entry with the given key
  7152. *
  7153. * @return The value node for the given key, or a nil node in case of error
  7154. */
  7155. mpack_node_t mpack_node_map_cstr(mpack_node_t node, const char* cstr);
  7156. /**
  7157. * Returns the value node in the given map for the given null-terminated
  7158. * string key, or a missing node if the map does not contain the given key.
  7159. *
  7160. * The key must be unique. An error is flagged if the node has multiple
  7161. * entries with the given key.
  7162. *
  7163. * @throws mpack_error_type If the node is not a map
  7164. * @throws mpack_error_data If the node contains more than one entry with the given key
  7165. *
  7166. * @return The value node for the given key, or a missing node if the key does
  7167. * not exist, or a nil node in case of error
  7168. *
  7169. * @see mpack_node_is_missing()
  7170. */
  7171. mpack_node_t mpack_node_map_cstr_optional(mpack_node_t node, const char* cstr);
  7172. /**
  7173. * Returns true if the given node map contains exactly one entry with the
  7174. * given integer key.
  7175. *
  7176. * The key must be unique. An error is flagged if the node has multiple
  7177. * entries with the given key.
  7178. *
  7179. * @throws mpack_error_type If the node is not a map
  7180. * @throws mpack_error_data If the node contains more than one entry with the given key
  7181. */
  7182. bool mpack_node_map_contains_int(mpack_node_t node, int64_t num);
  7183. /**
  7184. * Returns true if the given node map contains exactly one entry with the
  7185. * given unsigned integer key.
  7186. *
  7187. * The key must be unique. An error is flagged if the node has multiple
  7188. * entries with the given key.
  7189. *
  7190. * @throws mpack_error_type If the node is not a map
  7191. * @throws mpack_error_data If the node contains more than one entry with the given key
  7192. */
  7193. bool mpack_node_map_contains_uint(mpack_node_t node, uint64_t num);
  7194. /**
  7195. * Returns true if the given node map contains exactly one entry with the
  7196. * given string key.
  7197. *
  7198. * The key must be unique. An error is flagged if the node has multiple
  7199. * entries with the given key.
  7200. *
  7201. * @throws mpack_error_type If the node is not a map
  7202. * @throws mpack_error_data If the node contains more than one entry with the given key
  7203. */
  7204. bool mpack_node_map_contains_str(mpack_node_t node, const char* str, size_t length);
  7205. /**
  7206. * Returns true if the given node map contains exactly one entry with the
  7207. * given null-terminated string key.
  7208. *
  7209. * The key must be unique. An error is flagged if the node has multiple
  7210. * entries with the given key.
  7211. *
  7212. * @throws mpack_error_type If the node is not a map
  7213. * @throws mpack_error_data If the node contains more than one entry with the given key
  7214. */
  7215. bool mpack_node_map_contains_cstr(mpack_node_t node, const char* cstr);
  7216. /**
  7217. * @}
  7218. */
  7219. /**
  7220. * @}
  7221. */
  7222. #endif
  7223. MPACK_EXTERN_C_END
  7224. MPACK_SILENCE_WARNINGS_END
  7225. #endif
  7226. #endif