pugixml.cpp 303 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749107501075110752107531075410755107561075710758107591076010761107621076310764107651076610767107681076910770107711077210773107741077510776107771077810779107801078110782107831078410785107861078710788107891079010791107921079310794107951079610797107981079910800108011080210803108041080510806108071080810809108101081110812108131081410815108161081710818108191082010821108221082310824108251082610827108281082910830108311083210833108341083510836108371083810839108401084110842108431084410845108461084710848108491085010851108521085310854108551085610857108581085910860108611086210863108641086510866108671086810869108701087110872108731087410875108761087710878108791088010881108821088310884108851088610887108881088910890108911089210893108941089510896108971089810899109001090110902109031090410905109061090710908109091091010911109121091310914109151091610917109181091910920109211092210923109241092510926109271092810929109301093110932109331093410935109361093710938109391094010941109421094310944109451094610947109481094910950109511095210953109541095510956109571095810959109601096110962109631096410965109661096710968109691097010971109721097310974109751097610977109781097910980109811098210983109841098510986109871098810989109901099110992109931099410995109961099710998109991100011001110021100311004110051100611007110081100911010110111101211013110141101511016110171101811019110201102111022110231102411025110261102711028110291103011031110321103311034110351103611037110381103911040110411104211043110441104511046110471104811049110501105111052110531105411055110561105711058110591106011061110621106311064110651106611067110681106911070110711107211073110741107511076110771107811079110801108111082110831108411085110861108711088110891109011091110921109311094110951109611097110981109911100111011110211103111041110511106111071110811109111101111111112111131111411115111161111711118111191112011121111221112311124111251112611127111281112911130111311113211133111341113511136111371113811139111401114111142111431114411145111461114711148111491115011151111521115311154111551115611157111581115911160111611116211163111641116511166111671116811169111701117111172111731117411175111761117711178111791118011181111821118311184111851118611187111881118911190111911119211193111941119511196111971119811199112001120111202112031120411205112061120711208112091121011211112121121311214112151121611217112181121911220112211122211223112241122511226112271122811229112301123111232112331123411235112361123711238112391124011241112421124311244112451124611247112481124911250112511125211253112541125511256112571125811259112601126111262112631126411265112661126711268112691127011271112721127311274112751127611277112781127911280112811128211283112841128511286112871128811289112901129111292112931129411295112961129711298112991130011301113021130311304113051130611307113081130911310113111131211313113141131511316113171131811319113201132111322113231132411325113261132711328113291133011331113321133311334113351133611337113381133911340113411134211343113441134511346113471134811349113501135111352113531135411355113561135711358113591136011361113621136311364113651136611367113681136911370113711137211373113741137511376113771137811379113801138111382113831138411385113861138711388113891139011391113921139311394113951139611397113981139911400114011140211403114041140511406114071140811409114101141111412114131141411415114161141711418114191142011421114221142311424114251142611427114281142911430114311143211433114341143511436114371143811439114401144111442114431144411445114461144711448114491145011451114521145311454114551145611457114581145911460114611146211463114641146511466114671146811469114701147111472114731147411475114761147711478114791148011481114821148311484114851148611487114881148911490
  1. /**
  2. * pugixml parser - version 1.5
  3. * --------------------------------------------------------
  4. * Copyright (C) 2006-2014, by Arseny Kapoulkine ([email protected])
  5. * Report bugs and download new versions at http://pugixml.org/
  6. *
  7. * This library is distributed under the MIT License. See notice at the end
  8. * of this file.
  9. *
  10. * This work is based on the pugxml parser, which is:
  11. * Copyright (C) 2003, by Kristen Wegner ([email protected])
  12. */
  13. #ifndef SOURCE_PUGIXML_CPP
  14. #define SOURCE_PUGIXML_CPP
  15. #include "pugixml.hpp"
  16. #include <stdlib.h>
  17. #include <stdio.h>
  18. #include <string.h>
  19. #include <assert.h>
  20. #ifdef PUGIXML_WCHAR_MODE
  21. # include <wchar.h>
  22. #endif
  23. #ifndef PUGIXML_NO_XPATH
  24. # include <math.h>
  25. # include <float.h>
  26. # ifdef PUGIXML_NO_EXCEPTIONS
  27. # include <setjmp.h>
  28. # endif
  29. #endif
  30. #ifndef PUGIXML_NO_STL
  31. # include <istream>
  32. # include <ostream>
  33. # include <string>
  34. #endif
  35. // For placement new
  36. #include <new>
  37. #ifdef _MSC_VER
  38. # pragma warning(push)
  39. # pragma warning(disable: 4127) // conditional expression is constant
  40. # pragma warning(disable: 4324) // structure was padded due to __declspec(align())
  41. # pragma warning(disable: 4611) // interaction between '_setjmp' and C++ object destruction is non-portable
  42. # pragma warning(disable: 4702) // unreachable code
  43. # pragma warning(disable: 4996) // this function or variable may be unsafe
  44. # pragma warning(disable: 4793) // function compiled as native: presence of '_setjmp' makes a function unmanaged
  45. #endif
  46. #ifdef __INTEL_COMPILER
  47. # pragma warning(disable: 177) // function was declared but never referenced
  48. # pragma warning(disable: 279) // controlling expression is constant
  49. # pragma warning(disable: 1478 1786) // function was declared "deprecated"
  50. # pragma warning(disable: 1684) // conversion from pointer to same-sized integral type
  51. #endif
  52. #if defined(__BORLANDC__) && defined(PUGIXML_HEADER_ONLY)
  53. # pragma warn -8080 // symbol is declared but never used; disabling this inside push/pop bracket does not make the warning go away
  54. #endif
  55. #ifdef __BORLANDC__
  56. # pragma option push
  57. # pragma warn -8008 // condition is always false
  58. # pragma warn -8066 // unreachable code
  59. #endif
  60. #ifdef __SNC__
  61. // Using diag_push/diag_pop does not disable the warnings inside templates due to a compiler bug
  62. # pragma diag_suppress=178 // function was declared but never referenced
  63. # pragma diag_suppress=237 // controlling expression is constant
  64. #endif
  65. // Inlining controls
  66. #if defined(_MSC_VER) && _MSC_VER >= 1300
  67. # define PUGI__NO_INLINE __declspec(noinline)
  68. #elif defined(__GNUC__)
  69. # define PUGI__NO_INLINE __attribute__((noinline))
  70. #else
  71. # define PUGI__NO_INLINE
  72. #endif
  73. // Branch weight controls
  74. #if defined(__GNUC__)
  75. # define PUGI__UNLIKELY(cond) __builtin_expect(cond, 0)
  76. #else
  77. # define PUGI__UNLIKELY(cond) (cond)
  78. #endif
  79. // Simple static assertion
  80. #define PUGI__STATIC_ASSERT(cond) { static const char condition_failed[(cond) ? 1 : -1] = {0}; (void)condition_failed[0]; }
  81. // Digital Mars C++ bug workaround for passing char loaded from memory via stack
  82. #ifdef __DMC__
  83. # define PUGI__DMC_VOLATILE volatile
  84. #else
  85. # define PUGI__DMC_VOLATILE
  86. #endif
  87. // Borland C++ bug workaround for not defining ::memcpy depending on header include order (can't always use std::memcpy because some compilers don't have it at all)
  88. #if defined(__BORLANDC__) && !defined(__MEM_H_USING_LIST)
  89. using std::memcpy;
  90. using std::memmove;
  91. #endif
  92. // In some environments MSVC is a compiler but the CRT lacks certain MSVC-specific features
  93. #if defined(_MSC_VER) && !defined(__S3E__)
  94. # define PUGI__MSVC_CRT_VERSION _MSC_VER
  95. #endif
  96. #ifdef PUGIXML_HEADER_ONLY
  97. # define PUGI__NS_BEGIN namespace pugi { namespace impl {
  98. # define PUGI__NS_END } }
  99. # define PUGI__FN inline
  100. # define PUGI__FN_NO_INLINE inline
  101. #else
  102. # if defined(_MSC_VER) && _MSC_VER < 1300 // MSVC6 seems to have an amusing bug with anonymous namespaces inside namespaces
  103. # define PUGI__NS_BEGIN namespace pugi { namespace impl {
  104. # define PUGI__NS_END } }
  105. # else
  106. # define PUGI__NS_BEGIN namespace pugi { namespace impl { namespace {
  107. # define PUGI__NS_END } } }
  108. # endif
  109. # define PUGI__FN
  110. # define PUGI__FN_NO_INLINE PUGI__NO_INLINE
  111. #endif
  112. // uintptr_t
  113. #if !defined(_MSC_VER) || _MSC_VER >= 1600
  114. # include <stdint.h>
  115. #else
  116. # ifndef _UINTPTR_T_DEFINED
  117. // No native uintptr_t in MSVC6 and in some WinCE versions
  118. typedef size_t uintptr_t;
  119. #define _UINTPTR_T_DEFINED
  120. # endif
  121. PUGI__NS_BEGIN
  122. typedef unsigned __int8 uint8_t;
  123. typedef unsigned __int16 uint16_t;
  124. typedef unsigned __int32 uint32_t;
  125. PUGI__NS_END
  126. #endif
  127. // Memory allocation
  128. PUGI__NS_BEGIN
  129. PUGI__FN void* default_allocate(size_t size)
  130. {
  131. return malloc(size);
  132. }
  133. PUGI__FN void default_deallocate(void* ptr)
  134. {
  135. free(ptr);
  136. }
  137. template <typename T>
  138. struct xml_memory_management_function_storage
  139. {
  140. static allocation_function allocate;
  141. static deallocation_function deallocate;
  142. };
  143. // Global allocation functions are stored in class statics so that in header mode linker deduplicates them
  144. // Without a template<> we'll get multiple definitions of the same static
  145. template <typename T> allocation_function xml_memory_management_function_storage<T>::allocate = default_allocate;
  146. template <typename T> deallocation_function xml_memory_management_function_storage<T>::deallocate = default_deallocate;
  147. typedef xml_memory_management_function_storage<int> xml_memory;
  148. PUGI__NS_END
  149. // String utilities
  150. PUGI__NS_BEGIN
  151. // Get string length
  152. PUGI__FN size_t strlength(const char_t* s)
  153. {
  154. assert(s);
  155. #ifdef PUGIXML_WCHAR_MODE
  156. return wcslen(s);
  157. #else
  158. return strlen(s);
  159. #endif
  160. }
  161. // Compare two strings
  162. PUGI__FN bool strequal(const char_t* src, const char_t* dst)
  163. {
  164. assert(src && dst);
  165. #ifdef PUGIXML_WCHAR_MODE
  166. return wcscmp(src, dst) == 0;
  167. #else
  168. return strcmp(src, dst) == 0;
  169. #endif
  170. }
  171. // Compare lhs with [rhs_begin, rhs_end)
  172. PUGI__FN bool strequalrange(const char_t* lhs, const char_t* rhs, size_t count)
  173. {
  174. for (size_t i = 0; i < count; ++i)
  175. if (lhs[i] != rhs[i])
  176. return false;
  177. return lhs[count] == 0;
  178. }
  179. // Get length of wide string, even if CRT lacks wide character support
  180. PUGI__FN size_t strlength_wide(const wchar_t* s)
  181. {
  182. assert(s);
  183. #ifdef PUGIXML_WCHAR_MODE
  184. return wcslen(s);
  185. #else
  186. const wchar_t* end = s;
  187. while (*end) end++;
  188. return static_cast<size_t>(end - s);
  189. #endif
  190. }
  191. #ifdef PUGIXML_WCHAR_MODE
  192. // Convert string to wide string, assuming all symbols are ASCII
  193. PUGI__FN void widen_ascii(wchar_t* dest, const char* source)
  194. {
  195. for (const char* i = source; *i; ++i) *dest++ = *i;
  196. *dest = 0;
  197. }
  198. #endif
  199. PUGI__NS_END
  200. #if !defined(PUGIXML_NO_STL) || !defined(PUGIXML_NO_XPATH)
  201. // auto_ptr-like buffer holder for exception recovery
  202. PUGI__NS_BEGIN
  203. struct buffer_holder
  204. {
  205. void* data;
  206. void (*deleter)(void*);
  207. buffer_holder(void* data_, void (*deleter_)(void*)): data(data_), deleter(deleter_)
  208. {
  209. }
  210. ~buffer_holder()
  211. {
  212. if (data) deleter(data);
  213. }
  214. void* release()
  215. {
  216. void* result = data;
  217. data = 0;
  218. return result;
  219. }
  220. };
  221. PUGI__NS_END
  222. #endif
  223. PUGI__NS_BEGIN
  224. static const size_t xml_memory_page_size =
  225. #ifdef PUGIXML_MEMORY_PAGE_SIZE
  226. PUGIXML_MEMORY_PAGE_SIZE
  227. #else
  228. 32768
  229. #endif
  230. ;
  231. static const uintptr_t xml_memory_page_alignment = 64;
  232. static const uintptr_t xml_memory_page_pointer_mask = ~(xml_memory_page_alignment - 1);
  233. static const uintptr_t xml_memory_page_contents_shared_mask = 32;
  234. static const uintptr_t xml_memory_page_name_allocated_mask = 16;
  235. static const uintptr_t xml_memory_page_value_allocated_mask = 8;
  236. static const uintptr_t xml_memory_page_type_mask = 7;
  237. static const uintptr_t xml_memory_page_name_allocated_or_shared_mask = xml_memory_page_name_allocated_mask | xml_memory_page_contents_shared_mask;
  238. static const uintptr_t xml_memory_page_value_allocated_or_shared_mask = xml_memory_page_value_allocated_mask | xml_memory_page_contents_shared_mask;
  239. #define PUGI__NODETYPE(n) static_cast<xml_node_type>(((n)->header & impl::xml_memory_page_type_mask) + 1)
  240. struct xml_allocator;
  241. struct xml_memory_page
  242. {
  243. static xml_memory_page* construct(void* memory)
  244. {
  245. xml_memory_page* result = static_cast<xml_memory_page*>(memory);
  246. result->allocator = 0;
  247. result->prev = 0;
  248. result->next = 0;
  249. result->busy_size = 0;
  250. result->freed_size = 0;
  251. return result;
  252. }
  253. xml_allocator* allocator;
  254. xml_memory_page* prev;
  255. xml_memory_page* next;
  256. size_t busy_size;
  257. size_t freed_size;
  258. };
  259. struct xml_memory_string_header
  260. {
  261. uint16_t page_offset; // offset from page->data
  262. uint16_t full_size; // 0 if string occupies whole page
  263. };
  264. struct xml_allocator
  265. {
  266. xml_allocator(xml_memory_page* root): _root(root), _busy_size(root->busy_size)
  267. {
  268. }
  269. xml_memory_page* allocate_page(size_t data_size)
  270. {
  271. size_t size = sizeof(xml_memory_page) + data_size;
  272. // allocate block with some alignment, leaving memory for worst-case padding
  273. void* memory = xml_memory::allocate(size + xml_memory_page_alignment);
  274. if (!memory) return 0;
  275. // align to next page boundary (note: this guarantees at least 1 usable byte before the page)
  276. char* page_memory = reinterpret_cast<char*>((reinterpret_cast<uintptr_t>(memory) + xml_memory_page_alignment) & ~(xml_memory_page_alignment - 1));
  277. // prepare page structure
  278. xml_memory_page* page = xml_memory_page::construct(page_memory);
  279. assert(page);
  280. page->allocator = _root->allocator;
  281. // record the offset for freeing the memory block
  282. assert(page_memory > memory && page_memory - static_cast<char*>(memory) <= 127);
  283. page_memory[-1] = static_cast<char>(page_memory - static_cast<char*>(memory));
  284. return page;
  285. }
  286. static void deallocate_page(xml_memory_page* page)
  287. {
  288. char* page_memory = reinterpret_cast<char*>(page);
  289. xml_memory::deallocate(page_memory - page_memory[-1]);
  290. }
  291. void* allocate_memory_oob(size_t size, xml_memory_page*& out_page);
  292. void* allocate_memory(size_t size, xml_memory_page*& out_page)
  293. {
  294. if (_busy_size + size > xml_memory_page_size) return allocate_memory_oob(size, out_page);
  295. void* buf = reinterpret_cast<char*>(_root) + sizeof(xml_memory_page) + _busy_size;
  296. _busy_size += size;
  297. out_page = _root;
  298. return buf;
  299. }
  300. void deallocate_memory(void* ptr, size_t size, xml_memory_page* page)
  301. {
  302. if (page == _root) page->busy_size = _busy_size;
  303. assert(ptr >= reinterpret_cast<char*>(page) + sizeof(xml_memory_page) && ptr < reinterpret_cast<char*>(page) + sizeof(xml_memory_page) + page->busy_size);
  304. (void)!ptr;
  305. page->freed_size += size;
  306. assert(page->freed_size <= page->busy_size);
  307. if (page->freed_size == page->busy_size)
  308. {
  309. if (page->next == 0)
  310. {
  311. assert(_root == page);
  312. // top page freed, just reset sizes
  313. page->busy_size = page->freed_size = 0;
  314. _busy_size = 0;
  315. }
  316. else
  317. {
  318. assert(_root != page);
  319. assert(page->prev);
  320. // remove from the list
  321. page->prev->next = page->next;
  322. page->next->prev = page->prev;
  323. // deallocate
  324. deallocate_page(page);
  325. }
  326. }
  327. }
  328. char_t* allocate_string(size_t length)
  329. {
  330. PUGI__STATIC_ASSERT(xml_memory_page_size <= (1 << 16));
  331. // allocate memory for string and header block
  332. size_t size = sizeof(xml_memory_string_header) + length * sizeof(char_t);
  333. // round size up to pointer alignment boundary
  334. size_t full_size = (size + (sizeof(void*) - 1)) & ~(sizeof(void*) - 1);
  335. xml_memory_page* page;
  336. xml_memory_string_header* header = static_cast<xml_memory_string_header*>(allocate_memory(full_size, page));
  337. if (!header) return 0;
  338. // setup header
  339. ptrdiff_t page_offset = reinterpret_cast<char*>(header) - reinterpret_cast<char*>(page) - sizeof(xml_memory_page);
  340. assert(page_offset >= 0 && page_offset < (1 << 16));
  341. header->page_offset = static_cast<uint16_t>(page_offset);
  342. // full_size == 0 for large strings that occupy the whole page
  343. assert(full_size < (1 << 16) || (page->busy_size == full_size && page_offset == 0));
  344. header->full_size = static_cast<uint16_t>(full_size < (1 << 16) ? full_size : 0);
  345. // round-trip through void* to avoid 'cast increases required alignment of target type' warning
  346. // header is guaranteed a pointer-sized alignment, which should be enough for char_t
  347. return static_cast<char_t*>(static_cast<void*>(header + 1));
  348. }
  349. void deallocate_string(char_t* string)
  350. {
  351. // this function casts pointers through void* to avoid 'cast increases required alignment of target type' warnings
  352. // we're guaranteed the proper (pointer-sized) alignment on the input string if it was allocated via allocate_string
  353. // get header
  354. xml_memory_string_header* header = static_cast<xml_memory_string_header*>(static_cast<void*>(string)) - 1;
  355. assert(header);
  356. // deallocate
  357. size_t page_offset = sizeof(xml_memory_page) + header->page_offset;
  358. xml_memory_page* page = reinterpret_cast<xml_memory_page*>(static_cast<void*>(reinterpret_cast<char*>(header) - page_offset));
  359. // if full_size == 0 then this string occupies the whole page
  360. size_t full_size = header->full_size == 0 ? page->busy_size : header->full_size;
  361. deallocate_memory(header, full_size, page);
  362. }
  363. xml_memory_page* _root;
  364. size_t _busy_size;
  365. };
  366. PUGI__FN_NO_INLINE void* xml_allocator::allocate_memory_oob(size_t size, xml_memory_page*& out_page)
  367. {
  368. const size_t large_allocation_threshold = xml_memory_page_size / 4;
  369. xml_memory_page* page = allocate_page(size <= large_allocation_threshold ? xml_memory_page_size : size);
  370. out_page = page;
  371. if (!page) return 0;
  372. if (size <= large_allocation_threshold)
  373. {
  374. _root->busy_size = _busy_size;
  375. // insert page at the end of linked list
  376. page->prev = _root;
  377. _root->next = page;
  378. _root = page;
  379. _busy_size = size;
  380. }
  381. else
  382. {
  383. // insert page before the end of linked list, so that it is deleted as soon as possible
  384. // the last page is not deleted even if it's empty (see deallocate_memory)
  385. assert(_root->prev);
  386. page->prev = _root->prev;
  387. page->next = _root;
  388. _root->prev->next = page;
  389. _root->prev = page;
  390. }
  391. // allocate inside page
  392. page->busy_size = size;
  393. return reinterpret_cast<char*>(page) + sizeof(xml_memory_page);
  394. }
  395. PUGI__NS_END
  396. namespace pugi
  397. {
  398. /// A 'name=value' XML attribute structure.
  399. struct xml_attribute_struct
  400. {
  401. /// Default ctor
  402. xml_attribute_struct(impl::xml_memory_page* page): header(reinterpret_cast<uintptr_t>(page)), name(0), value(0), prev_attribute_c(0), next_attribute(0)
  403. {
  404. }
  405. uintptr_t header;
  406. char_t* name; ///< Pointer to attribute name.
  407. char_t* value; ///< Pointer to attribute value.
  408. xml_attribute_struct* prev_attribute_c; ///< Previous attribute (cyclic list)
  409. xml_attribute_struct* next_attribute; ///< Next attribute
  410. };
  411. /// An XML document tree node.
  412. struct xml_node_struct
  413. {
  414. /// Default ctor
  415. /// \param type - node type
  416. xml_node_struct(impl::xml_memory_page* page, xml_node_type type): header(reinterpret_cast<uintptr_t>(page) | (type - 1)), parent(0), name(0), value(0), first_child(0), prev_sibling_c(0), next_sibling(0), first_attribute(0)
  417. {
  418. }
  419. uintptr_t header;
  420. xml_node_struct* parent; ///< Pointer to parent
  421. char_t* name; ///< Pointer to element name.
  422. char_t* value; ///< Pointer to any associated string data.
  423. xml_node_struct* first_child; ///< First child
  424. xml_node_struct* prev_sibling_c; ///< Left brother (cyclic list)
  425. xml_node_struct* next_sibling; ///< Right brother
  426. xml_attribute_struct* first_attribute; ///< First attribute
  427. };
  428. }
  429. PUGI__NS_BEGIN
  430. struct xml_extra_buffer
  431. {
  432. char_t* buffer;
  433. xml_extra_buffer* next;
  434. };
  435. struct xml_document_struct: public xml_node_struct, public xml_allocator
  436. {
  437. xml_document_struct(xml_memory_page* page): xml_node_struct(page, node_document), xml_allocator(page), buffer(0), extra_buffers(0)
  438. {
  439. }
  440. const char_t* buffer;
  441. xml_extra_buffer* extra_buffers;
  442. };
  443. inline xml_allocator& get_allocator(const xml_node_struct* node)
  444. {
  445. assert(node);
  446. return *reinterpret_cast<xml_memory_page*>(node->header & xml_memory_page_pointer_mask)->allocator;
  447. }
  448. template <typename Object> inline xml_document_struct& get_document(const Object* object)
  449. {
  450. assert(object);
  451. return *static_cast<xml_document_struct*>(reinterpret_cast<xml_memory_page*>(object->header & xml_memory_page_pointer_mask)->allocator);
  452. }
  453. PUGI__NS_END
  454. // Low-level DOM operations
  455. PUGI__NS_BEGIN
  456. inline xml_attribute_struct* allocate_attribute(xml_allocator& alloc)
  457. {
  458. xml_memory_page* page;
  459. void* memory = alloc.allocate_memory(sizeof(xml_attribute_struct), page);
  460. return new (memory) xml_attribute_struct(page);
  461. }
  462. inline xml_node_struct* allocate_node(xml_allocator& alloc, xml_node_type type)
  463. {
  464. xml_memory_page* page;
  465. void* memory = alloc.allocate_memory(sizeof(xml_node_struct), page);
  466. return new (memory) xml_node_struct(page, type);
  467. }
  468. inline void destroy_attribute(xml_attribute_struct* a, xml_allocator& alloc)
  469. {
  470. uintptr_t header = a->header;
  471. if (header & impl::xml_memory_page_name_allocated_mask) alloc.deallocate_string(a->name);
  472. if (header & impl::xml_memory_page_value_allocated_mask) alloc.deallocate_string(a->value);
  473. alloc.deallocate_memory(a, sizeof(xml_attribute_struct), reinterpret_cast<xml_memory_page*>(header & xml_memory_page_pointer_mask));
  474. }
  475. inline void destroy_node(xml_node_struct* n, xml_allocator& alloc)
  476. {
  477. uintptr_t header = n->header;
  478. if (header & impl::xml_memory_page_name_allocated_mask) alloc.deallocate_string(n->name);
  479. if (header & impl::xml_memory_page_value_allocated_mask) alloc.deallocate_string(n->value);
  480. for (xml_attribute_struct* attr = n->first_attribute; attr; )
  481. {
  482. xml_attribute_struct* next = attr->next_attribute;
  483. destroy_attribute(attr, alloc);
  484. attr = next;
  485. }
  486. for (xml_node_struct* child = n->first_child; child; )
  487. {
  488. xml_node_struct* next = child->next_sibling;
  489. destroy_node(child, alloc);
  490. child = next;
  491. }
  492. alloc.deallocate_memory(n, sizeof(xml_node_struct), reinterpret_cast<xml_memory_page*>(header & xml_memory_page_pointer_mask));
  493. }
  494. inline void append_node(xml_node_struct* child, xml_node_struct* node)
  495. {
  496. child->parent = node;
  497. xml_node_struct* head = node->first_child;
  498. if (head)
  499. {
  500. xml_node_struct* tail = head->prev_sibling_c;
  501. tail->next_sibling = child;
  502. child->prev_sibling_c = tail;
  503. head->prev_sibling_c = child;
  504. }
  505. else
  506. {
  507. node->first_child = child;
  508. child->prev_sibling_c = child;
  509. }
  510. }
  511. inline void prepend_node(xml_node_struct* child, xml_node_struct* node)
  512. {
  513. child->parent = node;
  514. xml_node_struct* head = node->first_child;
  515. if (head)
  516. {
  517. child->prev_sibling_c = head->prev_sibling_c;
  518. head->prev_sibling_c = child;
  519. }
  520. else
  521. child->prev_sibling_c = child;
  522. child->next_sibling = head;
  523. node->first_child = child;
  524. }
  525. inline void insert_node_after(xml_node_struct* child, xml_node_struct* node)
  526. {
  527. xml_node_struct* parent = node->parent;
  528. child->parent = parent;
  529. if (node->next_sibling)
  530. node->next_sibling->prev_sibling_c = child;
  531. else
  532. parent->first_child->prev_sibling_c = child;
  533. child->next_sibling = node->next_sibling;
  534. child->prev_sibling_c = node;
  535. node->next_sibling = child;
  536. }
  537. inline void insert_node_before(xml_node_struct* child, xml_node_struct* node)
  538. {
  539. xml_node_struct* parent = node->parent;
  540. child->parent = parent;
  541. if (node->prev_sibling_c->next_sibling)
  542. node->prev_sibling_c->next_sibling = child;
  543. else
  544. parent->first_child = child;
  545. child->prev_sibling_c = node->prev_sibling_c;
  546. child->next_sibling = node;
  547. node->prev_sibling_c = child;
  548. }
  549. inline void remove_node(xml_node_struct* node)
  550. {
  551. xml_node_struct* parent = node->parent;
  552. if (node->next_sibling)
  553. node->next_sibling->prev_sibling_c = node->prev_sibling_c;
  554. else
  555. parent->first_child->prev_sibling_c = node->prev_sibling_c;
  556. if (node->prev_sibling_c->next_sibling)
  557. node->prev_sibling_c->next_sibling = node->next_sibling;
  558. else
  559. parent->first_child = node->next_sibling;
  560. node->parent = 0;
  561. node->prev_sibling_c = 0;
  562. node->next_sibling = 0;
  563. }
  564. inline void append_attribute(xml_attribute_struct* attr, xml_node_struct* node)
  565. {
  566. xml_attribute_struct* head = node->first_attribute;
  567. if (head)
  568. {
  569. xml_attribute_struct* tail = head->prev_attribute_c;
  570. tail->next_attribute = attr;
  571. attr->prev_attribute_c = tail;
  572. head->prev_attribute_c = attr;
  573. }
  574. else
  575. {
  576. node->first_attribute = attr;
  577. attr->prev_attribute_c = attr;
  578. }
  579. }
  580. inline void prepend_attribute(xml_attribute_struct* attr, xml_node_struct* node)
  581. {
  582. xml_attribute_struct* head = node->first_attribute;
  583. if (head)
  584. {
  585. attr->prev_attribute_c = head->prev_attribute_c;
  586. head->prev_attribute_c = attr;
  587. }
  588. else
  589. attr->prev_attribute_c = attr;
  590. attr->next_attribute = head;
  591. node->first_attribute = attr;
  592. }
  593. inline void insert_attribute_after(xml_attribute_struct* attr, xml_attribute_struct* place, xml_node_struct* node)
  594. {
  595. if (place->next_attribute)
  596. place->next_attribute->prev_attribute_c = attr;
  597. else
  598. node->first_attribute->prev_attribute_c = attr;
  599. attr->next_attribute = place->next_attribute;
  600. attr->prev_attribute_c = place;
  601. place->next_attribute = attr;
  602. }
  603. inline void insert_attribute_before(xml_attribute_struct* attr, xml_attribute_struct* place, xml_node_struct* node)
  604. {
  605. if (place->prev_attribute_c->next_attribute)
  606. place->prev_attribute_c->next_attribute = attr;
  607. else
  608. node->first_attribute = attr;
  609. attr->prev_attribute_c = place->prev_attribute_c;
  610. attr->next_attribute = place;
  611. place->prev_attribute_c = attr;
  612. }
  613. inline void remove_attribute(xml_attribute_struct* attr, xml_node_struct* node)
  614. {
  615. if (attr->next_attribute)
  616. attr->next_attribute->prev_attribute_c = attr->prev_attribute_c;
  617. else
  618. node->first_attribute->prev_attribute_c = attr->prev_attribute_c;
  619. if (attr->prev_attribute_c->next_attribute)
  620. attr->prev_attribute_c->next_attribute = attr->next_attribute;
  621. else
  622. node->first_attribute = attr->next_attribute;
  623. attr->prev_attribute_c = 0;
  624. attr->next_attribute = 0;
  625. }
  626. PUGI__FN_NO_INLINE xml_node_struct* append_new_node(xml_node_struct* node, xml_allocator& alloc, xml_node_type type = node_element)
  627. {
  628. xml_node_struct* child = allocate_node(alloc, type);
  629. if (!child) return 0;
  630. append_node(child, node);
  631. return child;
  632. }
  633. PUGI__FN_NO_INLINE xml_attribute_struct* append_new_attribute(xml_node_struct* node, xml_allocator& alloc)
  634. {
  635. xml_attribute_struct* attr = allocate_attribute(alloc);
  636. if (!attr) return 0;
  637. append_attribute(attr, node);
  638. return attr;
  639. }
  640. PUGI__NS_END
  641. // Helper classes for code generation
  642. PUGI__NS_BEGIN
  643. struct opt_false
  644. {
  645. enum { value = 0 };
  646. };
  647. struct opt_true
  648. {
  649. enum { value = 1 };
  650. };
  651. PUGI__NS_END
  652. // Unicode utilities
  653. PUGI__NS_BEGIN
  654. inline uint16_t endian_swap(uint16_t value)
  655. {
  656. return static_cast<uint16_t>(((value & 0xff) << 8) | (value >> 8));
  657. }
  658. inline uint32_t endian_swap(uint32_t value)
  659. {
  660. return ((value & 0xff) << 24) | ((value & 0xff00) << 8) | ((value & 0xff0000) >> 8) | (value >> 24);
  661. }
  662. struct utf8_counter
  663. {
  664. typedef size_t value_type;
  665. static value_type low(value_type result, uint32_t ch)
  666. {
  667. // U+0000..U+007F
  668. if (ch < 0x80) return result + 1;
  669. // U+0080..U+07FF
  670. else if (ch < 0x800) return result + 2;
  671. // U+0800..U+FFFF
  672. else return result + 3;
  673. }
  674. static value_type high(value_type result, uint32_t)
  675. {
  676. // U+10000..U+10FFFF
  677. return result + 4;
  678. }
  679. };
  680. struct utf8_writer
  681. {
  682. typedef uint8_t* value_type;
  683. static value_type low(value_type result, uint32_t ch)
  684. {
  685. // U+0000..U+007F
  686. if (ch < 0x80)
  687. {
  688. *result = static_cast<uint8_t>(ch);
  689. return result + 1;
  690. }
  691. // U+0080..U+07FF
  692. else if (ch < 0x800)
  693. {
  694. result[0] = static_cast<uint8_t>(0xC0 | (ch >> 6));
  695. result[1] = static_cast<uint8_t>(0x80 | (ch & 0x3F));
  696. return result + 2;
  697. }
  698. // U+0800..U+FFFF
  699. else
  700. {
  701. result[0] = static_cast<uint8_t>(0xE0 | (ch >> 12));
  702. result[1] = static_cast<uint8_t>(0x80 | ((ch >> 6) & 0x3F));
  703. result[2] = static_cast<uint8_t>(0x80 | (ch & 0x3F));
  704. return result + 3;
  705. }
  706. }
  707. static value_type high(value_type result, uint32_t ch)
  708. {
  709. // U+10000..U+10FFFF
  710. result[0] = static_cast<uint8_t>(0xF0 | (ch >> 18));
  711. result[1] = static_cast<uint8_t>(0x80 | ((ch >> 12) & 0x3F));
  712. result[2] = static_cast<uint8_t>(0x80 | ((ch >> 6) & 0x3F));
  713. result[3] = static_cast<uint8_t>(0x80 | (ch & 0x3F));
  714. return result + 4;
  715. }
  716. static value_type any(value_type result, uint32_t ch)
  717. {
  718. return (ch < 0x10000) ? low(result, ch) : high(result, ch);
  719. }
  720. };
  721. struct utf16_counter
  722. {
  723. typedef size_t value_type;
  724. static value_type low(value_type result, uint32_t)
  725. {
  726. return result + 1;
  727. }
  728. static value_type high(value_type result, uint32_t)
  729. {
  730. return result + 2;
  731. }
  732. };
  733. struct utf16_writer
  734. {
  735. typedef uint16_t* value_type;
  736. static value_type low(value_type result, uint32_t ch)
  737. {
  738. *result = static_cast<uint16_t>(ch);
  739. return result + 1;
  740. }
  741. static value_type high(value_type result, uint32_t ch)
  742. {
  743. uint32_t msh = static_cast<uint32_t>(ch - 0x10000) >> 10;
  744. uint32_t lsh = static_cast<uint32_t>(ch - 0x10000) & 0x3ff;
  745. result[0] = static_cast<uint16_t>(0xD800 + msh);
  746. result[1] = static_cast<uint16_t>(0xDC00 + lsh);
  747. return result + 2;
  748. }
  749. static value_type any(value_type result, uint32_t ch)
  750. {
  751. return (ch < 0x10000) ? low(result, ch) : high(result, ch);
  752. }
  753. };
  754. struct utf32_counter
  755. {
  756. typedef size_t value_type;
  757. static value_type low(value_type result, uint32_t)
  758. {
  759. return result + 1;
  760. }
  761. static value_type high(value_type result, uint32_t)
  762. {
  763. return result + 1;
  764. }
  765. };
  766. struct utf32_writer
  767. {
  768. typedef uint32_t* value_type;
  769. static value_type low(value_type result, uint32_t ch)
  770. {
  771. *result = ch;
  772. return result + 1;
  773. }
  774. static value_type high(value_type result, uint32_t ch)
  775. {
  776. *result = ch;
  777. return result + 1;
  778. }
  779. static value_type any(value_type result, uint32_t ch)
  780. {
  781. *result = ch;
  782. return result + 1;
  783. }
  784. };
  785. struct latin1_writer
  786. {
  787. typedef uint8_t* value_type;
  788. static value_type low(value_type result, uint32_t ch)
  789. {
  790. *result = static_cast<uint8_t>(ch > 255 ? '?' : ch);
  791. return result + 1;
  792. }
  793. static value_type high(value_type result, uint32_t ch)
  794. {
  795. (void)ch;
  796. *result = '?';
  797. return result + 1;
  798. }
  799. };
  800. template <size_t size> struct wchar_selector;
  801. template <> struct wchar_selector<2>
  802. {
  803. typedef uint16_t type;
  804. typedef utf16_counter counter;
  805. typedef utf16_writer writer;
  806. };
  807. template <> struct wchar_selector<4>
  808. {
  809. typedef uint32_t type;
  810. typedef utf32_counter counter;
  811. typedef utf32_writer writer;
  812. };
  813. typedef wchar_selector<sizeof(wchar_t)>::counter wchar_counter;
  814. typedef wchar_selector<sizeof(wchar_t)>::writer wchar_writer;
  815. template <typename Traits, typename opt_swap = opt_false> struct utf_decoder
  816. {
  817. static inline typename Traits::value_type decode_utf8_block(const uint8_t* data, size_t size, typename Traits::value_type result)
  818. {
  819. const uint8_t utf8_byte_mask = 0x3f;
  820. while (size)
  821. {
  822. uint8_t lead = *data;
  823. // 0xxxxxxx -> U+0000..U+007F
  824. if (lead < 0x80)
  825. {
  826. result = Traits::low(result, lead);
  827. data += 1;
  828. size -= 1;
  829. // process aligned single-byte (ascii) blocks
  830. if ((reinterpret_cast<uintptr_t>(data) & 3) == 0)
  831. {
  832. // round-trip through void* to silence 'cast increases required alignment of target type' warnings
  833. while (size >= 4 && (*static_cast<const uint32_t*>(static_cast<const void*>(data)) & 0x80808080) == 0)
  834. {
  835. result = Traits::low(result, data[0]);
  836. result = Traits::low(result, data[1]);
  837. result = Traits::low(result, data[2]);
  838. result = Traits::low(result, data[3]);
  839. data += 4;
  840. size -= 4;
  841. }
  842. }
  843. }
  844. // 110xxxxx -> U+0080..U+07FF
  845. else if (static_cast<unsigned int>(lead - 0xC0) < 0x20 && size >= 2 && (data[1] & 0xc0) == 0x80)
  846. {
  847. result = Traits::low(result, ((lead & ~0xC0) << 6) | (data[1] & utf8_byte_mask));
  848. data += 2;
  849. size -= 2;
  850. }
  851. // 1110xxxx -> U+0800-U+FFFF
  852. else if (static_cast<unsigned int>(lead - 0xE0) < 0x10 && size >= 3 && (data[1] & 0xc0) == 0x80 && (data[2] & 0xc0) == 0x80)
  853. {
  854. result = Traits::low(result, ((lead & ~0xE0) << 12) | ((data[1] & utf8_byte_mask) << 6) | (data[2] & utf8_byte_mask));
  855. data += 3;
  856. size -= 3;
  857. }
  858. // 11110xxx -> U+10000..U+10FFFF
  859. else if (static_cast<unsigned int>(lead - 0xF0) < 0x08 && size >= 4 && (data[1] & 0xc0) == 0x80 && (data[2] & 0xc0) == 0x80 && (data[3] & 0xc0) == 0x80)
  860. {
  861. result = Traits::high(result, ((lead & ~0xF0) << 18) | ((data[1] & utf8_byte_mask) << 12) | ((data[2] & utf8_byte_mask) << 6) | (data[3] & utf8_byte_mask));
  862. data += 4;
  863. size -= 4;
  864. }
  865. // 10xxxxxx or 11111xxx -> invalid
  866. else
  867. {
  868. data += 1;
  869. size -= 1;
  870. }
  871. }
  872. return result;
  873. }
  874. static inline typename Traits::value_type decode_utf16_block(const uint16_t* data, size_t size, typename Traits::value_type result)
  875. {
  876. const uint16_t* end = data + size;
  877. while (data < end)
  878. {
  879. unsigned int lead = opt_swap::value ? endian_swap(*data) : *data;
  880. // U+0000..U+D7FF
  881. if (lead < 0xD800)
  882. {
  883. result = Traits::low(result, lead);
  884. data += 1;
  885. }
  886. // U+E000..U+FFFF
  887. else if (static_cast<unsigned int>(lead - 0xE000) < 0x2000)
  888. {
  889. result = Traits::low(result, lead);
  890. data += 1;
  891. }
  892. // surrogate pair lead
  893. else if (static_cast<unsigned int>(lead - 0xD800) < 0x400 && data + 1 < end)
  894. {
  895. uint16_t next = opt_swap::value ? endian_swap(data[1]) : data[1];
  896. if (static_cast<unsigned int>(next - 0xDC00) < 0x400)
  897. {
  898. result = Traits::high(result, 0x10000 + ((lead & 0x3ff) << 10) + (next & 0x3ff));
  899. data += 2;
  900. }
  901. else
  902. {
  903. data += 1;
  904. }
  905. }
  906. else
  907. {
  908. data += 1;
  909. }
  910. }
  911. return result;
  912. }
  913. static inline typename Traits::value_type decode_utf32_block(const uint32_t* data, size_t size, typename Traits::value_type result)
  914. {
  915. const uint32_t* end = data + size;
  916. while (data < end)
  917. {
  918. uint32_t lead = opt_swap::value ? endian_swap(*data) : *data;
  919. // U+0000..U+FFFF
  920. if (lead < 0x10000)
  921. {
  922. result = Traits::low(result, lead);
  923. data += 1;
  924. }
  925. // U+10000..U+10FFFF
  926. else
  927. {
  928. result = Traits::high(result, lead);
  929. data += 1;
  930. }
  931. }
  932. return result;
  933. }
  934. static inline typename Traits::value_type decode_latin1_block(const uint8_t* data, size_t size, typename Traits::value_type result)
  935. {
  936. for (size_t i = 0; i < size; ++i)
  937. {
  938. result = Traits::low(result, data[i]);
  939. }
  940. return result;
  941. }
  942. static inline typename Traits::value_type decode_wchar_block_impl(const uint16_t* data, size_t size, typename Traits::value_type result)
  943. {
  944. return decode_utf16_block(data, size, result);
  945. }
  946. static inline typename Traits::value_type decode_wchar_block_impl(const uint32_t* data, size_t size, typename Traits::value_type result)
  947. {
  948. return decode_utf32_block(data, size, result);
  949. }
  950. static inline typename Traits::value_type decode_wchar_block(const wchar_t* data, size_t size, typename Traits::value_type result)
  951. {
  952. return decode_wchar_block_impl(reinterpret_cast<const wchar_selector<sizeof(wchar_t)>::type*>(data), size, result);
  953. }
  954. };
  955. template <typename T> PUGI__FN void convert_utf_endian_swap(T* result, const T* data, size_t length)
  956. {
  957. for (size_t i = 0; i < length; ++i) result[i] = endian_swap(data[i]);
  958. }
  959. #ifdef PUGIXML_WCHAR_MODE
  960. PUGI__FN void convert_wchar_endian_swap(wchar_t* result, const wchar_t* data, size_t length)
  961. {
  962. for (size_t i = 0; i < length; ++i) result[i] = static_cast<wchar_t>(endian_swap(static_cast<wchar_selector<sizeof(wchar_t)>::type>(data[i])));
  963. }
  964. #endif
  965. PUGI__NS_END
  966. PUGI__NS_BEGIN
  967. enum chartype_t
  968. {
  969. ct_parse_pcdata = 1, // \0, &, \r, <
  970. ct_parse_attr = 2, // \0, &, \r, ', "
  971. ct_parse_attr_ws = 4, // \0, &, \r, ', ", \n, tab
  972. ct_space = 8, // \r, \n, space, tab
  973. ct_parse_cdata = 16, // \0, ], >, \r
  974. ct_parse_comment = 32, // \0, -, >, \r
  975. ct_symbol = 64, // Any symbol > 127, a-z, A-Z, 0-9, _, :, -, .
  976. ct_start_symbol = 128 // Any symbol > 127, a-z, A-Z, _, :
  977. };
  978. static const unsigned char chartype_table[256] =
  979. {
  980. 55, 0, 0, 0, 0, 0, 0, 0, 0, 12, 12, 0, 0, 63, 0, 0, // 0-15
  981. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // 16-31
  982. 8, 0, 6, 0, 0, 0, 7, 6, 0, 0, 0, 0, 0, 96, 64, 0, // 32-47
  983. 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 192, 0, 1, 0, 48, 0, // 48-63
  984. 0, 192, 192, 192, 192, 192, 192, 192, 192, 192, 192, 192, 192, 192, 192, 192, // 64-79
  985. 192, 192, 192, 192, 192, 192, 192, 192, 192, 192, 192, 0, 0, 16, 0, 192, // 80-95
  986. 0, 192, 192, 192, 192, 192, 192, 192, 192, 192, 192, 192, 192, 192, 192, 192, // 96-111
  987. 192, 192, 192, 192, 192, 192, 192, 192, 192, 192, 192, 0, 0, 0, 0, 0, // 112-127
  988. 192, 192, 192, 192, 192, 192, 192, 192, 192, 192, 192, 192, 192, 192, 192, 192, // 128+
  989. 192, 192, 192, 192, 192, 192, 192, 192, 192, 192, 192, 192, 192, 192, 192, 192,
  990. 192, 192, 192, 192, 192, 192, 192, 192, 192, 192, 192, 192, 192, 192, 192, 192,
  991. 192, 192, 192, 192, 192, 192, 192, 192, 192, 192, 192, 192, 192, 192, 192, 192,
  992. 192, 192, 192, 192, 192, 192, 192, 192, 192, 192, 192, 192, 192, 192, 192, 192,
  993. 192, 192, 192, 192, 192, 192, 192, 192, 192, 192, 192, 192, 192, 192, 192, 192,
  994. 192, 192, 192, 192, 192, 192, 192, 192, 192, 192, 192, 192, 192, 192, 192, 192,
  995. 192, 192, 192, 192, 192, 192, 192, 192, 192, 192, 192, 192, 192, 192, 192, 192
  996. };
  997. enum chartypex_t
  998. {
  999. ctx_special_pcdata = 1, // Any symbol >= 0 and < 32 (except \t, \r, \n), &, <, >
  1000. ctx_special_attr = 2, // Any symbol >= 0 and < 32 (except \t), &, <, >, "
  1001. ctx_start_symbol = 4, // Any symbol > 127, a-z, A-Z, _
  1002. ctx_digit = 8, // 0-9
  1003. ctx_symbol = 16 // Any symbol > 127, a-z, A-Z, 0-9, _, -, .
  1004. };
  1005. static const unsigned char chartypex_table[256] =
  1006. {
  1007. 3, 3, 3, 3, 3, 3, 3, 3, 3, 0, 2, 3, 3, 2, 3, 3, // 0-15
  1008. 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, // 16-31
  1009. 0, 0, 2, 0, 0, 0, 3, 0, 0, 0, 0, 0, 0, 16, 16, 0, // 32-47
  1010. 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 0, 0, 3, 0, 3, 0, // 48-63
  1011. 0, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, // 64-79
  1012. 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 0, 0, 0, 0, 20, // 80-95
  1013. 0, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, // 96-111
  1014. 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 0, 0, 0, 0, 0, // 112-127
  1015. 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, // 128+
  1016. 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20,
  1017. 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20,
  1018. 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20,
  1019. 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20,
  1020. 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20,
  1021. 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20,
  1022. 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20
  1023. };
  1024. #ifdef PUGIXML_WCHAR_MODE
  1025. #define PUGI__IS_CHARTYPE_IMPL(c, ct, table) ((static_cast<unsigned int>(c) < 128 ? table[static_cast<unsigned int>(c)] : table[128]) & (ct))
  1026. #else
  1027. #define PUGI__IS_CHARTYPE_IMPL(c, ct, table) (table[static_cast<unsigned char>(c)] & (ct))
  1028. #endif
  1029. #define PUGI__IS_CHARTYPE(c, ct) PUGI__IS_CHARTYPE_IMPL(c, ct, chartype_table)
  1030. #define PUGI__IS_CHARTYPEX(c, ct) PUGI__IS_CHARTYPE_IMPL(c, ct, chartypex_table)
  1031. PUGI__FN bool is_little_endian()
  1032. {
  1033. unsigned int ui = 1;
  1034. return *reinterpret_cast<unsigned char*>(&ui) == 1;
  1035. }
  1036. PUGI__FN xml_encoding get_wchar_encoding()
  1037. {
  1038. PUGI__STATIC_ASSERT(sizeof(wchar_t) == 2 || sizeof(wchar_t) == 4);
  1039. if (sizeof(wchar_t) == 2)
  1040. return is_little_endian() ? encoding_utf16_le : encoding_utf16_be;
  1041. else
  1042. return is_little_endian() ? encoding_utf32_le : encoding_utf32_be;
  1043. }
  1044. PUGI__FN xml_encoding guess_buffer_encoding(uint8_t d0, uint8_t d1, uint8_t d2, uint8_t d3)
  1045. {
  1046. // look for BOM in first few bytes
  1047. if (d0 == 0 && d1 == 0 && d2 == 0xfe && d3 == 0xff) return encoding_utf32_be;
  1048. if (d0 == 0xff && d1 == 0xfe && d2 == 0 && d3 == 0) return encoding_utf32_le;
  1049. if (d0 == 0xfe && d1 == 0xff) return encoding_utf16_be;
  1050. if (d0 == 0xff && d1 == 0xfe) return encoding_utf16_le;
  1051. if (d0 == 0xef && d1 == 0xbb && d2 == 0xbf) return encoding_utf8;
  1052. // look for <, <? or <?xm in various encodings
  1053. if (d0 == 0 && d1 == 0 && d2 == 0 && d3 == 0x3c) return encoding_utf32_be;
  1054. if (d0 == 0x3c && d1 == 0 && d2 == 0 && d3 == 0) return encoding_utf32_le;
  1055. if (d0 == 0 && d1 == 0x3c && d2 == 0 && d3 == 0x3f) return encoding_utf16_be;
  1056. if (d0 == 0x3c && d1 == 0 && d2 == 0x3f && d3 == 0) return encoding_utf16_le;
  1057. if (d0 == 0x3c && d1 == 0x3f && d2 == 0x78 && d3 == 0x6d) return encoding_utf8;
  1058. // look for utf16 < followed by node name (this may fail, but is better than utf8 since it's zero terminated so early)
  1059. if (d0 == 0 && d1 == 0x3c) return encoding_utf16_be;
  1060. if (d0 == 0x3c && d1 == 0) return encoding_utf16_le;
  1061. // no known BOM detected, assume utf8
  1062. return encoding_utf8;
  1063. }
  1064. PUGI__FN xml_encoding get_buffer_encoding(xml_encoding encoding, const void* contents, size_t size)
  1065. {
  1066. // replace wchar encoding with utf implementation
  1067. if (encoding == encoding_wchar) return get_wchar_encoding();
  1068. // replace utf16 encoding with utf16 with specific endianness
  1069. if (encoding == encoding_utf16) return is_little_endian() ? encoding_utf16_le : encoding_utf16_be;
  1070. // replace utf32 encoding with utf32 with specific endianness
  1071. if (encoding == encoding_utf32) return is_little_endian() ? encoding_utf32_le : encoding_utf32_be;
  1072. // only do autodetection if no explicit encoding is requested
  1073. if (encoding != encoding_auto) return encoding;
  1074. // skip encoding autodetection if input buffer is too small
  1075. if (size < 4) return encoding_utf8;
  1076. // try to guess encoding (based on XML specification, Appendix F.1)
  1077. const uint8_t* data = static_cast<const uint8_t*>(contents);
  1078. PUGI__DMC_VOLATILE uint8_t d0 = data[0], d1 = data[1], d2 = data[2], d3 = data[3];
  1079. return guess_buffer_encoding(d0, d1, d2, d3);
  1080. }
  1081. PUGI__FN bool get_mutable_buffer(char_t*& out_buffer, size_t& out_length, const void* contents, size_t size, bool is_mutable)
  1082. {
  1083. size_t length = size / sizeof(char_t);
  1084. if (is_mutable)
  1085. {
  1086. out_buffer = static_cast<char_t*>(const_cast<void*>(contents));
  1087. out_length = length;
  1088. }
  1089. else
  1090. {
  1091. char_t* buffer = static_cast<char_t*>(xml_memory::allocate((length + 1) * sizeof(char_t)));
  1092. if (!buffer) return false;
  1093. if (contents)
  1094. memcpy(buffer, contents, length * sizeof(char_t));
  1095. else
  1096. assert(length == 0);
  1097. buffer[length] = 0;
  1098. out_buffer = buffer;
  1099. out_length = length + 1;
  1100. }
  1101. return true;
  1102. }
  1103. #ifdef PUGIXML_WCHAR_MODE
  1104. PUGI__FN bool need_endian_swap_utf(xml_encoding le, xml_encoding re)
  1105. {
  1106. return (le == encoding_utf16_be && re == encoding_utf16_le) || (le == encoding_utf16_le && re == encoding_utf16_be) ||
  1107. (le == encoding_utf32_be && re == encoding_utf32_le) || (le == encoding_utf32_le && re == encoding_utf32_be);
  1108. }
  1109. PUGI__FN bool convert_buffer_endian_swap(char_t*& out_buffer, size_t& out_length, const void* contents, size_t size, bool is_mutable)
  1110. {
  1111. const char_t* data = static_cast<const char_t*>(contents);
  1112. size_t length = size / sizeof(char_t);
  1113. if (is_mutable)
  1114. {
  1115. char_t* buffer = const_cast<char_t*>(data);
  1116. convert_wchar_endian_swap(buffer, data, length);
  1117. out_buffer = buffer;
  1118. out_length = length;
  1119. }
  1120. else
  1121. {
  1122. char_t* buffer = static_cast<char_t*>(xml_memory::allocate((length + 1) * sizeof(char_t)));
  1123. if (!buffer) return false;
  1124. convert_wchar_endian_swap(buffer, data, length);
  1125. buffer[length] = 0;
  1126. out_buffer = buffer;
  1127. out_length = length + 1;
  1128. }
  1129. return true;
  1130. }
  1131. PUGI__FN bool convert_buffer_utf8(char_t*& out_buffer, size_t& out_length, const void* contents, size_t size)
  1132. {
  1133. const uint8_t* data = static_cast<const uint8_t*>(contents);
  1134. size_t data_length = size;
  1135. // first pass: get length in wchar_t units
  1136. size_t length = utf_decoder<wchar_counter>::decode_utf8_block(data, data_length, 0);
  1137. // allocate buffer of suitable length
  1138. char_t* buffer = static_cast<char_t*>(xml_memory::allocate((length + 1) * sizeof(char_t)));
  1139. if (!buffer) return false;
  1140. // second pass: convert utf8 input to wchar_t
  1141. wchar_writer::value_type obegin = reinterpret_cast<wchar_writer::value_type>(buffer);
  1142. wchar_writer::value_type oend = utf_decoder<wchar_writer>::decode_utf8_block(data, data_length, obegin);
  1143. assert(oend == obegin + length);
  1144. *oend = 0;
  1145. out_buffer = buffer;
  1146. out_length = length + 1;
  1147. return true;
  1148. }
  1149. template <typename opt_swap> PUGI__FN bool convert_buffer_utf16(char_t*& out_buffer, size_t& out_length, const void* contents, size_t size, opt_swap)
  1150. {
  1151. const uint16_t* data = static_cast<const uint16_t*>(contents);
  1152. size_t data_length = size / sizeof(uint16_t);
  1153. // first pass: get length in wchar_t units
  1154. size_t length = utf_decoder<wchar_counter, opt_swap>::decode_utf16_block(data, data_length, 0);
  1155. // allocate buffer of suitable length
  1156. char_t* buffer = static_cast<char_t*>(xml_memory::allocate((length + 1) * sizeof(char_t)));
  1157. if (!buffer) return false;
  1158. // second pass: convert utf16 input to wchar_t
  1159. wchar_writer::value_type obegin = reinterpret_cast<wchar_writer::value_type>(buffer);
  1160. wchar_writer::value_type oend = utf_decoder<wchar_writer, opt_swap>::decode_utf16_block(data, data_length, obegin);
  1161. assert(oend == obegin + length);
  1162. *oend = 0;
  1163. out_buffer = buffer;
  1164. out_length = length + 1;
  1165. return true;
  1166. }
  1167. template <typename opt_swap> PUGI__FN bool convert_buffer_utf32(char_t*& out_buffer, size_t& out_length, const void* contents, size_t size, opt_swap)
  1168. {
  1169. const uint32_t* data = static_cast<const uint32_t*>(contents);
  1170. size_t data_length = size / sizeof(uint32_t);
  1171. // first pass: get length in wchar_t units
  1172. size_t length = utf_decoder<wchar_counter, opt_swap>::decode_utf32_block(data, data_length, 0);
  1173. // allocate buffer of suitable length
  1174. char_t* buffer = static_cast<char_t*>(xml_memory::allocate((length + 1) * sizeof(char_t)));
  1175. if (!buffer) return false;
  1176. // second pass: convert utf32 input to wchar_t
  1177. wchar_writer::value_type obegin = reinterpret_cast<wchar_writer::value_type>(buffer);
  1178. wchar_writer::value_type oend = utf_decoder<wchar_writer, opt_swap>::decode_utf32_block(data, data_length, obegin);
  1179. assert(oend == obegin + length);
  1180. *oend = 0;
  1181. out_buffer = buffer;
  1182. out_length = length + 1;
  1183. return true;
  1184. }
  1185. PUGI__FN bool convert_buffer_latin1(char_t*& out_buffer, size_t& out_length, const void* contents, size_t size)
  1186. {
  1187. const uint8_t* data = static_cast<const uint8_t*>(contents);
  1188. size_t data_length = size;
  1189. // get length in wchar_t units
  1190. size_t length = data_length;
  1191. // allocate buffer of suitable length
  1192. char_t* buffer = static_cast<char_t*>(xml_memory::allocate((length + 1) * sizeof(char_t)));
  1193. if (!buffer) return false;
  1194. // convert latin1 input to wchar_t
  1195. wchar_writer::value_type obegin = reinterpret_cast<wchar_writer::value_type>(buffer);
  1196. wchar_writer::value_type oend = utf_decoder<wchar_writer>::decode_latin1_block(data, data_length, obegin);
  1197. assert(oend == obegin + length);
  1198. *oend = 0;
  1199. out_buffer = buffer;
  1200. out_length = length + 1;
  1201. return true;
  1202. }
  1203. PUGI__FN bool convert_buffer(char_t*& out_buffer, size_t& out_length, xml_encoding encoding, const void* contents, size_t size, bool is_mutable)
  1204. {
  1205. // get native encoding
  1206. xml_encoding wchar_encoding = get_wchar_encoding();
  1207. // fast path: no conversion required
  1208. if (encoding == wchar_encoding) return get_mutable_buffer(out_buffer, out_length, contents, size, is_mutable);
  1209. // only endian-swapping is required
  1210. if (need_endian_swap_utf(encoding, wchar_encoding)) return convert_buffer_endian_swap(out_buffer, out_length, contents, size, is_mutable);
  1211. // source encoding is utf8
  1212. if (encoding == encoding_utf8) return convert_buffer_utf8(out_buffer, out_length, contents, size);
  1213. // source encoding is utf16
  1214. if (encoding == encoding_utf16_be || encoding == encoding_utf16_le)
  1215. {
  1216. xml_encoding native_encoding = is_little_endian() ? encoding_utf16_le : encoding_utf16_be;
  1217. return (native_encoding == encoding) ?
  1218. convert_buffer_utf16(out_buffer, out_length, contents, size, opt_false()) :
  1219. convert_buffer_utf16(out_buffer, out_length, contents, size, opt_true());
  1220. }
  1221. // source encoding is utf32
  1222. if (encoding == encoding_utf32_be || encoding == encoding_utf32_le)
  1223. {
  1224. xml_encoding native_encoding = is_little_endian() ? encoding_utf32_le : encoding_utf32_be;
  1225. return (native_encoding == encoding) ?
  1226. convert_buffer_utf32(out_buffer, out_length, contents, size, opt_false()) :
  1227. convert_buffer_utf32(out_buffer, out_length, contents, size, opt_true());
  1228. }
  1229. // source encoding is latin1
  1230. if (encoding == encoding_latin1) return convert_buffer_latin1(out_buffer, out_length, contents, size);
  1231. assert(!"Invalid encoding");
  1232. return false;
  1233. }
  1234. #else
  1235. template <typename opt_swap> PUGI__FN bool convert_buffer_utf16(char_t*& out_buffer, size_t& out_length, const void* contents, size_t size, opt_swap)
  1236. {
  1237. const uint16_t* data = static_cast<const uint16_t*>(contents);
  1238. size_t data_length = size / sizeof(uint16_t);
  1239. // first pass: get length in utf8 units
  1240. size_t length = utf_decoder<utf8_counter, opt_swap>::decode_utf16_block(data, data_length, 0);
  1241. // allocate buffer of suitable length
  1242. char_t* buffer = static_cast<char_t*>(xml_memory::allocate((length + 1) * sizeof(char_t)));
  1243. if (!buffer) return false;
  1244. // second pass: convert utf16 input to utf8
  1245. uint8_t* obegin = reinterpret_cast<uint8_t*>(buffer);
  1246. uint8_t* oend = utf_decoder<utf8_writer, opt_swap>::decode_utf16_block(data, data_length, obegin);
  1247. assert(oend == obegin + length);
  1248. *oend = 0;
  1249. out_buffer = buffer;
  1250. out_length = length + 1;
  1251. return true;
  1252. }
  1253. template <typename opt_swap> PUGI__FN bool convert_buffer_utf32(char_t*& out_buffer, size_t& out_length, const void* contents, size_t size, opt_swap)
  1254. {
  1255. const uint32_t* data = static_cast<const uint32_t*>(contents);
  1256. size_t data_length = size / sizeof(uint32_t);
  1257. // first pass: get length in utf8 units
  1258. size_t length = utf_decoder<utf8_counter, opt_swap>::decode_utf32_block(data, data_length, 0);
  1259. // allocate buffer of suitable length
  1260. char_t* buffer = static_cast<char_t*>(xml_memory::allocate((length + 1) * sizeof(char_t)));
  1261. if (!buffer) return false;
  1262. // second pass: convert utf32 input to utf8
  1263. uint8_t* obegin = reinterpret_cast<uint8_t*>(buffer);
  1264. uint8_t* oend = utf_decoder<utf8_writer, opt_swap>::decode_utf32_block(data, data_length, obegin);
  1265. assert(oend == obegin + length);
  1266. *oend = 0;
  1267. out_buffer = buffer;
  1268. out_length = length + 1;
  1269. return true;
  1270. }
  1271. PUGI__FN size_t get_latin1_7bit_prefix_length(const uint8_t* data, size_t size)
  1272. {
  1273. for (size_t i = 0; i < size; ++i)
  1274. if (data[i] > 127)
  1275. return i;
  1276. return size;
  1277. }
  1278. PUGI__FN bool convert_buffer_latin1(char_t*& out_buffer, size_t& out_length, const void* contents, size_t size, bool is_mutable)
  1279. {
  1280. const uint8_t* data = static_cast<const uint8_t*>(contents);
  1281. size_t data_length = size;
  1282. // get size of prefix that does not need utf8 conversion
  1283. size_t prefix_length = get_latin1_7bit_prefix_length(data, data_length);
  1284. assert(prefix_length <= data_length);
  1285. const uint8_t* postfix = data + prefix_length;
  1286. size_t postfix_length = data_length - prefix_length;
  1287. // if no conversion is needed, just return the original buffer
  1288. if (postfix_length == 0) return get_mutable_buffer(out_buffer, out_length, contents, size, is_mutable);
  1289. // first pass: get length in utf8 units
  1290. size_t length = prefix_length + utf_decoder<utf8_counter>::decode_latin1_block(postfix, postfix_length, 0);
  1291. // allocate buffer of suitable length
  1292. char_t* buffer = static_cast<char_t*>(xml_memory::allocate((length + 1) * sizeof(char_t)));
  1293. if (!buffer) return false;
  1294. // second pass: convert latin1 input to utf8
  1295. memcpy(buffer, data, prefix_length);
  1296. uint8_t* obegin = reinterpret_cast<uint8_t*>(buffer);
  1297. uint8_t* oend = utf_decoder<utf8_writer>::decode_latin1_block(postfix, postfix_length, obegin + prefix_length);
  1298. assert(oend == obegin + length);
  1299. *oend = 0;
  1300. out_buffer = buffer;
  1301. out_length = length + 1;
  1302. return true;
  1303. }
  1304. PUGI__FN bool convert_buffer(char_t*& out_buffer, size_t& out_length, xml_encoding encoding, const void* contents, size_t size, bool is_mutable)
  1305. {
  1306. // fast path: no conversion required
  1307. if (encoding == encoding_utf8) return get_mutable_buffer(out_buffer, out_length, contents, size, is_mutable);
  1308. // source encoding is utf16
  1309. if (encoding == encoding_utf16_be || encoding == encoding_utf16_le)
  1310. {
  1311. xml_encoding native_encoding = is_little_endian() ? encoding_utf16_le : encoding_utf16_be;
  1312. return (native_encoding == encoding) ?
  1313. convert_buffer_utf16(out_buffer, out_length, contents, size, opt_false()) :
  1314. convert_buffer_utf16(out_buffer, out_length, contents, size, opt_true());
  1315. }
  1316. // source encoding is utf32
  1317. if (encoding == encoding_utf32_be || encoding == encoding_utf32_le)
  1318. {
  1319. xml_encoding native_encoding = is_little_endian() ? encoding_utf32_le : encoding_utf32_be;
  1320. return (native_encoding == encoding) ?
  1321. convert_buffer_utf32(out_buffer, out_length, contents, size, opt_false()) :
  1322. convert_buffer_utf32(out_buffer, out_length, contents, size, opt_true());
  1323. }
  1324. // source encoding is latin1
  1325. if (encoding == encoding_latin1) return convert_buffer_latin1(out_buffer, out_length, contents, size, is_mutable);
  1326. assert(!"Invalid encoding");
  1327. return false;
  1328. }
  1329. #endif
  1330. PUGI__FN size_t as_utf8_begin(const wchar_t* str, size_t length)
  1331. {
  1332. // get length in utf8 characters
  1333. return utf_decoder<utf8_counter>::decode_wchar_block(str, length, 0);
  1334. }
  1335. PUGI__FN void as_utf8_end(char* buffer, size_t size, const wchar_t* str, size_t length)
  1336. {
  1337. // convert to utf8
  1338. uint8_t* begin = reinterpret_cast<uint8_t*>(buffer);
  1339. uint8_t* end = utf_decoder<utf8_writer>::decode_wchar_block(str, length, begin);
  1340. assert(begin + size == end);
  1341. (void)!end;
  1342. // zero-terminate
  1343. buffer[size] = 0;
  1344. }
  1345. #ifndef PUGIXML_NO_STL
  1346. PUGI__FN std::string as_utf8_impl(const wchar_t* str, size_t length)
  1347. {
  1348. // first pass: get length in utf8 characters
  1349. size_t size = as_utf8_begin(str, length);
  1350. // allocate resulting string
  1351. std::string result;
  1352. result.resize(size);
  1353. // second pass: convert to utf8
  1354. if (size > 0) as_utf8_end(&result[0], size, str, length);
  1355. return result;
  1356. }
  1357. PUGI__FN std::basic_string<wchar_t> as_wide_impl(const char* str, size_t size)
  1358. {
  1359. const uint8_t* data = reinterpret_cast<const uint8_t*>(str);
  1360. // first pass: get length in wchar_t units
  1361. size_t length = utf_decoder<wchar_counter>::decode_utf8_block(data, size, 0);
  1362. // allocate resulting string
  1363. std::basic_string<wchar_t> result;
  1364. result.resize(length);
  1365. // second pass: convert to wchar_t
  1366. if (length > 0)
  1367. {
  1368. wchar_writer::value_type begin = reinterpret_cast<wchar_writer::value_type>(&result[0]);
  1369. wchar_writer::value_type end = utf_decoder<wchar_writer>::decode_utf8_block(data, size, begin);
  1370. assert(begin + length == end);
  1371. (void)!end;
  1372. }
  1373. return result;
  1374. }
  1375. #endif
  1376. inline bool strcpy_insitu_allow(size_t length, uintptr_t header, uintptr_t header_mask, char_t* target)
  1377. {
  1378. // never reuse shared memory
  1379. if (header & xml_memory_page_contents_shared_mask) return false;
  1380. size_t target_length = strlength(target);
  1381. // always reuse document buffer memory if possible
  1382. if ((header & header_mask) == 0) return target_length >= length;
  1383. // reuse heap memory if waste is not too great
  1384. const size_t reuse_threshold = 32;
  1385. return target_length >= length && (target_length < reuse_threshold || target_length - length < target_length / 2);
  1386. }
  1387. PUGI__FN bool strcpy_insitu(char_t*& dest, uintptr_t& header, uintptr_t header_mask, const char_t* source)
  1388. {
  1389. assert(header);
  1390. size_t source_length = strlength(source);
  1391. if (source_length == 0)
  1392. {
  1393. // empty string and null pointer are equivalent, so just deallocate old memory
  1394. xml_allocator* alloc = reinterpret_cast<xml_memory_page*>(header & xml_memory_page_pointer_mask)->allocator;
  1395. if (header & header_mask) alloc->deallocate_string(dest);
  1396. // mark the string as not allocated
  1397. dest = 0;
  1398. header &= ~header_mask;
  1399. return true;
  1400. }
  1401. else if (dest && strcpy_insitu_allow(source_length, header, header_mask, dest))
  1402. {
  1403. // we can reuse old buffer, so just copy the new data (including zero terminator)
  1404. memcpy(dest, source, (source_length + 1) * sizeof(char_t));
  1405. return true;
  1406. }
  1407. else
  1408. {
  1409. xml_allocator* alloc = reinterpret_cast<xml_memory_page*>(header & xml_memory_page_pointer_mask)->allocator;
  1410. // allocate new buffer
  1411. char_t* buf = alloc->allocate_string(source_length + 1);
  1412. if (!buf) return false;
  1413. // copy the string (including zero terminator)
  1414. memcpy(buf, source, (source_length + 1) * sizeof(char_t));
  1415. // deallocate old buffer (*after* the above to protect against overlapping memory and/or allocation failures)
  1416. if (header & header_mask) alloc->deallocate_string(dest);
  1417. // the string is now allocated, so set the flag
  1418. dest = buf;
  1419. header |= header_mask;
  1420. return true;
  1421. }
  1422. }
  1423. struct gap
  1424. {
  1425. char_t* end;
  1426. size_t size;
  1427. gap(): end(0), size(0)
  1428. {
  1429. }
  1430. // Push new gap, move s count bytes further (skipping the gap).
  1431. // Collapse previous gap.
  1432. void push(char_t*& s, size_t count)
  1433. {
  1434. if (end) // there was a gap already; collapse it
  1435. {
  1436. // Move [old_gap_end, new_gap_start) to [old_gap_start, ...)
  1437. assert(s >= end);
  1438. memmove(end - size, end, reinterpret_cast<char*>(s) - reinterpret_cast<char*>(end));
  1439. }
  1440. s += count; // end of current gap
  1441. // "merge" two gaps
  1442. end = s;
  1443. size += count;
  1444. }
  1445. // Collapse all gaps, return past-the-end pointer
  1446. char_t* flush(char_t* s)
  1447. {
  1448. if (end)
  1449. {
  1450. // Move [old_gap_end, current_pos) to [old_gap_start, ...)
  1451. assert(s >= end);
  1452. memmove(end - size, end, reinterpret_cast<char*>(s) - reinterpret_cast<char*>(end));
  1453. return s - size;
  1454. }
  1455. else return s;
  1456. }
  1457. };
  1458. PUGI__FN char_t* strconv_escape(char_t* s, gap& g)
  1459. {
  1460. char_t* stre = s + 1;
  1461. switch (*stre)
  1462. {
  1463. case '#': // &#...
  1464. {
  1465. unsigned int ucsc = 0;
  1466. if (stre[1] == 'x') // &#x... (hex code)
  1467. {
  1468. stre += 2;
  1469. char_t ch = *stre;
  1470. if (ch == ';') return stre;
  1471. for (;;)
  1472. {
  1473. if (static_cast<unsigned int>(ch - '0') <= 9)
  1474. ucsc = 16 * ucsc + (ch - '0');
  1475. else if (static_cast<unsigned int>((ch | ' ') - 'a') <= 5)
  1476. ucsc = 16 * ucsc + ((ch | ' ') - 'a' + 10);
  1477. else if (ch == ';')
  1478. break;
  1479. else // cancel
  1480. return stre;
  1481. ch = *++stre;
  1482. }
  1483. ++stre;
  1484. }
  1485. else // &#... (dec code)
  1486. {
  1487. char_t ch = *++stre;
  1488. if (ch == ';') return stre;
  1489. for (;;)
  1490. {
  1491. if (static_cast<unsigned int>(static_cast<unsigned int>(ch) - '0') <= 9)
  1492. ucsc = 10 * ucsc + (ch - '0');
  1493. else if (ch == ';')
  1494. break;
  1495. else // cancel
  1496. return stre;
  1497. ch = *++stre;
  1498. }
  1499. ++stre;
  1500. }
  1501. #ifdef PUGIXML_WCHAR_MODE
  1502. s = reinterpret_cast<char_t*>(wchar_writer::any(reinterpret_cast<wchar_writer::value_type>(s), ucsc));
  1503. #else
  1504. s = reinterpret_cast<char_t*>(utf8_writer::any(reinterpret_cast<uint8_t*>(s), ucsc));
  1505. #endif
  1506. g.push(s, stre - s);
  1507. return stre;
  1508. }
  1509. case 'a': // &a
  1510. {
  1511. ++stre;
  1512. if (*stre == 'm') // &am
  1513. {
  1514. if (*++stre == 'p' && *++stre == ';') // &amp;
  1515. {
  1516. *s++ = '&';
  1517. ++stre;
  1518. g.push(s, stre - s);
  1519. return stre;
  1520. }
  1521. }
  1522. else if (*stre == 'p') // &ap
  1523. {
  1524. if (*++stre == 'o' && *++stre == 's' && *++stre == ';') // &apos;
  1525. {
  1526. *s++ = '\'';
  1527. ++stre;
  1528. g.push(s, stre - s);
  1529. return stre;
  1530. }
  1531. }
  1532. break;
  1533. }
  1534. case 'g': // &g
  1535. {
  1536. if (*++stre == 't' && *++stre == ';') // &gt;
  1537. {
  1538. *s++ = '>';
  1539. ++stre;
  1540. g.push(s, stre - s);
  1541. return stre;
  1542. }
  1543. break;
  1544. }
  1545. case 'l': // &l
  1546. {
  1547. if (*++stre == 't' && *++stre == ';') // &lt;
  1548. {
  1549. *s++ = '<';
  1550. ++stre;
  1551. g.push(s, stre - s);
  1552. return stre;
  1553. }
  1554. break;
  1555. }
  1556. case 'q': // &q
  1557. {
  1558. if (*++stre == 'u' && *++stre == 'o' && *++stre == 't' && *++stre == ';') // &quot;
  1559. {
  1560. *s++ = '"';
  1561. ++stre;
  1562. g.push(s, stre - s);
  1563. return stre;
  1564. }
  1565. break;
  1566. }
  1567. default:
  1568. break;
  1569. }
  1570. return stre;
  1571. }
  1572. // Parser utilities
  1573. #define PUGI__ENDSWITH(c, e) ((c) == (e) || ((c) == 0 && endch == (e)))
  1574. #define PUGI__SKIPWS() { while (PUGI__IS_CHARTYPE(*s, ct_space)) ++s; }
  1575. #define PUGI__OPTSET(OPT) ( optmsk & (OPT) )
  1576. #define PUGI__PUSHNODE(TYPE) { cursor = append_new_node(cursor, alloc, TYPE); if (!cursor) PUGI__THROW_ERROR(status_out_of_memory, s); }
  1577. #define PUGI__POPNODE() { cursor = cursor->parent; }
  1578. #define PUGI__SCANFOR(X) { while (*s != 0 && !(X)) ++s; }
  1579. #define PUGI__SCANWHILE(X) { while (X) ++s; }
  1580. #define PUGI__SCANWHILE_UNROLL(X) { for (;;) { char_t ss = s[0]; if (PUGI__UNLIKELY(!(X))) { break; } ss = s[1]; if (PUGI__UNLIKELY(!(X))) { s += 1; break; } ss = s[2]; if (PUGI__UNLIKELY(!(X))) { s += 2; break; } ss = s[3]; if (PUGI__UNLIKELY(!(X))) { s += 3; break; } s += 4; } }
  1581. #define PUGI__ENDSEG() { ch = *s; *s = 0; ++s; }
  1582. #define PUGI__THROW_ERROR(err, m) return error_offset = m, error_status = err, static_cast<char_t*>(0)
  1583. #define PUGI__CHECK_ERROR(err, m) { if (*s == 0) PUGI__THROW_ERROR(err, m); }
  1584. PUGI__FN char_t* strconv_comment(char_t* s, char_t endch)
  1585. {
  1586. gap g;
  1587. while (true)
  1588. {
  1589. PUGI__SCANWHILE_UNROLL(!PUGI__IS_CHARTYPE(ss, ct_parse_comment));
  1590. if (*s == '\r') // Either a single 0x0d or 0x0d 0x0a pair
  1591. {
  1592. *s++ = '\n'; // replace first one with 0x0a
  1593. if (*s == '\n') g.push(s, 1);
  1594. }
  1595. else if (s[0] == '-' && s[1] == '-' && PUGI__ENDSWITH(s[2], '>')) // comment ends here
  1596. {
  1597. *g.flush(s) = 0;
  1598. return s + (s[2] == '>' ? 3 : 2);
  1599. }
  1600. else if (*s == 0)
  1601. {
  1602. return 0;
  1603. }
  1604. else ++s;
  1605. }
  1606. }
  1607. PUGI__FN char_t* strconv_cdata(char_t* s, char_t endch)
  1608. {
  1609. gap g;
  1610. while (true)
  1611. {
  1612. PUGI__SCANWHILE_UNROLL(!PUGI__IS_CHARTYPE(ss, ct_parse_cdata));
  1613. if (*s == '\r') // Either a single 0x0d or 0x0d 0x0a pair
  1614. {
  1615. *s++ = '\n'; // replace first one with 0x0a
  1616. if (*s == '\n') g.push(s, 1);
  1617. }
  1618. else if (s[0] == ']' && s[1] == ']' && PUGI__ENDSWITH(s[2], '>')) // CDATA ends here
  1619. {
  1620. *g.flush(s) = 0;
  1621. return s + 1;
  1622. }
  1623. else if (*s == 0)
  1624. {
  1625. return 0;
  1626. }
  1627. else ++s;
  1628. }
  1629. }
  1630. typedef char_t* (*strconv_pcdata_t)(char_t*);
  1631. template <typename opt_trim, typename opt_eol, typename opt_escape> struct strconv_pcdata_impl
  1632. {
  1633. static char_t* parse(char_t* s)
  1634. {
  1635. gap g;
  1636. char_t* begin = s;
  1637. while (true)
  1638. {
  1639. PUGI__SCANWHILE_UNROLL(!PUGI__IS_CHARTYPE(ss, ct_parse_pcdata));
  1640. if (*s == '<') // PCDATA ends here
  1641. {
  1642. char_t* end = g.flush(s);
  1643. if (opt_trim::value)
  1644. while (end > begin && PUGI__IS_CHARTYPE(end[-1], ct_space))
  1645. --end;
  1646. *end = 0;
  1647. return s + 1;
  1648. }
  1649. else if (opt_eol::value && *s == '\r') // Either a single 0x0d or 0x0d 0x0a pair
  1650. {
  1651. *s++ = '\n'; // replace first one with 0x0a
  1652. if (*s == '\n') g.push(s, 1);
  1653. }
  1654. else if (opt_escape::value && *s == '&')
  1655. {
  1656. s = strconv_escape(s, g);
  1657. }
  1658. else if (*s == 0)
  1659. {
  1660. char_t* end = g.flush(s);
  1661. if (opt_trim::value)
  1662. while (end > begin && PUGI__IS_CHARTYPE(end[-1], ct_space))
  1663. --end;
  1664. *end = 0;
  1665. return s;
  1666. }
  1667. else ++s;
  1668. }
  1669. }
  1670. };
  1671. PUGI__FN strconv_pcdata_t get_strconv_pcdata(unsigned int optmask)
  1672. {
  1673. PUGI__STATIC_ASSERT(parse_escapes == 0x10 && parse_eol == 0x20 && parse_trim_pcdata == 0x0800);
  1674. switch (((optmask >> 4) & 3) | ((optmask >> 9) & 4)) // get bitmask for flags (eol escapes trim)
  1675. {
  1676. case 0: return strconv_pcdata_impl<opt_false, opt_false, opt_false>::parse;
  1677. case 1: return strconv_pcdata_impl<opt_false, opt_false, opt_true>::parse;
  1678. case 2: return strconv_pcdata_impl<opt_false, opt_true, opt_false>::parse;
  1679. case 3: return strconv_pcdata_impl<opt_false, opt_true, opt_true>::parse;
  1680. case 4: return strconv_pcdata_impl<opt_true, opt_false, opt_false>::parse;
  1681. case 5: return strconv_pcdata_impl<opt_true, opt_false, opt_true>::parse;
  1682. case 6: return strconv_pcdata_impl<opt_true, opt_true, opt_false>::parse;
  1683. case 7: return strconv_pcdata_impl<opt_true, opt_true, opt_true>::parse;
  1684. default: assert(false); return 0; // should not get here
  1685. }
  1686. }
  1687. typedef char_t* (*strconv_attribute_t)(char_t*, char_t);
  1688. template <typename opt_escape> struct strconv_attribute_impl
  1689. {
  1690. static char_t* parse_wnorm(char_t* s, char_t end_quote)
  1691. {
  1692. gap g;
  1693. // trim leading whitespaces
  1694. if (PUGI__IS_CHARTYPE(*s, ct_space))
  1695. {
  1696. char_t* str = s;
  1697. do ++str;
  1698. while (PUGI__IS_CHARTYPE(*str, ct_space));
  1699. g.push(s, str - s);
  1700. }
  1701. while (true)
  1702. {
  1703. PUGI__SCANWHILE_UNROLL(!PUGI__IS_CHARTYPE(ss, ct_parse_attr_ws | ct_space));
  1704. if (*s == end_quote)
  1705. {
  1706. char_t* str = g.flush(s);
  1707. do *str-- = 0;
  1708. while (PUGI__IS_CHARTYPE(*str, ct_space));
  1709. return s + 1;
  1710. }
  1711. else if (PUGI__IS_CHARTYPE(*s, ct_space))
  1712. {
  1713. *s++ = ' ';
  1714. if (PUGI__IS_CHARTYPE(*s, ct_space))
  1715. {
  1716. char_t* str = s + 1;
  1717. while (PUGI__IS_CHARTYPE(*str, ct_space)) ++str;
  1718. g.push(s, str - s);
  1719. }
  1720. }
  1721. else if (opt_escape::value && *s == '&')
  1722. {
  1723. s = strconv_escape(s, g);
  1724. }
  1725. else if (!*s)
  1726. {
  1727. return 0;
  1728. }
  1729. else ++s;
  1730. }
  1731. }
  1732. static char_t* parse_wconv(char_t* s, char_t end_quote)
  1733. {
  1734. gap g;
  1735. while (true)
  1736. {
  1737. PUGI__SCANWHILE_UNROLL(!PUGI__IS_CHARTYPE(ss, ct_parse_attr_ws));
  1738. if (*s == end_quote)
  1739. {
  1740. *g.flush(s) = 0;
  1741. return s + 1;
  1742. }
  1743. else if (PUGI__IS_CHARTYPE(*s, ct_space))
  1744. {
  1745. if (*s == '\r')
  1746. {
  1747. *s++ = ' ';
  1748. if (*s == '\n') g.push(s, 1);
  1749. }
  1750. else *s++ = ' ';
  1751. }
  1752. else if (opt_escape::value && *s == '&')
  1753. {
  1754. s = strconv_escape(s, g);
  1755. }
  1756. else if (!*s)
  1757. {
  1758. return 0;
  1759. }
  1760. else ++s;
  1761. }
  1762. }
  1763. static char_t* parse_eol(char_t* s, char_t end_quote)
  1764. {
  1765. gap g;
  1766. while (true)
  1767. {
  1768. PUGI__SCANWHILE_UNROLL(!PUGI__IS_CHARTYPE(ss, ct_parse_attr));
  1769. if (*s == end_quote)
  1770. {
  1771. *g.flush(s) = 0;
  1772. return s + 1;
  1773. }
  1774. else if (*s == '\r')
  1775. {
  1776. *s++ = '\n';
  1777. if (*s == '\n') g.push(s, 1);
  1778. }
  1779. else if (opt_escape::value && *s == '&')
  1780. {
  1781. s = strconv_escape(s, g);
  1782. }
  1783. else if (!*s)
  1784. {
  1785. return 0;
  1786. }
  1787. else ++s;
  1788. }
  1789. }
  1790. static char_t* parse_simple(char_t* s, char_t end_quote)
  1791. {
  1792. gap g;
  1793. while (true)
  1794. {
  1795. PUGI__SCANWHILE_UNROLL(!PUGI__IS_CHARTYPE(ss, ct_parse_attr));
  1796. if (*s == end_quote)
  1797. {
  1798. *g.flush(s) = 0;
  1799. return s + 1;
  1800. }
  1801. else if (opt_escape::value && *s == '&')
  1802. {
  1803. s = strconv_escape(s, g);
  1804. }
  1805. else if (!*s)
  1806. {
  1807. return 0;
  1808. }
  1809. else ++s;
  1810. }
  1811. }
  1812. };
  1813. PUGI__FN strconv_attribute_t get_strconv_attribute(unsigned int optmask)
  1814. {
  1815. PUGI__STATIC_ASSERT(parse_escapes == 0x10 && parse_eol == 0x20 && parse_wconv_attribute == 0x40 && parse_wnorm_attribute == 0x80);
  1816. switch ((optmask >> 4) & 15) // get bitmask for flags (wconv wnorm eol escapes)
  1817. {
  1818. case 0: return strconv_attribute_impl<opt_false>::parse_simple;
  1819. case 1: return strconv_attribute_impl<opt_true>::parse_simple;
  1820. case 2: return strconv_attribute_impl<opt_false>::parse_eol;
  1821. case 3: return strconv_attribute_impl<opt_true>::parse_eol;
  1822. case 4: return strconv_attribute_impl<opt_false>::parse_wconv;
  1823. case 5: return strconv_attribute_impl<opt_true>::parse_wconv;
  1824. case 6: return strconv_attribute_impl<opt_false>::parse_wconv;
  1825. case 7: return strconv_attribute_impl<opt_true>::parse_wconv;
  1826. case 8: return strconv_attribute_impl<opt_false>::parse_wnorm;
  1827. case 9: return strconv_attribute_impl<opt_true>::parse_wnorm;
  1828. case 10: return strconv_attribute_impl<opt_false>::parse_wnorm;
  1829. case 11: return strconv_attribute_impl<opt_true>::parse_wnorm;
  1830. case 12: return strconv_attribute_impl<opt_false>::parse_wnorm;
  1831. case 13: return strconv_attribute_impl<opt_true>::parse_wnorm;
  1832. case 14: return strconv_attribute_impl<opt_false>::parse_wnorm;
  1833. case 15: return strconv_attribute_impl<opt_true>::parse_wnorm;
  1834. default: assert(false); return 0; // should not get here
  1835. }
  1836. }
  1837. inline xml_parse_result make_parse_result(xml_parse_status status, ptrdiff_t offset = 0)
  1838. {
  1839. xml_parse_result result;
  1840. result.status = status;
  1841. result.offset = offset;
  1842. return result;
  1843. }
  1844. struct xml_parser
  1845. {
  1846. xml_allocator alloc;
  1847. char_t* error_offset;
  1848. xml_parse_status error_status;
  1849. xml_parser(const xml_allocator& alloc_): alloc(alloc_), error_offset(0), error_status(status_ok)
  1850. {
  1851. }
  1852. // DOCTYPE consists of nested sections of the following possible types:
  1853. // <!-- ... -->, <? ... ?>, "...", '...'
  1854. // <![...]]>
  1855. // <!...>
  1856. // First group can not contain nested groups
  1857. // Second group can contain nested groups of the same type
  1858. // Third group can contain all other groups
  1859. char_t* parse_doctype_primitive(char_t* s)
  1860. {
  1861. if (*s == '"' || *s == '\'')
  1862. {
  1863. // quoted string
  1864. char_t ch = *s++;
  1865. PUGI__SCANFOR(*s == ch);
  1866. if (!*s) PUGI__THROW_ERROR(status_bad_doctype, s);
  1867. s++;
  1868. }
  1869. else if (s[0] == '<' && s[1] == '?')
  1870. {
  1871. // <? ... ?>
  1872. s += 2;
  1873. PUGI__SCANFOR(s[0] == '?' && s[1] == '>'); // no need for ENDSWITH because ?> can't terminate proper doctype
  1874. if (!*s) PUGI__THROW_ERROR(status_bad_doctype, s);
  1875. s += 2;
  1876. }
  1877. else if (s[0] == '<' && s[1] == '!' && s[2] == '-' && s[3] == '-')
  1878. {
  1879. s += 4;
  1880. PUGI__SCANFOR(s[0] == '-' && s[1] == '-' && s[2] == '>'); // no need for ENDSWITH because --> can't terminate proper doctype
  1881. if (!*s) PUGI__THROW_ERROR(status_bad_doctype, s);
  1882. s += 4;
  1883. }
  1884. else PUGI__THROW_ERROR(status_bad_doctype, s);
  1885. return s;
  1886. }
  1887. char_t* parse_doctype_ignore(char_t* s)
  1888. {
  1889. assert(s[0] == '<' && s[1] == '!' && s[2] == '[');
  1890. s++;
  1891. while (*s)
  1892. {
  1893. if (s[0] == '<' && s[1] == '!' && s[2] == '[')
  1894. {
  1895. // nested ignore section
  1896. s = parse_doctype_ignore(s);
  1897. if (!s) return s;
  1898. }
  1899. else if (s[0] == ']' && s[1] == ']' && s[2] == '>')
  1900. {
  1901. // ignore section end
  1902. s += 3;
  1903. return s;
  1904. }
  1905. else s++;
  1906. }
  1907. PUGI__THROW_ERROR(status_bad_doctype, s);
  1908. }
  1909. char_t* parse_doctype_group(char_t* s, char_t endch, bool toplevel)
  1910. {
  1911. assert((s[0] == '<' || s[0] == 0) && s[1] == '!');
  1912. s++;
  1913. while (*s)
  1914. {
  1915. if (s[0] == '<' && s[1] == '!' && s[2] != '-')
  1916. {
  1917. if (s[2] == '[')
  1918. {
  1919. // ignore
  1920. s = parse_doctype_ignore(s);
  1921. if (!s) return s;
  1922. }
  1923. else
  1924. {
  1925. // some control group
  1926. s = parse_doctype_group(s, endch, false);
  1927. if (!s) return s;
  1928. // skip >
  1929. assert(*s == '>');
  1930. s++;
  1931. }
  1932. }
  1933. else if (s[0] == '<' || s[0] == '"' || s[0] == '\'')
  1934. {
  1935. // unknown tag (forbidden), or some primitive group
  1936. s = parse_doctype_primitive(s);
  1937. if (!s) return s;
  1938. }
  1939. else if (*s == '>')
  1940. {
  1941. return s;
  1942. }
  1943. else s++;
  1944. }
  1945. if (!toplevel || endch != '>') PUGI__THROW_ERROR(status_bad_doctype, s);
  1946. return s;
  1947. }
  1948. char_t* parse_exclamation(char_t* s, xml_node_struct* cursor, unsigned int optmsk, char_t endch)
  1949. {
  1950. // parse node contents, starting with exclamation mark
  1951. ++s;
  1952. if (*s == '-') // '<!-...'
  1953. {
  1954. ++s;
  1955. if (*s == '-') // '<!--...'
  1956. {
  1957. ++s;
  1958. if (PUGI__OPTSET(parse_comments))
  1959. {
  1960. PUGI__PUSHNODE(node_comment); // Append a new node on the tree.
  1961. cursor->value = s; // Save the offset.
  1962. }
  1963. if (PUGI__OPTSET(parse_eol) && PUGI__OPTSET(parse_comments))
  1964. {
  1965. s = strconv_comment(s, endch);
  1966. if (!s) PUGI__THROW_ERROR(status_bad_comment, cursor->value);
  1967. }
  1968. else
  1969. {
  1970. // Scan for terminating '-->'.
  1971. PUGI__SCANFOR(s[0] == '-' && s[1] == '-' && PUGI__ENDSWITH(s[2], '>'));
  1972. PUGI__CHECK_ERROR(status_bad_comment, s);
  1973. if (PUGI__OPTSET(parse_comments))
  1974. *s = 0; // Zero-terminate this segment at the first terminating '-'.
  1975. s += (s[2] == '>' ? 3 : 2); // Step over the '\0->'.
  1976. }
  1977. }
  1978. else PUGI__THROW_ERROR(status_bad_comment, s);
  1979. }
  1980. else if (*s == '[')
  1981. {
  1982. // '<![CDATA[...'
  1983. if (*++s=='C' && *++s=='D' && *++s=='A' && *++s=='T' && *++s=='A' && *++s == '[')
  1984. {
  1985. ++s;
  1986. if (PUGI__OPTSET(parse_cdata))
  1987. {
  1988. PUGI__PUSHNODE(node_cdata); // Append a new node on the tree.
  1989. cursor->value = s; // Save the offset.
  1990. if (PUGI__OPTSET(parse_eol))
  1991. {
  1992. s = strconv_cdata(s, endch);
  1993. if (!s) PUGI__THROW_ERROR(status_bad_cdata, cursor->value);
  1994. }
  1995. else
  1996. {
  1997. // Scan for terminating ']]>'.
  1998. PUGI__SCANFOR(s[0] == ']' && s[1] == ']' && PUGI__ENDSWITH(s[2], '>'));
  1999. PUGI__CHECK_ERROR(status_bad_cdata, s);
  2000. *s++ = 0; // Zero-terminate this segment.
  2001. }
  2002. }
  2003. else // Flagged for discard, but we still have to scan for the terminator.
  2004. {
  2005. // Scan for terminating ']]>'.
  2006. PUGI__SCANFOR(s[0] == ']' && s[1] == ']' && PUGI__ENDSWITH(s[2], '>'));
  2007. PUGI__CHECK_ERROR(status_bad_cdata, s);
  2008. ++s;
  2009. }
  2010. s += (s[1] == '>' ? 2 : 1); // Step over the last ']>'.
  2011. }
  2012. else PUGI__THROW_ERROR(status_bad_cdata, s);
  2013. }
  2014. else if (s[0] == 'D' && s[1] == 'O' && s[2] == 'C' && s[3] == 'T' && s[4] == 'Y' && s[5] == 'P' && PUGI__ENDSWITH(s[6], 'E'))
  2015. {
  2016. s -= 2;
  2017. if (cursor->parent) PUGI__THROW_ERROR(status_bad_doctype, s);
  2018. char_t* mark = s + 9;
  2019. s = parse_doctype_group(s, endch, true);
  2020. if (!s) return s;
  2021. assert((*s == 0 && endch == '>') || *s == '>');
  2022. if (*s) *s++ = 0;
  2023. if (PUGI__OPTSET(parse_doctype))
  2024. {
  2025. while (PUGI__IS_CHARTYPE(*mark, ct_space)) ++mark;
  2026. PUGI__PUSHNODE(node_doctype);
  2027. cursor->value = mark;
  2028. }
  2029. }
  2030. else if (*s == 0 && endch == '-') PUGI__THROW_ERROR(status_bad_comment, s);
  2031. else if (*s == 0 && endch == '[') PUGI__THROW_ERROR(status_bad_cdata, s);
  2032. else PUGI__THROW_ERROR(status_unrecognized_tag, s);
  2033. return s;
  2034. }
  2035. char_t* parse_question(char_t* s, xml_node_struct*& ref_cursor, unsigned int optmsk, char_t endch)
  2036. {
  2037. // load into registers
  2038. xml_node_struct* cursor = ref_cursor;
  2039. char_t ch = 0;
  2040. // parse node contents, starting with question mark
  2041. ++s;
  2042. // read PI target
  2043. char_t* target = s;
  2044. if (!PUGI__IS_CHARTYPE(*s, ct_start_symbol)) PUGI__THROW_ERROR(status_bad_pi, s);
  2045. PUGI__SCANWHILE(PUGI__IS_CHARTYPE(*s, ct_symbol));
  2046. PUGI__CHECK_ERROR(status_bad_pi, s);
  2047. // determine node type; stricmp / strcasecmp is not portable
  2048. bool declaration = (target[0] | ' ') == 'x' && (target[1] | ' ') == 'm' && (target[2] | ' ') == 'l' && target + 3 == s;
  2049. if (declaration ? PUGI__OPTSET(parse_declaration) : PUGI__OPTSET(parse_pi))
  2050. {
  2051. if (declaration)
  2052. {
  2053. // disallow non top-level declarations
  2054. if (cursor->parent) PUGI__THROW_ERROR(status_bad_pi, s);
  2055. PUGI__PUSHNODE(node_declaration);
  2056. }
  2057. else
  2058. {
  2059. PUGI__PUSHNODE(node_pi);
  2060. }
  2061. cursor->name = target;
  2062. PUGI__ENDSEG();
  2063. // parse value/attributes
  2064. if (ch == '?')
  2065. {
  2066. // empty node
  2067. if (!PUGI__ENDSWITH(*s, '>')) PUGI__THROW_ERROR(status_bad_pi, s);
  2068. s += (*s == '>');
  2069. PUGI__POPNODE();
  2070. }
  2071. else if (PUGI__IS_CHARTYPE(ch, ct_space))
  2072. {
  2073. PUGI__SKIPWS();
  2074. // scan for tag end
  2075. char_t* value = s;
  2076. PUGI__SCANFOR(s[0] == '?' && PUGI__ENDSWITH(s[1], '>'));
  2077. PUGI__CHECK_ERROR(status_bad_pi, s);
  2078. if (declaration)
  2079. {
  2080. // replace ending ? with / so that 'element' terminates properly
  2081. *s = '/';
  2082. // we exit from this function with cursor at node_declaration, which is a signal to parse() to go to LOC_ATTRIBUTES
  2083. s = value;
  2084. }
  2085. else
  2086. {
  2087. // store value and step over >
  2088. cursor->value = value;
  2089. PUGI__POPNODE();
  2090. PUGI__ENDSEG();
  2091. s += (*s == '>');
  2092. }
  2093. }
  2094. else PUGI__THROW_ERROR(status_bad_pi, s);
  2095. }
  2096. else
  2097. {
  2098. // scan for tag end
  2099. PUGI__SCANFOR(s[0] == '?' && PUGI__ENDSWITH(s[1], '>'));
  2100. PUGI__CHECK_ERROR(status_bad_pi, s);
  2101. s += (s[1] == '>' ? 2 : 1);
  2102. }
  2103. // store from registers
  2104. ref_cursor = cursor;
  2105. return s;
  2106. }
  2107. char_t* parse_tree(char_t* s, xml_node_struct* root, unsigned int optmsk, char_t endch)
  2108. {
  2109. strconv_attribute_t strconv_attribute = get_strconv_attribute(optmsk);
  2110. strconv_pcdata_t strconv_pcdata = get_strconv_pcdata(optmsk);
  2111. char_t ch = 0;
  2112. xml_node_struct* cursor = root;
  2113. char_t* mark = s;
  2114. while (*s != 0)
  2115. {
  2116. if (*s == '<')
  2117. {
  2118. ++s;
  2119. LOC_TAG:
  2120. if (PUGI__IS_CHARTYPE(*s, ct_start_symbol)) // '<#...'
  2121. {
  2122. PUGI__PUSHNODE(node_element); // Append a new node to the tree.
  2123. cursor->name = s;
  2124. PUGI__SCANWHILE_UNROLL(PUGI__IS_CHARTYPE(ss, ct_symbol)); // Scan for a terminator.
  2125. PUGI__ENDSEG(); // Save char in 'ch', terminate & step over.
  2126. if (ch == '>')
  2127. {
  2128. // end of tag
  2129. }
  2130. else if (PUGI__IS_CHARTYPE(ch, ct_space))
  2131. {
  2132. LOC_ATTRIBUTES:
  2133. while (true)
  2134. {
  2135. PUGI__SKIPWS(); // Eat any whitespace.
  2136. if (PUGI__IS_CHARTYPE(*s, ct_start_symbol)) // <... #...
  2137. {
  2138. xml_attribute_struct* a = append_new_attribute(cursor, alloc); // Make space for this attribute.
  2139. if (!a) PUGI__THROW_ERROR(status_out_of_memory, s);
  2140. a->name = s; // Save the offset.
  2141. PUGI__SCANWHILE_UNROLL(PUGI__IS_CHARTYPE(ss, ct_symbol)); // Scan for a terminator.
  2142. PUGI__ENDSEG(); // Save char in 'ch', terminate & step over.
  2143. if (PUGI__IS_CHARTYPE(ch, ct_space))
  2144. {
  2145. PUGI__SKIPWS(); // Eat any whitespace.
  2146. ch = *s;
  2147. ++s;
  2148. }
  2149. if (ch == '=') // '<... #=...'
  2150. {
  2151. PUGI__SKIPWS(); // Eat any whitespace.
  2152. if (*s == '"' || *s == '\'') // '<... #="...'
  2153. {
  2154. ch = *s; // Save quote char to avoid breaking on "''" -or- '""'.
  2155. ++s; // Step over the quote.
  2156. a->value = s; // Save the offset.
  2157. s = strconv_attribute(s, ch);
  2158. if (!s) PUGI__THROW_ERROR(status_bad_attribute, a->value);
  2159. // After this line the loop continues from the start;
  2160. // Whitespaces, / and > are ok, symbols and EOF are wrong,
  2161. // everything else will be detected
  2162. if (PUGI__IS_CHARTYPE(*s, ct_start_symbol)) PUGI__THROW_ERROR(status_bad_attribute, s);
  2163. }
  2164. else PUGI__THROW_ERROR(status_bad_attribute, s);
  2165. }
  2166. else PUGI__THROW_ERROR(status_bad_attribute, s);
  2167. }
  2168. else if (*s == '/')
  2169. {
  2170. ++s;
  2171. if (*s == '>')
  2172. {
  2173. PUGI__POPNODE();
  2174. s++;
  2175. break;
  2176. }
  2177. else if (*s == 0 && endch == '>')
  2178. {
  2179. PUGI__POPNODE();
  2180. break;
  2181. }
  2182. else PUGI__THROW_ERROR(status_bad_start_element, s);
  2183. }
  2184. else if (*s == '>')
  2185. {
  2186. ++s;
  2187. break;
  2188. }
  2189. else if (*s == 0 && endch == '>')
  2190. {
  2191. break;
  2192. }
  2193. else PUGI__THROW_ERROR(status_bad_start_element, s);
  2194. }
  2195. // !!!
  2196. }
  2197. else if (ch == '/') // '<#.../'
  2198. {
  2199. if (!PUGI__ENDSWITH(*s, '>')) PUGI__THROW_ERROR(status_bad_start_element, s);
  2200. PUGI__POPNODE(); // Pop.
  2201. s += (*s == '>');
  2202. }
  2203. else if (ch == 0)
  2204. {
  2205. // we stepped over null terminator, backtrack & handle closing tag
  2206. --s;
  2207. if (endch != '>') PUGI__THROW_ERROR(status_bad_start_element, s);
  2208. }
  2209. else PUGI__THROW_ERROR(status_bad_start_element, s);
  2210. }
  2211. else if (*s == '/')
  2212. {
  2213. ++s;
  2214. char_t* name = cursor->name;
  2215. if (!name) PUGI__THROW_ERROR(status_end_element_mismatch, s);
  2216. while (PUGI__IS_CHARTYPE(*s, ct_symbol))
  2217. {
  2218. if (*s++ != *name++) PUGI__THROW_ERROR(status_end_element_mismatch, s);
  2219. }
  2220. if (*name)
  2221. {
  2222. if (*s == 0 && name[0] == endch && name[1] == 0) PUGI__THROW_ERROR(status_bad_end_element, s);
  2223. else PUGI__THROW_ERROR(status_end_element_mismatch, s);
  2224. }
  2225. PUGI__POPNODE(); // Pop.
  2226. PUGI__SKIPWS();
  2227. if (*s == 0)
  2228. {
  2229. if (endch != '>') PUGI__THROW_ERROR(status_bad_end_element, s);
  2230. }
  2231. else
  2232. {
  2233. if (*s != '>') PUGI__THROW_ERROR(status_bad_end_element, s);
  2234. ++s;
  2235. }
  2236. }
  2237. else if (*s == '?') // '<?...'
  2238. {
  2239. s = parse_question(s, cursor, optmsk, endch);
  2240. if (!s) return s;
  2241. assert(cursor);
  2242. if (PUGI__NODETYPE(cursor) == node_declaration) goto LOC_ATTRIBUTES;
  2243. }
  2244. else if (*s == '!') // '<!...'
  2245. {
  2246. s = parse_exclamation(s, cursor, optmsk, endch);
  2247. if (!s) return s;
  2248. }
  2249. else if (*s == 0 && endch == '?') PUGI__THROW_ERROR(status_bad_pi, s);
  2250. else PUGI__THROW_ERROR(status_unrecognized_tag, s);
  2251. }
  2252. else
  2253. {
  2254. mark = s; // Save this offset while searching for a terminator.
  2255. PUGI__SKIPWS(); // Eat whitespace if no genuine PCDATA here.
  2256. if (*s == '<' || !*s)
  2257. {
  2258. // We skipped some whitespace characters because otherwise we would take the tag branch instead of PCDATA one
  2259. assert(mark != s);
  2260. if (!PUGI__OPTSET(parse_ws_pcdata | parse_ws_pcdata_single) || PUGI__OPTSET(parse_trim_pcdata))
  2261. {
  2262. continue;
  2263. }
  2264. else if (PUGI__OPTSET(parse_ws_pcdata_single))
  2265. {
  2266. if (s[0] != '<' || s[1] != '/' || cursor->first_child) continue;
  2267. }
  2268. }
  2269. if (!PUGI__OPTSET(parse_trim_pcdata))
  2270. s = mark;
  2271. if (cursor->parent || PUGI__OPTSET(parse_fragment))
  2272. {
  2273. PUGI__PUSHNODE(node_pcdata); // Append a new node on the tree.
  2274. cursor->value = s; // Save the offset.
  2275. s = strconv_pcdata(s);
  2276. PUGI__POPNODE(); // Pop since this is a standalone.
  2277. if (!*s) break;
  2278. }
  2279. else
  2280. {
  2281. PUGI__SCANFOR(*s == '<'); // '...<'
  2282. if (!*s) break;
  2283. ++s;
  2284. }
  2285. // We're after '<'
  2286. goto LOC_TAG;
  2287. }
  2288. }
  2289. // check that last tag is closed
  2290. if (cursor != root) PUGI__THROW_ERROR(status_end_element_mismatch, s);
  2291. return s;
  2292. }
  2293. #ifdef PUGIXML_WCHAR_MODE
  2294. static char_t* parse_skip_bom(char_t* s)
  2295. {
  2296. unsigned int bom = 0xfeff;
  2297. return (s[0] == static_cast<wchar_t>(bom)) ? s + 1 : s;
  2298. }
  2299. #else
  2300. static char_t* parse_skip_bom(char_t* s)
  2301. {
  2302. return (s[0] == '\xef' && s[1] == '\xbb' && s[2] == '\xbf') ? s + 3 : s;
  2303. }
  2304. #endif
  2305. static bool has_element_node_siblings(xml_node_struct* node)
  2306. {
  2307. while (node)
  2308. {
  2309. if (PUGI__NODETYPE(node) == node_element) return true;
  2310. node = node->next_sibling;
  2311. }
  2312. return false;
  2313. }
  2314. static xml_parse_result parse(char_t* buffer, size_t length, xml_document_struct* xmldoc, xml_node_struct* root, unsigned int optmsk)
  2315. {
  2316. // allocator object is a part of document object
  2317. xml_allocator& alloc_ = *static_cast<xml_allocator*>(xmldoc);
  2318. // early-out for empty documents
  2319. if (length == 0)
  2320. return make_parse_result(PUGI__OPTSET(parse_fragment) ? status_ok : status_no_document_element);
  2321. // get last child of the root before parsing
  2322. xml_node_struct* last_root_child = root->first_child ? root->first_child->prev_sibling_c : 0;
  2323. // create parser on stack
  2324. xml_parser parser(alloc_);
  2325. // save last character and make buffer zero-terminated (speeds up parsing)
  2326. char_t endch = buffer[length - 1];
  2327. buffer[length - 1] = 0;
  2328. // skip BOM to make sure it does not end up as part of parse output
  2329. char_t* buffer_data = parse_skip_bom(buffer);
  2330. // perform actual parsing
  2331. parser.parse_tree(buffer_data, root, optmsk, endch);
  2332. // update allocator state
  2333. alloc_ = parser.alloc;
  2334. xml_parse_result result = make_parse_result(parser.error_status, parser.error_offset ? parser.error_offset - buffer : 0);
  2335. assert(result.offset >= 0 && static_cast<size_t>(result.offset) <= length);
  2336. if (result)
  2337. {
  2338. // since we removed last character, we have to handle the only possible false positive (stray <)
  2339. if (endch == '<')
  2340. return make_parse_result(status_unrecognized_tag, length - 1);
  2341. // check if there are any element nodes parsed
  2342. xml_node_struct* first_root_child_parsed = last_root_child ? last_root_child->next_sibling : root->first_child;
  2343. if (!PUGI__OPTSET(parse_fragment) && !has_element_node_siblings(first_root_child_parsed))
  2344. return make_parse_result(status_no_document_element, length - 1);
  2345. }
  2346. else
  2347. {
  2348. // roll back offset if it occurs on a null terminator in the source buffer
  2349. if (result.offset > 0 && static_cast<size_t>(result.offset) == length - 1 && endch == 0)
  2350. result.offset--;
  2351. }
  2352. return result;
  2353. }
  2354. };
  2355. // Output facilities
  2356. PUGI__FN xml_encoding get_write_native_encoding()
  2357. {
  2358. #ifdef PUGIXML_WCHAR_MODE
  2359. return get_wchar_encoding();
  2360. #else
  2361. return encoding_utf8;
  2362. #endif
  2363. }
  2364. PUGI__FN xml_encoding get_write_encoding(xml_encoding encoding)
  2365. {
  2366. // replace wchar encoding with utf implementation
  2367. if (encoding == encoding_wchar) return get_wchar_encoding();
  2368. // replace utf16 encoding with utf16 with specific endianness
  2369. if (encoding == encoding_utf16) return is_little_endian() ? encoding_utf16_le : encoding_utf16_be;
  2370. // replace utf32 encoding with utf32 with specific endianness
  2371. if (encoding == encoding_utf32) return is_little_endian() ? encoding_utf32_le : encoding_utf32_be;
  2372. // only do autodetection if no explicit encoding is requested
  2373. if (encoding != encoding_auto) return encoding;
  2374. // assume utf8 encoding
  2375. return encoding_utf8;
  2376. }
  2377. #ifdef PUGIXML_WCHAR_MODE
  2378. PUGI__FN size_t get_valid_length(const char_t* data, size_t length)
  2379. {
  2380. if (length < 1) return 0;
  2381. // discard last character if it's the lead of a surrogate pair
  2382. return (sizeof(wchar_t) == 2 && static_cast<unsigned int>(static_cast<uint16_t>(data[length - 1]) - 0xD800) < 0x400) ? length - 1 : length;
  2383. }
  2384. PUGI__FN size_t convert_buffer_output(char_t* r_char, uint8_t* r_u8, uint16_t* r_u16, uint32_t* r_u32, const char_t* data, size_t length, xml_encoding encoding)
  2385. {
  2386. // only endian-swapping is required
  2387. if (need_endian_swap_utf(encoding, get_wchar_encoding()))
  2388. {
  2389. convert_wchar_endian_swap(r_char, data, length);
  2390. return length * sizeof(char_t);
  2391. }
  2392. // convert to utf8
  2393. if (encoding == encoding_utf8)
  2394. {
  2395. uint8_t* dest = r_u8;
  2396. uint8_t* end = utf_decoder<utf8_writer>::decode_wchar_block(data, length, dest);
  2397. return static_cast<size_t>(end - dest);
  2398. }
  2399. // convert to utf16
  2400. if (encoding == encoding_utf16_be || encoding == encoding_utf16_le)
  2401. {
  2402. uint16_t* dest = r_u16;
  2403. // convert to native utf16
  2404. uint16_t* end = utf_decoder<utf16_writer>::decode_wchar_block(data, length, dest);
  2405. // swap if necessary
  2406. xml_encoding native_encoding = is_little_endian() ? encoding_utf16_le : encoding_utf16_be;
  2407. if (native_encoding != encoding) convert_utf_endian_swap(dest, dest, static_cast<size_t>(end - dest));
  2408. return static_cast<size_t>(end - dest) * sizeof(uint16_t);
  2409. }
  2410. // convert to utf32
  2411. if (encoding == encoding_utf32_be || encoding == encoding_utf32_le)
  2412. {
  2413. uint32_t* dest = r_u32;
  2414. // convert to native utf32
  2415. uint32_t* end = utf_decoder<utf32_writer>::decode_wchar_block(data, length, dest);
  2416. // swap if necessary
  2417. xml_encoding native_encoding = is_little_endian() ? encoding_utf32_le : encoding_utf32_be;
  2418. if (native_encoding != encoding) convert_utf_endian_swap(dest, dest, static_cast<size_t>(end - dest));
  2419. return static_cast<size_t>(end - dest) * sizeof(uint32_t);
  2420. }
  2421. // convert to latin1
  2422. if (encoding == encoding_latin1)
  2423. {
  2424. uint8_t* dest = r_u8;
  2425. uint8_t* end = utf_decoder<latin1_writer>::decode_wchar_block(data, length, dest);
  2426. return static_cast<size_t>(end - dest);
  2427. }
  2428. assert(!"Invalid encoding");
  2429. return 0;
  2430. }
  2431. #else
  2432. PUGI__FN size_t get_valid_length(const char_t* data, size_t length)
  2433. {
  2434. if (length < 5) return 0;
  2435. for (size_t i = 1; i <= 4; ++i)
  2436. {
  2437. uint8_t ch = static_cast<uint8_t>(data[length - i]);
  2438. // either a standalone character or a leading one
  2439. if ((ch & 0xc0) != 0x80) return length - i;
  2440. }
  2441. // there are four non-leading characters at the end, sequence tail is broken so might as well process the whole chunk
  2442. return length;
  2443. }
  2444. PUGI__FN size_t convert_buffer_output(char_t* /* r_char */, uint8_t* r_u8, uint16_t* r_u16, uint32_t* r_u32, const char_t* data, size_t length, xml_encoding encoding)
  2445. {
  2446. if (encoding == encoding_utf16_be || encoding == encoding_utf16_le)
  2447. {
  2448. uint16_t* dest = r_u16;
  2449. // convert to native utf16
  2450. uint16_t* end = utf_decoder<utf16_writer>::decode_utf8_block(reinterpret_cast<const uint8_t*>(data), length, dest);
  2451. // swap if necessary
  2452. xml_encoding native_encoding = is_little_endian() ? encoding_utf16_le : encoding_utf16_be;
  2453. if (native_encoding != encoding) convert_utf_endian_swap(dest, dest, static_cast<size_t>(end - dest));
  2454. return static_cast<size_t>(end - dest) * sizeof(uint16_t);
  2455. }
  2456. if (encoding == encoding_utf32_be || encoding == encoding_utf32_le)
  2457. {
  2458. uint32_t* dest = r_u32;
  2459. // convert to native utf32
  2460. uint32_t* end = utf_decoder<utf32_writer>::decode_utf8_block(reinterpret_cast<const uint8_t*>(data), length, dest);
  2461. // swap if necessary
  2462. xml_encoding native_encoding = is_little_endian() ? encoding_utf32_le : encoding_utf32_be;
  2463. if (native_encoding != encoding) convert_utf_endian_swap(dest, dest, static_cast<size_t>(end - dest));
  2464. return static_cast<size_t>(end - dest) * sizeof(uint32_t);
  2465. }
  2466. if (encoding == encoding_latin1)
  2467. {
  2468. uint8_t* dest = r_u8;
  2469. uint8_t* end = utf_decoder<latin1_writer>::decode_utf8_block(reinterpret_cast<const uint8_t*>(data), length, dest);
  2470. return static_cast<size_t>(end - dest);
  2471. }
  2472. assert(!"Invalid encoding");
  2473. return 0;
  2474. }
  2475. #endif
  2476. class xml_buffered_writer
  2477. {
  2478. xml_buffered_writer(const xml_buffered_writer&);
  2479. xml_buffered_writer& operator=(const xml_buffered_writer&);
  2480. public:
  2481. xml_buffered_writer(xml_writer& writer_, xml_encoding user_encoding): writer(writer_), bufsize(0), encoding(get_write_encoding(user_encoding))
  2482. {
  2483. PUGI__STATIC_ASSERT(bufcapacity >= 8);
  2484. }
  2485. ~xml_buffered_writer()
  2486. {
  2487. flush();
  2488. }
  2489. size_t flush()
  2490. {
  2491. flush(buffer, bufsize);
  2492. bufsize = 0;
  2493. return 0;
  2494. }
  2495. void flush(const char_t* data, size_t size)
  2496. {
  2497. if (size == 0) return;
  2498. // fast path, just write data
  2499. if (encoding == get_write_native_encoding())
  2500. writer.write(data, size * sizeof(char_t));
  2501. else
  2502. {
  2503. // convert chunk
  2504. size_t result = convert_buffer_output(scratch.data_char, scratch.data_u8, scratch.data_u16, scratch.data_u32, data, size, encoding);
  2505. assert(result <= sizeof(scratch));
  2506. // write data
  2507. writer.write(scratch.data_u8, result);
  2508. }
  2509. }
  2510. void write_direct(const char_t* data, size_t length)
  2511. {
  2512. // flush the remaining buffer contents
  2513. flush();
  2514. // handle large chunks
  2515. if (length > bufcapacity)
  2516. {
  2517. if (encoding == get_write_native_encoding())
  2518. {
  2519. // fast path, can just write data chunk
  2520. writer.write(data, length * sizeof(char_t));
  2521. return;
  2522. }
  2523. // need to convert in suitable chunks
  2524. while (length > bufcapacity)
  2525. {
  2526. // get chunk size by selecting such number of characters that are guaranteed to fit into scratch buffer
  2527. // and form a complete codepoint sequence (i.e. discard start of last codepoint if necessary)
  2528. size_t chunk_size = get_valid_length(data, bufcapacity);
  2529. assert(chunk_size);
  2530. // convert chunk and write
  2531. flush(data, chunk_size);
  2532. // iterate
  2533. data += chunk_size;
  2534. length -= chunk_size;
  2535. }
  2536. // small tail is copied below
  2537. bufsize = 0;
  2538. }
  2539. memcpy(buffer + bufsize, data, length * sizeof(char_t));
  2540. bufsize += length;
  2541. }
  2542. void write_buffer(const char_t* data, size_t length)
  2543. {
  2544. size_t offset = bufsize;
  2545. if (offset + length <= bufcapacity)
  2546. {
  2547. memcpy(buffer + offset, data, length * sizeof(char_t));
  2548. bufsize = offset + length;
  2549. }
  2550. else
  2551. {
  2552. write_direct(data, length);
  2553. }
  2554. }
  2555. void write_string(const char_t* data)
  2556. {
  2557. // write the part of the string that fits in the buffer
  2558. size_t offset = bufsize;
  2559. while (*data && offset < bufcapacity)
  2560. buffer[offset++] = *data++;
  2561. // write the rest
  2562. if (offset < bufcapacity)
  2563. {
  2564. bufsize = offset;
  2565. }
  2566. else
  2567. {
  2568. // backtrack a bit if we have split the codepoint
  2569. size_t length = offset - bufsize;
  2570. size_t extra = length - get_valid_length(data - length, length);
  2571. bufsize = offset - extra;
  2572. write_direct(data - extra, strlength(data) + extra);
  2573. }
  2574. }
  2575. void write(char_t d0)
  2576. {
  2577. size_t offset = bufsize;
  2578. if (offset > bufcapacity - 1) offset = flush();
  2579. buffer[offset + 0] = d0;
  2580. bufsize = offset + 1;
  2581. }
  2582. void write(char_t d0, char_t d1)
  2583. {
  2584. size_t offset = bufsize;
  2585. if (offset > bufcapacity - 2) offset = flush();
  2586. buffer[offset + 0] = d0;
  2587. buffer[offset + 1] = d1;
  2588. bufsize = offset + 2;
  2589. }
  2590. void write(char_t d0, char_t d1, char_t d2)
  2591. {
  2592. size_t offset = bufsize;
  2593. if (offset > bufcapacity - 3) offset = flush();
  2594. buffer[offset + 0] = d0;
  2595. buffer[offset + 1] = d1;
  2596. buffer[offset + 2] = d2;
  2597. bufsize = offset + 3;
  2598. }
  2599. void write(char_t d0, char_t d1, char_t d2, char_t d3)
  2600. {
  2601. size_t offset = bufsize;
  2602. if (offset > bufcapacity - 4) offset = flush();
  2603. buffer[offset + 0] = d0;
  2604. buffer[offset + 1] = d1;
  2605. buffer[offset + 2] = d2;
  2606. buffer[offset + 3] = d3;
  2607. bufsize = offset + 4;
  2608. }
  2609. void write(char_t d0, char_t d1, char_t d2, char_t d3, char_t d4)
  2610. {
  2611. size_t offset = bufsize;
  2612. if (offset > bufcapacity - 5) offset = flush();
  2613. buffer[offset + 0] = d0;
  2614. buffer[offset + 1] = d1;
  2615. buffer[offset + 2] = d2;
  2616. buffer[offset + 3] = d3;
  2617. buffer[offset + 4] = d4;
  2618. bufsize = offset + 5;
  2619. }
  2620. void write(char_t d0, char_t d1, char_t d2, char_t d3, char_t d4, char_t d5)
  2621. {
  2622. size_t offset = bufsize;
  2623. if (offset > bufcapacity - 6) offset = flush();
  2624. buffer[offset + 0] = d0;
  2625. buffer[offset + 1] = d1;
  2626. buffer[offset + 2] = d2;
  2627. buffer[offset + 3] = d3;
  2628. buffer[offset + 4] = d4;
  2629. buffer[offset + 5] = d5;
  2630. bufsize = offset + 6;
  2631. }
  2632. // utf8 maximum expansion: x4 (-> utf32)
  2633. // utf16 maximum expansion: x2 (-> utf32)
  2634. // utf32 maximum expansion: x1
  2635. enum
  2636. {
  2637. bufcapacitybytes =
  2638. #ifdef PUGIXML_MEMORY_OUTPUT_STACK
  2639. PUGIXML_MEMORY_OUTPUT_STACK
  2640. #else
  2641. 10240
  2642. #endif
  2643. ,
  2644. bufcapacity = bufcapacitybytes / (sizeof(char_t) + 4)
  2645. };
  2646. char_t buffer[bufcapacity];
  2647. union
  2648. {
  2649. uint8_t data_u8[4 * bufcapacity];
  2650. uint16_t data_u16[2 * bufcapacity];
  2651. uint32_t data_u32[bufcapacity];
  2652. char_t data_char[bufcapacity];
  2653. } scratch;
  2654. xml_writer& writer;
  2655. size_t bufsize;
  2656. xml_encoding encoding;
  2657. };
  2658. PUGI__FN void text_output_escaped(xml_buffered_writer& writer, const char_t* s, chartypex_t type)
  2659. {
  2660. while (*s)
  2661. {
  2662. const char_t* prev = s;
  2663. // While *s is a usual symbol
  2664. PUGI__SCANWHILE_UNROLL(!PUGI__IS_CHARTYPEX(ss, type));
  2665. writer.write_buffer(prev, static_cast<size_t>(s - prev));
  2666. switch (*s)
  2667. {
  2668. case 0: break;
  2669. case '&':
  2670. writer.write('&', 'a', 'm', 'p', ';');
  2671. ++s;
  2672. break;
  2673. case '<':
  2674. writer.write('&', 'l', 't', ';');
  2675. ++s;
  2676. break;
  2677. case '>':
  2678. writer.write('&', 'g', 't', ';');
  2679. ++s;
  2680. break;
  2681. case '"':
  2682. writer.write('&', 'q', 'u', 'o', 't', ';');
  2683. ++s;
  2684. break;
  2685. default: // s is not a usual symbol
  2686. {
  2687. unsigned int ch = static_cast<unsigned int>(*s++);
  2688. assert(ch < 32);
  2689. writer.write('&', '#', static_cast<char_t>((ch / 10) + '0'), static_cast<char_t>((ch % 10) + '0'), ';');
  2690. }
  2691. }
  2692. }
  2693. }
  2694. PUGI__FN void text_output(xml_buffered_writer& writer, const char_t* s, chartypex_t type, unsigned int flags)
  2695. {
  2696. if (flags & format_no_escapes)
  2697. writer.write_string(s);
  2698. else
  2699. text_output_escaped(writer, s, type);
  2700. }
  2701. PUGI__FN void text_output_cdata(xml_buffered_writer& writer, const char_t* s)
  2702. {
  2703. do
  2704. {
  2705. writer.write('<', '!', '[', 'C', 'D');
  2706. writer.write('A', 'T', 'A', '[');
  2707. const char_t* prev = s;
  2708. // look for ]]> sequence - we can't output it as is since it terminates CDATA
  2709. while (*s && !(s[0] == ']' && s[1] == ']' && s[2] == '>')) ++s;
  2710. // skip ]] if we stopped at ]]>, > will go to the next CDATA section
  2711. if (*s) s += 2;
  2712. writer.write_buffer(prev, static_cast<size_t>(s - prev));
  2713. writer.write(']', ']', '>');
  2714. }
  2715. while (*s);
  2716. }
  2717. PUGI__FN void text_output_indent(xml_buffered_writer& writer, const char_t* indent, size_t indent_length, unsigned int depth)
  2718. {
  2719. switch (indent_length)
  2720. {
  2721. case 1:
  2722. {
  2723. for (unsigned int i = 0; i < depth; ++i)
  2724. writer.write(indent[0]);
  2725. break;
  2726. }
  2727. case 2:
  2728. {
  2729. for (unsigned int i = 0; i < depth; ++i)
  2730. writer.write(indent[0], indent[1]);
  2731. break;
  2732. }
  2733. case 3:
  2734. {
  2735. for (unsigned int i = 0; i < depth; ++i)
  2736. writer.write(indent[0], indent[1], indent[2]);
  2737. break;
  2738. }
  2739. case 4:
  2740. {
  2741. for (unsigned int i = 0; i < depth; ++i)
  2742. writer.write(indent[0], indent[1], indent[2], indent[3]);
  2743. break;
  2744. }
  2745. default:
  2746. {
  2747. for (unsigned int i = 0; i < depth; ++i)
  2748. writer.write_buffer(indent, indent_length);
  2749. }
  2750. }
  2751. }
  2752. PUGI__FN void node_output_comment(xml_buffered_writer& writer, const char_t* s)
  2753. {
  2754. writer.write('<', '!', '-', '-');
  2755. while (*s)
  2756. {
  2757. const char_t* prev = s;
  2758. // look for -\0 or -- sequence - we can't output it since -- is illegal in comment body
  2759. while (*s && !(s[0] == '-' && (s[1] == '-' || s[1] == 0))) ++s;
  2760. writer.write_buffer(prev, static_cast<size_t>(s - prev));
  2761. if (*s)
  2762. {
  2763. assert(*s == '-');
  2764. writer.write('-', ' ');
  2765. ++s;
  2766. }
  2767. }
  2768. writer.write('-', '-', '>');
  2769. }
  2770. PUGI__FN void node_output_attributes(xml_buffered_writer& writer, xml_node_struct* node, unsigned int flags)
  2771. {
  2772. const char_t* default_name = PUGIXML_TEXT(":anonymous");
  2773. for (xml_attribute_struct* a = node->first_attribute; a; a = a->next_attribute)
  2774. {
  2775. writer.write(' ');
  2776. writer.write_string(a->name ? a->name : default_name);
  2777. writer.write('=', '"');
  2778. if (a->value)
  2779. text_output(writer, a->value, ctx_special_attr, flags);
  2780. writer.write('"');
  2781. }
  2782. }
  2783. PUGI__FN bool node_output_start(xml_buffered_writer& writer, xml_node_struct* node, unsigned int flags)
  2784. {
  2785. const char_t* default_name = PUGIXML_TEXT(":anonymous");
  2786. const char_t* name = node->name ? node->name : default_name;
  2787. writer.write('<');
  2788. writer.write_string(name);
  2789. if (node->first_attribute)
  2790. node_output_attributes(writer, node, flags);
  2791. if (flags & format_raw)
  2792. {
  2793. if (!node->first_child)
  2794. writer.write(' ', '/', '>');
  2795. else
  2796. {
  2797. writer.write('>');
  2798. return true;
  2799. }
  2800. }
  2801. else
  2802. {
  2803. xml_node_struct* first = node->first_child;
  2804. if (!first)
  2805. writer.write(' ', '/', '>', '\n');
  2806. else if (!first->next_sibling && (PUGI__NODETYPE(first) == node_pcdata || PUGI__NODETYPE(first) == node_cdata))
  2807. {
  2808. writer.write('>');
  2809. const char_t* value = first->value ? first->value : PUGIXML_TEXT("");
  2810. if (PUGI__NODETYPE(first) == node_pcdata)
  2811. text_output(writer, value, ctx_special_pcdata, flags);
  2812. else
  2813. text_output_cdata(writer, value);
  2814. writer.write('<', '/');
  2815. writer.write_string(name);
  2816. writer.write('>', '\n');
  2817. }
  2818. else
  2819. {
  2820. writer.write('>', '\n');
  2821. return true;
  2822. }
  2823. }
  2824. return false;
  2825. }
  2826. PUGI__FN void node_output_end(xml_buffered_writer& writer, xml_node_struct* node, unsigned int flags)
  2827. {
  2828. const char_t* default_name = PUGIXML_TEXT(":anonymous");
  2829. const char_t* name = node->name ? node->name : default_name;
  2830. writer.write('<', '/');
  2831. writer.write_string(name);
  2832. if (flags & format_raw)
  2833. writer.write('>');
  2834. else
  2835. writer.write('>', '\n');
  2836. }
  2837. PUGI__FN void node_output_simple(xml_buffered_writer& writer, xml_node_struct* node, unsigned int flags)
  2838. {
  2839. const char_t* default_name = PUGIXML_TEXT(":anonymous");
  2840. switch (PUGI__NODETYPE(node))
  2841. {
  2842. case node_pcdata:
  2843. text_output(writer, node->value ? node->value : PUGIXML_TEXT(""), ctx_special_pcdata, flags);
  2844. if ((flags & format_raw) == 0) writer.write('\n');
  2845. break;
  2846. case node_cdata:
  2847. text_output_cdata(writer, node->value ? node->value : PUGIXML_TEXT(""));
  2848. if ((flags & format_raw) == 0) writer.write('\n');
  2849. break;
  2850. case node_comment:
  2851. node_output_comment(writer, node->value ? node->value : PUGIXML_TEXT(""));
  2852. if ((flags & format_raw) == 0) writer.write('\n');
  2853. break;
  2854. case node_pi:
  2855. writer.write('<', '?');
  2856. writer.write_string(node->name ? node->name : default_name);
  2857. if (node->value)
  2858. {
  2859. writer.write(' ');
  2860. writer.write_string(node->value);
  2861. }
  2862. writer.write('?', '>');
  2863. if ((flags & format_raw) == 0) writer.write('\n');
  2864. break;
  2865. case node_declaration:
  2866. writer.write('<', '?');
  2867. writer.write_string(node->name ? node->name : default_name);
  2868. node_output_attributes(writer, node, flags);
  2869. writer.write('?', '>');
  2870. if ((flags & format_raw) == 0) writer.write('\n');
  2871. break;
  2872. case node_doctype:
  2873. writer.write('<', '!', 'D', 'O', 'C');
  2874. writer.write('T', 'Y', 'P', 'E');
  2875. if (node->value)
  2876. {
  2877. writer.write(' ');
  2878. writer.write_string(node->value);
  2879. }
  2880. writer.write('>');
  2881. if ((flags & format_raw) == 0) writer.write('\n');
  2882. break;
  2883. default:
  2884. assert(!"Invalid node type");
  2885. }
  2886. }
  2887. PUGI__FN void node_output(xml_buffered_writer& writer, xml_node_struct* root, const char_t* indent, unsigned int flags, unsigned int depth)
  2888. {
  2889. size_t indent_length = ((flags & (format_indent | format_raw)) == format_indent) ? strlength(indent) : 0;
  2890. xml_node_struct* node = root;
  2891. do
  2892. {
  2893. assert(node);
  2894. // begin writing current node
  2895. if (indent_length)
  2896. text_output_indent(writer, indent, indent_length, depth);
  2897. if (PUGI__NODETYPE(node) == node_element)
  2898. {
  2899. if (node_output_start(writer, node, flags))
  2900. {
  2901. node = node->first_child;
  2902. depth++;
  2903. continue;
  2904. }
  2905. }
  2906. else if (PUGI__NODETYPE(node) == node_document)
  2907. {
  2908. if (node->first_child)
  2909. {
  2910. node = node->first_child;
  2911. continue;
  2912. }
  2913. }
  2914. else
  2915. {
  2916. node_output_simple(writer, node, flags);
  2917. }
  2918. // continue to the next node
  2919. while (node != root)
  2920. {
  2921. if (node->next_sibling)
  2922. {
  2923. node = node->next_sibling;
  2924. break;
  2925. }
  2926. node = node->parent;
  2927. // write closing node
  2928. if (PUGI__NODETYPE(node) == node_element)
  2929. {
  2930. depth--;
  2931. if (indent_length)
  2932. text_output_indent(writer, indent, indent_length, depth);
  2933. node_output_end(writer, node, flags);
  2934. }
  2935. }
  2936. }
  2937. while (node != root);
  2938. }
  2939. PUGI__FN bool has_declaration(xml_node_struct* node)
  2940. {
  2941. for (xml_node_struct* child = node->first_child; child; child = child->next_sibling)
  2942. {
  2943. xml_node_type type = PUGI__NODETYPE(child);
  2944. if (type == node_declaration) return true;
  2945. if (type == node_element) return false;
  2946. }
  2947. return false;
  2948. }
  2949. PUGI__FN bool is_attribute_of(xml_attribute_struct* attr, xml_node_struct* node)
  2950. {
  2951. for (xml_attribute_struct* a = node->first_attribute; a; a = a->next_attribute)
  2952. if (a == attr)
  2953. return true;
  2954. return false;
  2955. }
  2956. PUGI__FN bool allow_insert_attribute(xml_node_type parent)
  2957. {
  2958. return parent == node_element || parent == node_declaration;
  2959. }
  2960. PUGI__FN bool allow_insert_child(xml_node_type parent, xml_node_type child)
  2961. {
  2962. if (parent != node_document && parent != node_element) return false;
  2963. if (child == node_document || child == node_null) return false;
  2964. if (parent != node_document && (child == node_declaration || child == node_doctype)) return false;
  2965. return true;
  2966. }
  2967. PUGI__FN bool allow_move(xml_node parent, xml_node child)
  2968. {
  2969. // check that child can be a child of parent
  2970. if (!allow_insert_child(parent.type(), child.type()))
  2971. return false;
  2972. // check that node is not moved between documents
  2973. if (parent.root() != child.root())
  2974. return false;
  2975. // check that new parent is not in the child subtree
  2976. xml_node cur = parent;
  2977. while (cur)
  2978. {
  2979. if (cur == child)
  2980. return false;
  2981. cur = cur.parent();
  2982. }
  2983. return true;
  2984. }
  2985. PUGI__FN void node_copy_string(char_t*& dest, uintptr_t& header, uintptr_t header_mask, char_t* source, uintptr_t& source_header, xml_allocator* alloc)
  2986. {
  2987. assert(!dest && (header & header_mask) == 0);
  2988. if (source)
  2989. {
  2990. if (alloc && (source_header & header_mask) == 0)
  2991. {
  2992. dest = source;
  2993. // since strcpy_insitu can reuse document buffer memory we need to mark both source and dest as shared
  2994. header |= xml_memory_page_contents_shared_mask;
  2995. source_header |= xml_memory_page_contents_shared_mask;
  2996. }
  2997. else
  2998. strcpy_insitu(dest, header, header_mask, source);
  2999. }
  3000. }
  3001. PUGI__FN void node_copy_contents(xml_node_struct* dn, xml_node_struct* sn, xml_allocator* shared_alloc)
  3002. {
  3003. node_copy_string(dn->name, dn->header, xml_memory_page_name_allocated_mask, sn->name, sn->header, shared_alloc);
  3004. node_copy_string(dn->value, dn->header, xml_memory_page_value_allocated_mask, sn->value, sn->header, shared_alloc);
  3005. for (xml_attribute_struct* sa = sn->first_attribute; sa; sa = sa->next_attribute)
  3006. {
  3007. xml_attribute_struct* da = append_new_attribute(dn, get_allocator(dn));
  3008. if (da)
  3009. {
  3010. node_copy_string(da->name, da->header, xml_memory_page_name_allocated_mask, sa->name, sa->header, shared_alloc);
  3011. node_copy_string(da->value, da->header, xml_memory_page_value_allocated_mask, sa->value, sa->header, shared_alloc);
  3012. }
  3013. }
  3014. }
  3015. PUGI__FN void node_copy_tree(xml_node_struct* dn, xml_node_struct* sn)
  3016. {
  3017. xml_allocator& alloc = get_allocator(dn);
  3018. xml_allocator* shared_alloc = (&alloc == &get_allocator(sn)) ? &alloc : 0;
  3019. node_copy_contents(dn, sn, shared_alloc);
  3020. xml_node_struct* dit = dn;
  3021. xml_node_struct* sit = sn->first_child;
  3022. while (sit && sit != sn)
  3023. {
  3024. if (sit != dn)
  3025. {
  3026. xml_node_struct* copy = append_new_node(dit, alloc, PUGI__NODETYPE(sit));
  3027. if (copy)
  3028. {
  3029. node_copy_contents(copy, sit, shared_alloc);
  3030. if (sit->first_child)
  3031. {
  3032. dit = copy;
  3033. sit = sit->first_child;
  3034. continue;
  3035. }
  3036. }
  3037. }
  3038. // continue to the next node
  3039. do
  3040. {
  3041. if (sit->next_sibling)
  3042. {
  3043. sit = sit->next_sibling;
  3044. break;
  3045. }
  3046. sit = sit->parent;
  3047. dit = dit->parent;
  3048. }
  3049. while (sit != sn);
  3050. }
  3051. }
  3052. inline bool is_text_node(xml_node_struct* node)
  3053. {
  3054. xml_node_type type = PUGI__NODETYPE(node);
  3055. return type == node_pcdata || type == node_cdata;
  3056. }
  3057. // get value with conversion functions
  3058. PUGI__FN int get_integer_base(const char_t* value)
  3059. {
  3060. const char_t* s = value;
  3061. while (PUGI__IS_CHARTYPE(*s, ct_space))
  3062. s++;
  3063. if (*s == '-')
  3064. s++;
  3065. return (s[0] == '0' && (s[1] == 'x' || s[1] == 'X')) ? 16 : 10;
  3066. }
  3067. PUGI__FN int get_value_int(const char_t* value, int def)
  3068. {
  3069. if (!value) return def;
  3070. int base = get_integer_base(value);
  3071. #ifdef PUGIXML_WCHAR_MODE
  3072. return static_cast<int>(wcstol(value, 0, base));
  3073. #else
  3074. return static_cast<int>(strtol(value, 0, base));
  3075. #endif
  3076. }
  3077. PUGI__FN unsigned int get_value_uint(const char_t* value, unsigned int def)
  3078. {
  3079. if (!value) return def;
  3080. int base = get_integer_base(value);
  3081. #ifdef PUGIXML_WCHAR_MODE
  3082. return static_cast<unsigned int>(wcstoul(value, 0, base));
  3083. #else
  3084. return static_cast<unsigned int>(strtoul(value, 0, base));
  3085. #endif
  3086. }
  3087. PUGI__FN double get_value_double(const char_t* value, double def)
  3088. {
  3089. if (!value) return def;
  3090. #ifdef PUGIXML_WCHAR_MODE
  3091. return wcstod(value, 0);
  3092. #else
  3093. return strtod(value, 0);
  3094. #endif
  3095. }
  3096. PUGI__FN float get_value_float(const char_t* value, float def)
  3097. {
  3098. if (!value) return def;
  3099. #ifdef PUGIXML_WCHAR_MODE
  3100. return static_cast<float>(wcstod(value, 0));
  3101. #else
  3102. return static_cast<float>(strtod(value, 0));
  3103. #endif
  3104. }
  3105. PUGI__FN bool get_value_bool(const char_t* value, bool def)
  3106. {
  3107. if (!value) return def;
  3108. // only look at first char
  3109. char_t first = *value;
  3110. // 1*, t* (true), T* (True), y* (yes), Y* (YES)
  3111. return (first == '1' || first == 't' || first == 'T' || first == 'y' || first == 'Y');
  3112. }
  3113. #ifdef PUGIXML_HAS_LONG_LONG
  3114. PUGI__FN long long get_value_llong(const char_t* value, long long def)
  3115. {
  3116. if (!value) return def;
  3117. int base = get_integer_base(value);
  3118. #ifdef PUGIXML_WCHAR_MODE
  3119. #ifdef PUGI__MSVC_CRT_VERSION
  3120. return _wcstoi64(value, 0, base);
  3121. #else
  3122. return wcstoll(value, 0, base);
  3123. #endif
  3124. #else
  3125. #ifdef PUGI__MSVC_CRT_VERSION
  3126. return _strtoi64(value, 0, base);
  3127. #else
  3128. return strtoll(value, 0, base);
  3129. #endif
  3130. #endif
  3131. }
  3132. PUGI__FN unsigned long long get_value_ullong(const char_t* value, unsigned long long def)
  3133. {
  3134. if (!value) return def;
  3135. int base = get_integer_base(value);
  3136. #ifdef PUGIXML_WCHAR_MODE
  3137. #ifdef PUGI__MSVC_CRT_VERSION
  3138. return _wcstoui64(value, 0, base);
  3139. #else
  3140. return wcstoull(value, 0, base);
  3141. #endif
  3142. #else
  3143. #ifdef PUGI__MSVC_CRT_VERSION
  3144. return _strtoui64(value, 0, base);
  3145. #else
  3146. return strtoull(value, 0, base);
  3147. #endif
  3148. #endif
  3149. }
  3150. #endif
  3151. // set value with conversion functions
  3152. PUGI__FN bool set_value_buffer(char_t*& dest, uintptr_t& header, uintptr_t header_mask, char (&buf)[128])
  3153. {
  3154. #ifdef PUGIXML_WCHAR_MODE
  3155. char_t wbuf[128];
  3156. impl::widen_ascii(wbuf, buf);
  3157. return strcpy_insitu(dest, header, header_mask, wbuf);
  3158. #else
  3159. return strcpy_insitu(dest, header, header_mask, buf);
  3160. #endif
  3161. }
  3162. PUGI__FN bool set_value_convert(char_t*& dest, uintptr_t& header, uintptr_t header_mask, int value)
  3163. {
  3164. char buf[128];
  3165. sprintf(buf, "%d", value);
  3166. return set_value_buffer(dest, header, header_mask, buf);
  3167. }
  3168. PUGI__FN bool set_value_convert(char_t*& dest, uintptr_t& header, uintptr_t header_mask, unsigned int value)
  3169. {
  3170. char buf[128];
  3171. sprintf(buf, "%u", value);
  3172. return set_value_buffer(dest, header, header_mask, buf);
  3173. }
  3174. PUGI__FN bool set_value_convert(char_t*& dest, uintptr_t& header, uintptr_t header_mask, double value)
  3175. {
  3176. char buf[128];
  3177. sprintf(buf, "%g", value);
  3178. return set_value_buffer(dest, header, header_mask, buf);
  3179. }
  3180. PUGI__FN bool set_value_convert(char_t*& dest, uintptr_t& header, uintptr_t header_mask, bool value)
  3181. {
  3182. return strcpy_insitu(dest, header, header_mask, value ? PUGIXML_TEXT("true") : PUGIXML_TEXT("false"));
  3183. }
  3184. #ifdef PUGIXML_HAS_LONG_LONG
  3185. PUGI__FN bool set_value_convert(char_t*& dest, uintptr_t& header, uintptr_t header_mask, long long value)
  3186. {
  3187. char buf[128];
  3188. sprintf(buf, "%lld", value);
  3189. return set_value_buffer(dest, header, header_mask, buf);
  3190. }
  3191. PUGI__FN bool set_value_convert(char_t*& dest, uintptr_t& header, uintptr_t header_mask, unsigned long long value)
  3192. {
  3193. char buf[128];
  3194. sprintf(buf, "%llu", value);
  3195. return set_value_buffer(dest, header, header_mask, buf);
  3196. }
  3197. #endif
  3198. // we need to get length of entire file to load it in memory; the only (relatively) sane way to do it is via seek/tell trick
  3199. PUGI__FN xml_parse_status get_file_size(FILE* file, size_t& out_result)
  3200. {
  3201. #if defined(PUGI__MSVC_CRT_VERSION) && PUGI__MSVC_CRT_VERSION >= 1400 && !defined(_WIN32_WCE)
  3202. // there are 64-bit versions of fseek/ftell, let's use them
  3203. typedef __int64 length_type;
  3204. _fseeki64(file, 0, SEEK_END);
  3205. length_type length = _ftelli64(file);
  3206. _fseeki64(file, 0, SEEK_SET);
  3207. #elif defined(__MINGW32__) && !defined(__NO_MINGW_LFS) && (!defined(__STRICT_ANSI__) || defined(__MINGW64_VERSION_MAJOR))
  3208. // there are 64-bit versions of fseek/ftell, let's use them
  3209. typedef off64_t length_type;
  3210. fseeko64(file, 0, SEEK_END);
  3211. length_type length = ftello64(file);
  3212. fseeko64(file, 0, SEEK_SET);
  3213. #else
  3214. // if this is a 32-bit OS, long is enough; if this is a unix system, long is 64-bit, which is enough; otherwise we can't do anything anyway.
  3215. typedef long length_type;
  3216. fseek(file, 0, SEEK_END);
  3217. length_type length = ftell(file);
  3218. fseek(file, 0, SEEK_SET);
  3219. #endif
  3220. // check for I/O errors
  3221. if (length < 0) return status_io_error;
  3222. // check for overflow
  3223. size_t result = static_cast<size_t>(length);
  3224. if (static_cast<length_type>(result) != length) return status_out_of_memory;
  3225. // finalize
  3226. out_result = result;
  3227. return status_ok;
  3228. }
  3229. PUGI__FN size_t zero_terminate_buffer(void* buffer, size_t size, xml_encoding encoding)
  3230. {
  3231. // We only need to zero-terminate if encoding conversion does not do it for us
  3232. #ifdef PUGIXML_WCHAR_MODE
  3233. xml_encoding wchar_encoding = get_wchar_encoding();
  3234. if (encoding == wchar_encoding || need_endian_swap_utf(encoding, wchar_encoding))
  3235. {
  3236. size_t length = size / sizeof(char_t);
  3237. static_cast<char_t*>(buffer)[length] = 0;
  3238. return (length + 1) * sizeof(char_t);
  3239. }
  3240. #else
  3241. if (encoding == encoding_utf8)
  3242. {
  3243. static_cast<char*>(buffer)[size] = 0;
  3244. return size + 1;
  3245. }
  3246. #endif
  3247. return size;
  3248. }
  3249. PUGI__FN xml_parse_result load_file_impl(xml_document& doc, FILE* file, unsigned int options, xml_encoding encoding)
  3250. {
  3251. if (!file) return make_parse_result(status_file_not_found);
  3252. // get file size (can result in I/O errors)
  3253. size_t size = 0;
  3254. xml_parse_status size_status = get_file_size(file, size);
  3255. if (size_status != status_ok)
  3256. {
  3257. fclose(file);
  3258. return make_parse_result(size_status);
  3259. }
  3260. size_t max_suffix_size = sizeof(char_t);
  3261. // allocate buffer for the whole file
  3262. char* contents = static_cast<char*>(xml_memory::allocate(size + max_suffix_size));
  3263. if (!contents)
  3264. {
  3265. fclose(file);
  3266. return make_parse_result(status_out_of_memory);
  3267. }
  3268. // read file in memory
  3269. size_t read_size = fread(contents, 1, size, file);
  3270. fclose(file);
  3271. if (read_size != size)
  3272. {
  3273. xml_memory::deallocate(contents);
  3274. return make_parse_result(status_io_error);
  3275. }
  3276. xml_encoding real_encoding = get_buffer_encoding(encoding, contents, size);
  3277. return doc.load_buffer_inplace_own(contents, zero_terminate_buffer(contents, size, real_encoding), options, real_encoding);
  3278. }
  3279. #ifndef PUGIXML_NO_STL
  3280. template <typename T> struct xml_stream_chunk
  3281. {
  3282. static xml_stream_chunk* create()
  3283. {
  3284. void* memory = xml_memory::allocate(sizeof(xml_stream_chunk));
  3285. return new (memory) xml_stream_chunk();
  3286. }
  3287. static void destroy(void* ptr)
  3288. {
  3289. xml_stream_chunk* chunk = static_cast<xml_stream_chunk*>(ptr);
  3290. // free chunk chain
  3291. while (chunk)
  3292. {
  3293. xml_stream_chunk* next_ = chunk->next;
  3294. xml_memory::deallocate(chunk);
  3295. chunk = next_;
  3296. }
  3297. }
  3298. xml_stream_chunk(): next(0), size(0)
  3299. {
  3300. }
  3301. xml_stream_chunk* next;
  3302. size_t size;
  3303. T data[xml_memory_page_size / sizeof(T)];
  3304. };
  3305. template <typename T> PUGI__FN xml_parse_status load_stream_data_noseek(std::basic_istream<T>& stream, void** out_buffer, size_t* out_size)
  3306. {
  3307. buffer_holder chunks(0, xml_stream_chunk<T>::destroy);
  3308. // read file to a chunk list
  3309. size_t total = 0;
  3310. xml_stream_chunk<T>* last = 0;
  3311. while (!stream.eof())
  3312. {
  3313. // allocate new chunk
  3314. xml_stream_chunk<T>* chunk = xml_stream_chunk<T>::create();
  3315. if (!chunk) return status_out_of_memory;
  3316. // append chunk to list
  3317. if (last) last = last->next = chunk;
  3318. else chunks.data = last = chunk;
  3319. // read data to chunk
  3320. stream.read(chunk->data, static_cast<std::streamsize>(sizeof(chunk->data) / sizeof(T)));
  3321. chunk->size = static_cast<size_t>(stream.gcount()) * sizeof(T);
  3322. // read may set failbit | eofbit in case gcount() is less than read length, so check for other I/O errors
  3323. if (stream.bad() || (!stream.eof() && stream.fail())) return status_io_error;
  3324. // guard against huge files (chunk size is small enough to make this overflow check work)
  3325. if (total + chunk->size < total) return status_out_of_memory;
  3326. total += chunk->size;
  3327. }
  3328. size_t max_suffix_size = sizeof(char_t);
  3329. // copy chunk list to a contiguous buffer
  3330. char* buffer = static_cast<char*>(xml_memory::allocate(total + max_suffix_size));
  3331. if (!buffer) return status_out_of_memory;
  3332. char* write = buffer;
  3333. for (xml_stream_chunk<T>* chunk = static_cast<xml_stream_chunk<T>*>(chunks.data); chunk; chunk = chunk->next)
  3334. {
  3335. assert(write + chunk->size <= buffer + total);
  3336. memcpy(write, chunk->data, chunk->size);
  3337. write += chunk->size;
  3338. }
  3339. assert(write == buffer + total);
  3340. // return buffer
  3341. *out_buffer = buffer;
  3342. *out_size = total;
  3343. return status_ok;
  3344. }
  3345. template <typename T> PUGI__FN xml_parse_status load_stream_data_seek(std::basic_istream<T>& stream, void** out_buffer, size_t* out_size)
  3346. {
  3347. // get length of remaining data in stream
  3348. typename std::basic_istream<T>::pos_type pos = stream.tellg();
  3349. stream.seekg(0, std::ios::end);
  3350. std::streamoff length = stream.tellg() - pos;
  3351. stream.seekg(pos);
  3352. if (stream.fail() || pos < 0) return status_io_error;
  3353. // guard against huge files
  3354. size_t read_length = static_cast<size_t>(length);
  3355. if (static_cast<std::streamsize>(read_length) != length || length < 0) return status_out_of_memory;
  3356. size_t max_suffix_size = sizeof(char_t);
  3357. // read stream data into memory (guard against stream exceptions with buffer holder)
  3358. buffer_holder buffer(xml_memory::allocate(read_length * sizeof(T) + max_suffix_size), xml_memory::deallocate);
  3359. if (!buffer.data) return status_out_of_memory;
  3360. stream.read(static_cast<T*>(buffer.data), static_cast<std::streamsize>(read_length));
  3361. // read may set failbit | eofbit in case gcount() is less than read_length (i.e. line ending conversion), so check for other I/O errors
  3362. if (stream.bad() || (!stream.eof() && stream.fail())) return status_io_error;
  3363. // return buffer
  3364. size_t actual_length = static_cast<size_t>(stream.gcount());
  3365. assert(actual_length <= read_length);
  3366. *out_buffer = buffer.release();
  3367. *out_size = actual_length * sizeof(T);
  3368. return status_ok;
  3369. }
  3370. template <typename T> PUGI__FN xml_parse_result load_stream_impl(xml_document& doc, std::basic_istream<T>& stream, unsigned int options, xml_encoding encoding)
  3371. {
  3372. void* buffer = 0;
  3373. size_t size = 0;
  3374. xml_parse_status status = status_ok;
  3375. // if stream has an error bit set, bail out (otherwise tellg() can fail and we'll clear error bits)
  3376. if (stream.fail()) return make_parse_result(status_io_error);
  3377. // load stream to memory (using seek-based implementation if possible, since it's faster and takes less memory)
  3378. if (stream.tellg() < 0)
  3379. {
  3380. stream.clear(); // clear error flags that could be set by a failing tellg
  3381. status = load_stream_data_noseek(stream, &buffer, &size);
  3382. }
  3383. else
  3384. status = load_stream_data_seek(stream, &buffer, &size);
  3385. if (status != status_ok) return make_parse_result(status);
  3386. xml_encoding real_encoding = get_buffer_encoding(encoding, buffer, size);
  3387. return doc.load_buffer_inplace_own(buffer, zero_terminate_buffer(buffer, size, real_encoding), options, real_encoding);
  3388. }
  3389. #endif
  3390. #if defined(PUGI__MSVC_CRT_VERSION) || defined(__BORLANDC__) || (defined(__MINGW32__) && (!defined(__STRICT_ANSI__) || defined(__MINGW64_VERSION_MAJOR)))
  3391. PUGI__FN FILE* open_file_wide(const wchar_t* path, const wchar_t* mode)
  3392. {
  3393. return _wfopen(path, mode);
  3394. }
  3395. #else
  3396. PUGI__FN char* convert_path_heap(const wchar_t* str)
  3397. {
  3398. assert(str);
  3399. // first pass: get length in utf8 characters
  3400. size_t length = strlength_wide(str);
  3401. size_t size = as_utf8_begin(str, length);
  3402. // allocate resulting string
  3403. char* result = static_cast<char*>(xml_memory::allocate(size + 1));
  3404. if (!result) return 0;
  3405. // second pass: convert to utf8
  3406. as_utf8_end(result, size, str, length);
  3407. return result;
  3408. }
  3409. PUGI__FN FILE* open_file_wide(const wchar_t* path, const wchar_t* mode)
  3410. {
  3411. // there is no standard function to open wide paths, so our best bet is to try utf8 path
  3412. char* path_utf8 = convert_path_heap(path);
  3413. if (!path_utf8) return 0;
  3414. // convert mode to ASCII (we mirror _wfopen interface)
  3415. char mode_ascii[4] = {0};
  3416. for (size_t i = 0; mode[i]; ++i) mode_ascii[i] = static_cast<char>(mode[i]);
  3417. // try to open the utf8 path
  3418. FILE* result = fopen(path_utf8, mode_ascii);
  3419. // free dummy buffer
  3420. xml_memory::deallocate(path_utf8);
  3421. return result;
  3422. }
  3423. #endif
  3424. PUGI__FN bool save_file_impl(const xml_document& doc, FILE* file, const char_t* indent, unsigned int flags, xml_encoding encoding)
  3425. {
  3426. if (!file) return false;
  3427. xml_writer_file writer(file);
  3428. doc.save(writer, indent, flags, encoding);
  3429. int result = ferror(file);
  3430. fclose(file);
  3431. return result == 0;
  3432. }
  3433. PUGI__FN xml_parse_result load_buffer_impl(xml_document_struct* doc, xml_node_struct* root, void* contents, size_t size, unsigned int options, xml_encoding encoding, bool is_mutable, bool own, char_t** out_buffer)
  3434. {
  3435. // check input buffer
  3436. assert(contents || size == 0);
  3437. // get actual encoding
  3438. xml_encoding buffer_encoding = impl::get_buffer_encoding(encoding, contents, size);
  3439. // get private buffer
  3440. char_t* buffer = 0;
  3441. size_t length = 0;
  3442. if (!impl::convert_buffer(buffer, length, buffer_encoding, contents, size, is_mutable)) return impl::make_parse_result(status_out_of_memory);
  3443. // delete original buffer if we performed a conversion
  3444. if (own && buffer != contents && contents) impl::xml_memory::deallocate(contents);
  3445. // store buffer for offset_debug
  3446. doc->buffer = buffer;
  3447. // parse
  3448. xml_parse_result res = impl::xml_parser::parse(buffer, length, doc, root, options);
  3449. // remember encoding
  3450. res.encoding = buffer_encoding;
  3451. // grab onto buffer if it's our buffer, user is responsible for deallocating contents himself
  3452. if (own || buffer != contents) *out_buffer = buffer;
  3453. return res;
  3454. }
  3455. PUGI__NS_END
  3456. namespace pugi
  3457. {
  3458. PUGI__FN xml_writer_file::xml_writer_file(void* file_): file(file_)
  3459. {
  3460. }
  3461. PUGI__FN void xml_writer_file::write(const void* data, size_t size)
  3462. {
  3463. size_t result = fwrite(data, 1, size, static_cast<FILE*>(file));
  3464. (void)!result; // unfortunately we can't do proper error handling here
  3465. }
  3466. #ifndef PUGIXML_NO_STL
  3467. PUGI__FN xml_writer_stream::xml_writer_stream(std::basic_ostream<char, std::char_traits<char> >& stream): narrow_stream(&stream), wide_stream(0)
  3468. {
  3469. }
  3470. PUGI__FN xml_writer_stream::xml_writer_stream(std::basic_ostream<wchar_t, std::char_traits<wchar_t> >& stream): narrow_stream(0), wide_stream(&stream)
  3471. {
  3472. }
  3473. PUGI__FN void xml_writer_stream::write(const void* data, size_t size)
  3474. {
  3475. if (narrow_stream)
  3476. {
  3477. assert(!wide_stream);
  3478. narrow_stream->write(reinterpret_cast<const char*>(data), static_cast<std::streamsize>(size));
  3479. }
  3480. else
  3481. {
  3482. assert(wide_stream);
  3483. assert(size % sizeof(wchar_t) == 0);
  3484. wide_stream->write(reinterpret_cast<const wchar_t*>(data), static_cast<std::streamsize>(size / sizeof(wchar_t)));
  3485. }
  3486. }
  3487. #endif
  3488. PUGI__FN xml_tree_walker::xml_tree_walker(): _depth(0)
  3489. {
  3490. }
  3491. PUGI__FN xml_tree_walker::~xml_tree_walker()
  3492. {
  3493. }
  3494. PUGI__FN int xml_tree_walker::depth() const
  3495. {
  3496. return _depth;
  3497. }
  3498. PUGI__FN bool xml_tree_walker::begin(xml_node&)
  3499. {
  3500. return true;
  3501. }
  3502. PUGI__FN bool xml_tree_walker::end(xml_node&)
  3503. {
  3504. return true;
  3505. }
  3506. PUGI__FN xml_attribute::xml_attribute(): _attr(0)
  3507. {
  3508. }
  3509. PUGI__FN xml_attribute::xml_attribute(xml_attribute_struct* attr): _attr(attr)
  3510. {
  3511. }
  3512. PUGI__FN static void unspecified_bool_xml_attribute(xml_attribute***)
  3513. {
  3514. }
  3515. PUGI__FN xml_attribute::operator xml_attribute::unspecified_bool_type() const
  3516. {
  3517. return _attr ? unspecified_bool_xml_attribute : 0;
  3518. }
  3519. PUGI__FN bool xml_attribute::operator!() const
  3520. {
  3521. return !_attr;
  3522. }
  3523. PUGI__FN bool xml_attribute::operator==(const xml_attribute& r) const
  3524. {
  3525. return (_attr == r._attr);
  3526. }
  3527. PUGI__FN bool xml_attribute::operator!=(const xml_attribute& r) const
  3528. {
  3529. return (_attr != r._attr);
  3530. }
  3531. PUGI__FN bool xml_attribute::operator<(const xml_attribute& r) const
  3532. {
  3533. return (_attr < r._attr);
  3534. }
  3535. PUGI__FN bool xml_attribute::operator>(const xml_attribute& r) const
  3536. {
  3537. return (_attr > r._attr);
  3538. }
  3539. PUGI__FN bool xml_attribute::operator<=(const xml_attribute& r) const
  3540. {
  3541. return (_attr <= r._attr);
  3542. }
  3543. PUGI__FN bool xml_attribute::operator>=(const xml_attribute& r) const
  3544. {
  3545. return (_attr >= r._attr);
  3546. }
  3547. PUGI__FN xml_attribute xml_attribute::next_attribute() const
  3548. {
  3549. return _attr ? xml_attribute(_attr->next_attribute) : xml_attribute();
  3550. }
  3551. PUGI__FN xml_attribute xml_attribute::previous_attribute() const
  3552. {
  3553. return _attr && _attr->prev_attribute_c->next_attribute ? xml_attribute(_attr->prev_attribute_c) : xml_attribute();
  3554. }
  3555. PUGI__FN const char_t* xml_attribute::as_string(const char_t* def) const
  3556. {
  3557. return (_attr && _attr->value) ? _attr->value : def;
  3558. }
  3559. PUGI__FN int xml_attribute::as_int(int def) const
  3560. {
  3561. return impl::get_value_int(_attr ? _attr->value : 0, def);
  3562. }
  3563. PUGI__FN unsigned int xml_attribute::as_uint(unsigned int def) const
  3564. {
  3565. return impl::get_value_uint(_attr ? _attr->value : 0, def);
  3566. }
  3567. PUGI__FN double xml_attribute::as_double(double def) const
  3568. {
  3569. return impl::get_value_double(_attr ? _attr->value : 0, def);
  3570. }
  3571. PUGI__FN float xml_attribute::as_float(float def) const
  3572. {
  3573. return impl::get_value_float(_attr ? _attr->value : 0, def);
  3574. }
  3575. PUGI__FN bool xml_attribute::as_bool(bool def) const
  3576. {
  3577. return impl::get_value_bool(_attr ? _attr->value : 0, def);
  3578. }
  3579. #ifdef PUGIXML_HAS_LONG_LONG
  3580. PUGI__FN long long xml_attribute::as_llong(long long def) const
  3581. {
  3582. return impl::get_value_llong(_attr ? _attr->value : 0, def);
  3583. }
  3584. PUGI__FN unsigned long long xml_attribute::as_ullong(unsigned long long def) const
  3585. {
  3586. return impl::get_value_ullong(_attr ? _attr->value : 0, def);
  3587. }
  3588. #endif
  3589. PUGI__FN bool xml_attribute::empty() const
  3590. {
  3591. return !_attr;
  3592. }
  3593. PUGI__FN const char_t* xml_attribute::name() const
  3594. {
  3595. return (_attr && _attr->name) ? _attr->name : PUGIXML_TEXT("");
  3596. }
  3597. PUGI__FN const char_t* xml_attribute::value() const
  3598. {
  3599. return (_attr && _attr->value) ? _attr->value : PUGIXML_TEXT("");
  3600. }
  3601. PUGI__FN size_t xml_attribute::hash_value() const
  3602. {
  3603. return static_cast<size_t>(reinterpret_cast<uintptr_t>(_attr) / sizeof(xml_attribute_struct));
  3604. }
  3605. PUGI__FN xml_attribute_struct* xml_attribute::internal_object() const
  3606. {
  3607. return _attr;
  3608. }
  3609. PUGI__FN xml_attribute& xml_attribute::operator=(const char_t* rhs)
  3610. {
  3611. set_value(rhs);
  3612. return *this;
  3613. }
  3614. PUGI__FN xml_attribute& xml_attribute::operator=(int rhs)
  3615. {
  3616. set_value(rhs);
  3617. return *this;
  3618. }
  3619. PUGI__FN xml_attribute& xml_attribute::operator=(unsigned int rhs)
  3620. {
  3621. set_value(rhs);
  3622. return *this;
  3623. }
  3624. PUGI__FN xml_attribute& xml_attribute::operator=(double rhs)
  3625. {
  3626. set_value(rhs);
  3627. return *this;
  3628. }
  3629. PUGI__FN xml_attribute& xml_attribute::operator=(bool rhs)
  3630. {
  3631. set_value(rhs);
  3632. return *this;
  3633. }
  3634. #ifdef PUGIXML_HAS_LONG_LONG
  3635. PUGI__FN xml_attribute& xml_attribute::operator=(long long rhs)
  3636. {
  3637. set_value(rhs);
  3638. return *this;
  3639. }
  3640. PUGI__FN xml_attribute& xml_attribute::operator=(unsigned long long rhs)
  3641. {
  3642. set_value(rhs);
  3643. return *this;
  3644. }
  3645. #endif
  3646. PUGI__FN bool xml_attribute::set_name(const char_t* rhs)
  3647. {
  3648. if (!_attr) return false;
  3649. return impl::strcpy_insitu(_attr->name, _attr->header, impl::xml_memory_page_name_allocated_mask, rhs);
  3650. }
  3651. PUGI__FN bool xml_attribute::set_value(const char_t* rhs)
  3652. {
  3653. if (!_attr) return false;
  3654. return impl::strcpy_insitu(_attr->value, _attr->header, impl::xml_memory_page_value_allocated_mask, rhs);
  3655. }
  3656. PUGI__FN bool xml_attribute::set_value(int rhs)
  3657. {
  3658. if (!_attr) return false;
  3659. return impl::set_value_convert(_attr->value, _attr->header, impl::xml_memory_page_value_allocated_mask, rhs);
  3660. }
  3661. PUGI__FN bool xml_attribute::set_value(unsigned int rhs)
  3662. {
  3663. if (!_attr) return false;
  3664. return impl::set_value_convert(_attr->value, _attr->header, impl::xml_memory_page_value_allocated_mask, rhs);
  3665. }
  3666. PUGI__FN bool xml_attribute::set_value(double rhs)
  3667. {
  3668. if (!_attr) return false;
  3669. return impl::set_value_convert(_attr->value, _attr->header, impl::xml_memory_page_value_allocated_mask, rhs);
  3670. }
  3671. PUGI__FN bool xml_attribute::set_value(bool rhs)
  3672. {
  3673. if (!_attr) return false;
  3674. return impl::set_value_convert(_attr->value, _attr->header, impl::xml_memory_page_value_allocated_mask, rhs);
  3675. }
  3676. #ifdef PUGIXML_HAS_LONG_LONG
  3677. PUGI__FN bool xml_attribute::set_value(long long rhs)
  3678. {
  3679. if (!_attr) return false;
  3680. return impl::set_value_convert(_attr->value, _attr->header, impl::xml_memory_page_value_allocated_mask, rhs);
  3681. }
  3682. PUGI__FN bool xml_attribute::set_value(unsigned long long rhs)
  3683. {
  3684. if (!_attr) return false;
  3685. return impl::set_value_convert(_attr->value, _attr->header, impl::xml_memory_page_value_allocated_mask, rhs);
  3686. }
  3687. #endif
  3688. #ifdef __BORLANDC__
  3689. PUGI__FN bool operator&&(const xml_attribute& lhs, bool rhs)
  3690. {
  3691. return (bool)lhs && rhs;
  3692. }
  3693. PUGI__FN bool operator||(const xml_attribute& lhs, bool rhs)
  3694. {
  3695. return (bool)lhs || rhs;
  3696. }
  3697. #endif
  3698. PUGI__FN xml_node::xml_node(): _root(0)
  3699. {
  3700. }
  3701. PUGI__FN xml_node::xml_node(xml_node_struct* p): _root(p)
  3702. {
  3703. }
  3704. PUGI__FN static void unspecified_bool_xml_node(xml_node***)
  3705. {
  3706. }
  3707. PUGI__FN xml_node::operator xml_node::unspecified_bool_type() const
  3708. {
  3709. return _root ? unspecified_bool_xml_node : 0;
  3710. }
  3711. PUGI__FN bool xml_node::operator!() const
  3712. {
  3713. return !_root;
  3714. }
  3715. PUGI__FN xml_node::iterator xml_node::begin() const
  3716. {
  3717. return iterator(_root ? _root->first_child : 0, _root);
  3718. }
  3719. PUGI__FN xml_node::iterator xml_node::end() const
  3720. {
  3721. return iterator(0, _root);
  3722. }
  3723. PUGI__FN xml_node::attribute_iterator xml_node::attributes_begin() const
  3724. {
  3725. return attribute_iterator(_root ? _root->first_attribute : 0, _root);
  3726. }
  3727. PUGI__FN xml_node::attribute_iterator xml_node::attributes_end() const
  3728. {
  3729. return attribute_iterator(0, _root);
  3730. }
  3731. PUGI__FN xml_object_range<xml_node_iterator> xml_node::children() const
  3732. {
  3733. return xml_object_range<xml_node_iterator>(begin(), end());
  3734. }
  3735. PUGI__FN xml_object_range<xml_named_node_iterator> xml_node::children(const char_t* name_) const
  3736. {
  3737. return xml_object_range<xml_named_node_iterator>(xml_named_node_iterator(child(name_)._root, _root, name_), xml_named_node_iterator(0, _root, name_));
  3738. }
  3739. PUGI__FN xml_object_range<xml_attribute_iterator> xml_node::attributes() const
  3740. {
  3741. return xml_object_range<xml_attribute_iterator>(attributes_begin(), attributes_end());
  3742. }
  3743. PUGI__FN bool xml_node::operator==(const xml_node& r) const
  3744. {
  3745. return (_root == r._root);
  3746. }
  3747. PUGI__FN bool xml_node::operator!=(const xml_node& r) const
  3748. {
  3749. return (_root != r._root);
  3750. }
  3751. PUGI__FN bool xml_node::operator<(const xml_node& r) const
  3752. {
  3753. return (_root < r._root);
  3754. }
  3755. PUGI__FN bool xml_node::operator>(const xml_node& r) const
  3756. {
  3757. return (_root > r._root);
  3758. }
  3759. PUGI__FN bool xml_node::operator<=(const xml_node& r) const
  3760. {
  3761. return (_root <= r._root);
  3762. }
  3763. PUGI__FN bool xml_node::operator>=(const xml_node& r) const
  3764. {
  3765. return (_root >= r._root);
  3766. }
  3767. PUGI__FN bool xml_node::empty() const
  3768. {
  3769. return !_root;
  3770. }
  3771. PUGI__FN const char_t* xml_node::name() const
  3772. {
  3773. return (_root && _root->name) ? _root->name : PUGIXML_TEXT("");
  3774. }
  3775. PUGI__FN xml_node_type xml_node::type() const
  3776. {
  3777. return _root ? PUGI__NODETYPE(_root) : node_null;
  3778. }
  3779. PUGI__FN const char_t* xml_node::value() const
  3780. {
  3781. return (_root && _root->value) ? _root->value : PUGIXML_TEXT("");
  3782. }
  3783. PUGI__FN xml_node xml_node::child(const char_t* name_) const
  3784. {
  3785. if (!_root) return xml_node();
  3786. for (xml_node_struct* i = _root->first_child; i; i = i->next_sibling)
  3787. if (i->name && impl::strequal(name_, i->name)) return xml_node(i);
  3788. return xml_node();
  3789. }
  3790. PUGI__FN xml_attribute xml_node::attribute(const char_t* name_) const
  3791. {
  3792. if (!_root) return xml_attribute();
  3793. for (xml_attribute_struct* i = _root->first_attribute; i; i = i->next_attribute)
  3794. if (i->name && impl::strequal(name_, i->name))
  3795. return xml_attribute(i);
  3796. return xml_attribute();
  3797. }
  3798. PUGI__FN xml_node xml_node::next_sibling(const char_t* name_) const
  3799. {
  3800. if (!_root) return xml_node();
  3801. for (xml_node_struct* i = _root->next_sibling; i; i = i->next_sibling)
  3802. if (i->name && impl::strequal(name_, i->name)) return xml_node(i);
  3803. return xml_node();
  3804. }
  3805. PUGI__FN xml_node xml_node::next_sibling() const
  3806. {
  3807. return _root ? xml_node(_root->next_sibling) : xml_node();
  3808. }
  3809. PUGI__FN xml_node xml_node::previous_sibling(const char_t* name_) const
  3810. {
  3811. if (!_root) return xml_node();
  3812. for (xml_node_struct* i = _root->prev_sibling_c; i->next_sibling; i = i->prev_sibling_c)
  3813. if (i->name && impl::strequal(name_, i->name)) return xml_node(i);
  3814. return xml_node();
  3815. }
  3816. PUGI__FN xml_node xml_node::previous_sibling() const
  3817. {
  3818. if (!_root) return xml_node();
  3819. if (_root->prev_sibling_c->next_sibling) return xml_node(_root->prev_sibling_c);
  3820. else return xml_node();
  3821. }
  3822. PUGI__FN xml_node xml_node::parent() const
  3823. {
  3824. return _root ? xml_node(_root->parent) : xml_node();
  3825. }
  3826. PUGI__FN xml_node xml_node::root() const
  3827. {
  3828. return _root ? xml_node(&impl::get_document(_root)) : xml_node();
  3829. }
  3830. PUGI__FN xml_text xml_node::text() const
  3831. {
  3832. return xml_text(_root);
  3833. }
  3834. PUGI__FN const char_t* xml_node::child_value() const
  3835. {
  3836. if (!_root) return PUGIXML_TEXT("");
  3837. for (xml_node_struct* i = _root->first_child; i; i = i->next_sibling)
  3838. if (i->value && impl::is_text_node(i))
  3839. return i->value;
  3840. return PUGIXML_TEXT("");
  3841. }
  3842. PUGI__FN const char_t* xml_node::child_value(const char_t* name_) const
  3843. {
  3844. return child(name_).child_value();
  3845. }
  3846. PUGI__FN xml_attribute xml_node::first_attribute() const
  3847. {
  3848. return _root ? xml_attribute(_root->first_attribute) : xml_attribute();
  3849. }
  3850. PUGI__FN xml_attribute xml_node::last_attribute() const
  3851. {
  3852. return _root && _root->first_attribute ? xml_attribute(_root->first_attribute->prev_attribute_c) : xml_attribute();
  3853. }
  3854. PUGI__FN xml_node xml_node::first_child() const
  3855. {
  3856. return _root ? xml_node(_root->first_child) : xml_node();
  3857. }
  3858. PUGI__FN xml_node xml_node::last_child() const
  3859. {
  3860. return _root && _root->first_child ? xml_node(_root->first_child->prev_sibling_c) : xml_node();
  3861. }
  3862. PUGI__FN bool xml_node::set_name(const char_t* rhs)
  3863. {
  3864. switch (type())
  3865. {
  3866. case node_pi:
  3867. case node_declaration:
  3868. case node_element:
  3869. return impl::strcpy_insitu(_root->name, _root->header, impl::xml_memory_page_name_allocated_mask, rhs);
  3870. default:
  3871. return false;
  3872. }
  3873. }
  3874. PUGI__FN bool xml_node::set_value(const char_t* rhs)
  3875. {
  3876. switch (type())
  3877. {
  3878. case node_pi:
  3879. case node_cdata:
  3880. case node_pcdata:
  3881. case node_comment:
  3882. case node_doctype:
  3883. return impl::strcpy_insitu(_root->value, _root->header, impl::xml_memory_page_value_allocated_mask, rhs);
  3884. default:
  3885. return false;
  3886. }
  3887. }
  3888. PUGI__FN xml_attribute xml_node::append_attribute(const char_t* name_)
  3889. {
  3890. if (!impl::allow_insert_attribute(type())) return xml_attribute();
  3891. xml_attribute a(impl::allocate_attribute(impl::get_allocator(_root)));
  3892. if (!a) return xml_attribute();
  3893. impl::append_attribute(a._attr, _root);
  3894. a.set_name(name_);
  3895. return a;
  3896. }
  3897. PUGI__FN xml_attribute xml_node::prepend_attribute(const char_t* name_)
  3898. {
  3899. if (!impl::allow_insert_attribute(type())) return xml_attribute();
  3900. xml_attribute a(impl::allocate_attribute(impl::get_allocator(_root)));
  3901. if (!a) return xml_attribute();
  3902. impl::prepend_attribute(a._attr, _root);
  3903. a.set_name(name_);
  3904. return a;
  3905. }
  3906. PUGI__FN xml_attribute xml_node::insert_attribute_after(const char_t* name_, const xml_attribute& attr)
  3907. {
  3908. if (!impl::allow_insert_attribute(type())) return xml_attribute();
  3909. if (!attr || !impl::is_attribute_of(attr._attr, _root)) return xml_attribute();
  3910. xml_attribute a(impl::allocate_attribute(impl::get_allocator(_root)));
  3911. if (!a) return xml_attribute();
  3912. impl::insert_attribute_after(a._attr, attr._attr, _root);
  3913. a.set_name(name_);
  3914. return a;
  3915. }
  3916. PUGI__FN xml_attribute xml_node::insert_attribute_before(const char_t* name_, const xml_attribute& attr)
  3917. {
  3918. if (!impl::allow_insert_attribute(type())) return xml_attribute();
  3919. if (!attr || !impl::is_attribute_of(attr._attr, _root)) return xml_attribute();
  3920. xml_attribute a(impl::allocate_attribute(impl::get_allocator(_root)));
  3921. if (!a) return xml_attribute();
  3922. impl::insert_attribute_before(a._attr, attr._attr, _root);
  3923. a.set_name(name_);
  3924. return a;
  3925. }
  3926. PUGI__FN xml_attribute xml_node::append_copy(const xml_attribute& proto)
  3927. {
  3928. if (!proto) return xml_attribute();
  3929. xml_attribute result = append_attribute(proto.name());
  3930. result.set_value(proto.value());
  3931. return result;
  3932. }
  3933. PUGI__FN xml_attribute xml_node::prepend_copy(const xml_attribute& proto)
  3934. {
  3935. if (!proto) return xml_attribute();
  3936. xml_attribute result = prepend_attribute(proto.name());
  3937. result.set_value(proto.value());
  3938. return result;
  3939. }
  3940. PUGI__FN xml_attribute xml_node::insert_copy_after(const xml_attribute& proto, const xml_attribute& attr)
  3941. {
  3942. if (!proto) return xml_attribute();
  3943. xml_attribute result = insert_attribute_after(proto.name(), attr);
  3944. result.set_value(proto.value());
  3945. return result;
  3946. }
  3947. PUGI__FN xml_attribute xml_node::insert_copy_before(const xml_attribute& proto, const xml_attribute& attr)
  3948. {
  3949. if (!proto) return xml_attribute();
  3950. xml_attribute result = insert_attribute_before(proto.name(), attr);
  3951. result.set_value(proto.value());
  3952. return result;
  3953. }
  3954. PUGI__FN xml_node xml_node::append_child(xml_node_type type_)
  3955. {
  3956. if (!impl::allow_insert_child(type(), type_)) return xml_node();
  3957. xml_node n(impl::allocate_node(impl::get_allocator(_root), type_));
  3958. if (!n) return xml_node();
  3959. impl::append_node(n._root, _root);
  3960. if (type_ == node_declaration) n.set_name(PUGIXML_TEXT("xml"));
  3961. return n;
  3962. }
  3963. PUGI__FN xml_node xml_node::prepend_child(xml_node_type type_)
  3964. {
  3965. if (!impl::allow_insert_child(type(), type_)) return xml_node();
  3966. xml_node n(impl::allocate_node(impl::get_allocator(_root), type_));
  3967. if (!n) return xml_node();
  3968. impl::prepend_node(n._root, _root);
  3969. if (type_ == node_declaration) n.set_name(PUGIXML_TEXT("xml"));
  3970. return n;
  3971. }
  3972. PUGI__FN xml_node xml_node::insert_child_before(xml_node_type type_, const xml_node& node)
  3973. {
  3974. if (!impl::allow_insert_child(type(), type_)) return xml_node();
  3975. if (!node._root || node._root->parent != _root) return xml_node();
  3976. xml_node n(impl::allocate_node(impl::get_allocator(_root), type_));
  3977. if (!n) return xml_node();
  3978. impl::insert_node_before(n._root, node._root);
  3979. if (type_ == node_declaration) n.set_name(PUGIXML_TEXT("xml"));
  3980. return n;
  3981. }
  3982. PUGI__FN xml_node xml_node::insert_child_after(xml_node_type type_, const xml_node& node)
  3983. {
  3984. if (!impl::allow_insert_child(type(), type_)) return xml_node();
  3985. if (!node._root || node._root->parent != _root) return xml_node();
  3986. xml_node n(impl::allocate_node(impl::get_allocator(_root), type_));
  3987. if (!n) return xml_node();
  3988. impl::insert_node_after(n._root, node._root);
  3989. if (type_ == node_declaration) n.set_name(PUGIXML_TEXT("xml"));
  3990. return n;
  3991. }
  3992. PUGI__FN xml_node xml_node::append_child(const char_t* name_)
  3993. {
  3994. xml_node result = append_child(node_element);
  3995. result.set_name(name_);
  3996. return result;
  3997. }
  3998. PUGI__FN xml_node xml_node::prepend_child(const char_t* name_)
  3999. {
  4000. xml_node result = prepend_child(node_element);
  4001. result.set_name(name_);
  4002. return result;
  4003. }
  4004. PUGI__FN xml_node xml_node::insert_child_after(const char_t* name_, const xml_node& node)
  4005. {
  4006. xml_node result = insert_child_after(node_element, node);
  4007. result.set_name(name_);
  4008. return result;
  4009. }
  4010. PUGI__FN xml_node xml_node::insert_child_before(const char_t* name_, const xml_node& node)
  4011. {
  4012. xml_node result = insert_child_before(node_element, node);
  4013. result.set_name(name_);
  4014. return result;
  4015. }
  4016. PUGI__FN xml_node xml_node::append_copy(const xml_node& proto)
  4017. {
  4018. xml_node_type type_ = proto.type();
  4019. if (!impl::allow_insert_child(type(), type_)) return xml_node();
  4020. xml_node n(impl::allocate_node(impl::get_allocator(_root), type_));
  4021. if (!n) return xml_node();
  4022. impl::append_node(n._root, _root);
  4023. impl::node_copy_tree(n._root, proto._root);
  4024. return n;
  4025. }
  4026. PUGI__FN xml_node xml_node::prepend_copy(const xml_node& proto)
  4027. {
  4028. xml_node_type type_ = proto.type();
  4029. if (!impl::allow_insert_child(type(), type_)) return xml_node();
  4030. xml_node n(impl::allocate_node(impl::get_allocator(_root), type_));
  4031. if (!n) return xml_node();
  4032. impl::prepend_node(n._root, _root);
  4033. impl::node_copy_tree(n._root, proto._root);
  4034. return n;
  4035. }
  4036. PUGI__FN xml_node xml_node::insert_copy_after(const xml_node& proto, const xml_node& node)
  4037. {
  4038. xml_node_type type_ = proto.type();
  4039. if (!impl::allow_insert_child(type(), type_)) return xml_node();
  4040. if (!node._root || node._root->parent != _root) return xml_node();
  4041. xml_node n(impl::allocate_node(impl::get_allocator(_root), type_));
  4042. if (!n) return xml_node();
  4043. impl::insert_node_after(n._root, node._root);
  4044. impl::node_copy_tree(n._root, proto._root);
  4045. return n;
  4046. }
  4047. PUGI__FN xml_node xml_node::insert_copy_before(const xml_node& proto, const xml_node& node)
  4048. {
  4049. xml_node_type type_ = proto.type();
  4050. if (!impl::allow_insert_child(type(), type_)) return xml_node();
  4051. if (!node._root || node._root->parent != _root) return xml_node();
  4052. xml_node n(impl::allocate_node(impl::get_allocator(_root), type_));
  4053. if (!n) return xml_node();
  4054. impl::insert_node_before(n._root, node._root);
  4055. impl::node_copy_tree(n._root, proto._root);
  4056. return n;
  4057. }
  4058. PUGI__FN xml_node xml_node::append_move(const xml_node& moved)
  4059. {
  4060. if (!impl::allow_move(*this, moved)) return xml_node();
  4061. // disable document_buffer_order optimization since moving nodes around changes document order without changing buffer pointers
  4062. impl::get_document(_root).header |= impl::xml_memory_page_contents_shared_mask;
  4063. impl::remove_node(moved._root);
  4064. impl::append_node(moved._root, _root);
  4065. return moved;
  4066. }
  4067. PUGI__FN xml_node xml_node::prepend_move(const xml_node& moved)
  4068. {
  4069. if (!impl::allow_move(*this, moved)) return xml_node();
  4070. // disable document_buffer_order optimization since moving nodes around changes document order without changing buffer pointers
  4071. impl::get_document(_root).header |= impl::xml_memory_page_contents_shared_mask;
  4072. impl::remove_node(moved._root);
  4073. impl::prepend_node(moved._root, _root);
  4074. return moved;
  4075. }
  4076. PUGI__FN xml_node xml_node::insert_move_after(const xml_node& moved, const xml_node& node)
  4077. {
  4078. if (!impl::allow_move(*this, moved)) return xml_node();
  4079. if (!node._root || node._root->parent != _root) return xml_node();
  4080. if (moved._root == node._root) return xml_node();
  4081. // disable document_buffer_order optimization since moving nodes around changes document order without changing buffer pointers
  4082. impl::get_document(_root).header |= impl::xml_memory_page_contents_shared_mask;
  4083. impl::remove_node(moved._root);
  4084. impl::insert_node_after(moved._root, node._root);
  4085. return moved;
  4086. }
  4087. PUGI__FN xml_node xml_node::insert_move_before(const xml_node& moved, const xml_node& node)
  4088. {
  4089. if (!impl::allow_move(*this, moved)) return xml_node();
  4090. if (!node._root || node._root->parent != _root) return xml_node();
  4091. if (moved._root == node._root) return xml_node();
  4092. // disable document_buffer_order optimization since moving nodes around changes document order without changing buffer pointers
  4093. impl::get_document(_root).header |= impl::xml_memory_page_contents_shared_mask;
  4094. impl::remove_node(moved._root);
  4095. impl::insert_node_before(moved._root, node._root);
  4096. return moved;
  4097. }
  4098. PUGI__FN bool xml_node::remove_attribute(const char_t* name_)
  4099. {
  4100. return remove_attribute(attribute(name_));
  4101. }
  4102. PUGI__FN bool xml_node::remove_attribute(const xml_attribute& a)
  4103. {
  4104. if (!_root || !a._attr) return false;
  4105. if (!impl::is_attribute_of(a._attr, _root)) return false;
  4106. impl::remove_attribute(a._attr, _root);
  4107. impl::destroy_attribute(a._attr, impl::get_allocator(_root));
  4108. return true;
  4109. }
  4110. PUGI__FN bool xml_node::remove_child(const char_t* name_)
  4111. {
  4112. return remove_child(child(name_));
  4113. }
  4114. PUGI__FN bool xml_node::remove_child(const xml_node& n)
  4115. {
  4116. if (!_root || !n._root || n._root->parent != _root) return false;
  4117. impl::remove_node(n._root);
  4118. impl::destroy_node(n._root, impl::get_allocator(_root));
  4119. return true;
  4120. }
  4121. PUGI__FN xml_parse_result xml_node::append_buffer(const void* contents, size_t size, unsigned int options, xml_encoding encoding)
  4122. {
  4123. // append_buffer is only valid for elements/documents
  4124. if (!impl::allow_insert_child(type(), node_element)) return impl::make_parse_result(status_append_invalid_root);
  4125. // get document node
  4126. impl::xml_document_struct* doc = &impl::get_document(_root);
  4127. // disable document_buffer_order optimization since in a document with multiple buffers comparing buffer pointers does not make sense
  4128. doc->header |= impl::xml_memory_page_contents_shared_mask;
  4129. // get extra buffer element (we'll store the document fragment buffer there so that we can deallocate it later)
  4130. impl::xml_memory_page* page = 0;
  4131. impl::xml_extra_buffer* extra = static_cast<impl::xml_extra_buffer*>(doc->allocate_memory(sizeof(impl::xml_extra_buffer), page));
  4132. (void)page;
  4133. if (!extra) return impl::make_parse_result(status_out_of_memory);
  4134. // save name; name of the root has to be NULL before parsing - otherwise closing node mismatches will not be detected at the top level
  4135. char_t* rootname = _root->name;
  4136. _root->name = 0;
  4137. // parse
  4138. char_t* buffer = 0;
  4139. xml_parse_result res = impl::load_buffer_impl(doc, _root, const_cast<void*>(contents), size, options, encoding, false, false, &buffer);
  4140. // restore name
  4141. _root->name = rootname;
  4142. // add extra buffer to the list
  4143. extra->buffer = buffer;
  4144. extra->next = doc->extra_buffers;
  4145. doc->extra_buffers = extra;
  4146. return res;
  4147. }
  4148. PUGI__FN xml_node xml_node::find_child_by_attribute(const char_t* name_, const char_t* attr_name, const char_t* attr_value) const
  4149. {
  4150. if (!_root) return xml_node();
  4151. for (xml_node_struct* i = _root->first_child; i; i = i->next_sibling)
  4152. if (i->name && impl::strequal(name_, i->name))
  4153. {
  4154. for (xml_attribute_struct* a = i->first_attribute; a; a = a->next_attribute)
  4155. if (a->name && impl::strequal(attr_name, a->name) && impl::strequal(attr_value, a->value ? a->value : PUGIXML_TEXT("")))
  4156. return xml_node(i);
  4157. }
  4158. return xml_node();
  4159. }
  4160. PUGI__FN xml_node xml_node::find_child_by_attribute(const char_t* attr_name, const char_t* attr_value) const
  4161. {
  4162. if (!_root) return xml_node();
  4163. for (xml_node_struct* i = _root->first_child; i; i = i->next_sibling)
  4164. for (xml_attribute_struct* a = i->first_attribute; a; a = a->next_attribute)
  4165. if (a->name && impl::strequal(attr_name, a->name) && impl::strequal(attr_value, a->value ? a->value : PUGIXML_TEXT("")))
  4166. return xml_node(i);
  4167. return xml_node();
  4168. }
  4169. #ifndef PUGIXML_NO_STL
  4170. PUGI__FN string_t xml_node::path(char_t delimiter) const
  4171. {
  4172. xml_node cursor = *this; // Make a copy.
  4173. string_t result = cursor.name();
  4174. while (cursor.parent())
  4175. {
  4176. cursor = cursor.parent();
  4177. string_t temp = cursor.name();
  4178. temp += delimiter;
  4179. temp += result;
  4180. result.swap(temp);
  4181. }
  4182. return result;
  4183. }
  4184. #endif
  4185. PUGI__FN xml_node xml_node::first_element_by_path(const char_t* path_, char_t delimiter) const
  4186. {
  4187. xml_node found = *this; // Current search context.
  4188. if (!_root || !path_ || !path_[0]) return found;
  4189. if (path_[0] == delimiter)
  4190. {
  4191. // Absolute path; e.g. '/foo/bar'
  4192. found = found.root();
  4193. ++path_;
  4194. }
  4195. const char_t* path_segment = path_;
  4196. while (*path_segment == delimiter) ++path_segment;
  4197. const char_t* path_segment_end = path_segment;
  4198. while (*path_segment_end && *path_segment_end != delimiter) ++path_segment_end;
  4199. if (path_segment == path_segment_end) return found;
  4200. const char_t* next_segment = path_segment_end;
  4201. while (*next_segment == delimiter) ++next_segment;
  4202. if (*path_segment == '.' && path_segment + 1 == path_segment_end)
  4203. return found.first_element_by_path(next_segment, delimiter);
  4204. else if (*path_segment == '.' && *(path_segment+1) == '.' && path_segment + 2 == path_segment_end)
  4205. return found.parent().first_element_by_path(next_segment, delimiter);
  4206. else
  4207. {
  4208. for (xml_node_struct* j = found._root->first_child; j; j = j->next_sibling)
  4209. {
  4210. if (j->name && impl::strequalrange(j->name, path_segment, static_cast<size_t>(path_segment_end - path_segment)))
  4211. {
  4212. xml_node subsearch = xml_node(j).first_element_by_path(next_segment, delimiter);
  4213. if (subsearch) return subsearch;
  4214. }
  4215. }
  4216. return xml_node();
  4217. }
  4218. }
  4219. PUGI__FN bool xml_node::traverse(xml_tree_walker& walker)
  4220. {
  4221. walker._depth = -1;
  4222. xml_node arg_begin = *this;
  4223. if (!walker.begin(arg_begin)) return false;
  4224. xml_node cur = first_child();
  4225. if (cur)
  4226. {
  4227. ++walker._depth;
  4228. do
  4229. {
  4230. xml_node arg_for_each = cur;
  4231. if (!walker.for_each(arg_for_each))
  4232. return false;
  4233. if (cur.first_child())
  4234. {
  4235. ++walker._depth;
  4236. cur = cur.first_child();
  4237. }
  4238. else if (cur.next_sibling())
  4239. cur = cur.next_sibling();
  4240. else
  4241. {
  4242. // Borland C++ workaround
  4243. while (!cur.next_sibling() && cur != *this && !cur.parent().empty())
  4244. {
  4245. --walker._depth;
  4246. cur = cur.parent();
  4247. }
  4248. if (cur != *this)
  4249. cur = cur.next_sibling();
  4250. }
  4251. }
  4252. while (cur && cur != *this);
  4253. }
  4254. assert(walker._depth == -1);
  4255. xml_node arg_end = *this;
  4256. return walker.end(arg_end);
  4257. }
  4258. PUGI__FN size_t xml_node::hash_value() const
  4259. {
  4260. return static_cast<size_t>(reinterpret_cast<uintptr_t>(_root) / sizeof(xml_node_struct));
  4261. }
  4262. PUGI__FN xml_node_struct* xml_node::internal_object() const
  4263. {
  4264. return _root;
  4265. }
  4266. PUGI__FN void xml_node::print(xml_writer& writer, const char_t* indent, unsigned int flags, xml_encoding encoding, unsigned int depth) const
  4267. {
  4268. if (!_root) return;
  4269. impl::xml_buffered_writer buffered_writer(writer, encoding);
  4270. impl::node_output(buffered_writer, _root, indent, flags, depth);
  4271. }
  4272. #ifndef PUGIXML_NO_STL
  4273. PUGI__FN void xml_node::print(std::basic_ostream<char, std::char_traits<char> >& stream, const char_t* indent, unsigned int flags, xml_encoding encoding, unsigned int depth) const
  4274. {
  4275. xml_writer_stream writer(stream);
  4276. print(writer, indent, flags, encoding, depth);
  4277. }
  4278. PUGI__FN void xml_node::print(std::basic_ostream<wchar_t, std::char_traits<wchar_t> >& stream, const char_t* indent, unsigned int flags, unsigned int depth) const
  4279. {
  4280. xml_writer_stream writer(stream);
  4281. print(writer, indent, flags, encoding_wchar, depth);
  4282. }
  4283. #endif
  4284. PUGI__FN ptrdiff_t xml_node::offset_debug() const
  4285. {
  4286. if (!_root) return -1;
  4287. impl::xml_document_struct& doc = impl::get_document(_root);
  4288. // we can determine the offset reliably only if there is exactly once parse buffer
  4289. if (!doc.buffer || doc.extra_buffers) return -1;
  4290. switch (type())
  4291. {
  4292. case node_document:
  4293. return 0;
  4294. case node_element:
  4295. case node_declaration:
  4296. case node_pi:
  4297. return _root->name && (_root->header & impl::xml_memory_page_name_allocated_or_shared_mask) == 0 ? _root->name - doc.buffer : -1;
  4298. case node_pcdata:
  4299. case node_cdata:
  4300. case node_comment:
  4301. case node_doctype:
  4302. return _root->value && (_root->header & impl::xml_memory_page_value_allocated_or_shared_mask) == 0 ? _root->value - doc.buffer : -1;
  4303. default:
  4304. return -1;
  4305. }
  4306. }
  4307. #ifdef __BORLANDC__
  4308. PUGI__FN bool operator&&(const xml_node& lhs, bool rhs)
  4309. {
  4310. return (bool)lhs && rhs;
  4311. }
  4312. PUGI__FN bool operator||(const xml_node& lhs, bool rhs)
  4313. {
  4314. return (bool)lhs || rhs;
  4315. }
  4316. #endif
  4317. PUGI__FN xml_text::xml_text(xml_node_struct* root): _root(root)
  4318. {
  4319. }
  4320. PUGI__FN xml_node_struct* xml_text::_data() const
  4321. {
  4322. if (!_root || impl::is_text_node(_root)) return _root;
  4323. for (xml_node_struct* node = _root->first_child; node; node = node->next_sibling)
  4324. if (impl::is_text_node(node))
  4325. return node;
  4326. return 0;
  4327. }
  4328. PUGI__FN xml_node_struct* xml_text::_data_new()
  4329. {
  4330. xml_node_struct* d = _data();
  4331. if (d) return d;
  4332. return xml_node(_root).append_child(node_pcdata).internal_object();
  4333. }
  4334. PUGI__FN xml_text::xml_text(): _root(0)
  4335. {
  4336. }
  4337. PUGI__FN static void unspecified_bool_xml_text(xml_text***)
  4338. {
  4339. }
  4340. PUGI__FN xml_text::operator xml_text::unspecified_bool_type() const
  4341. {
  4342. return _data() ? unspecified_bool_xml_text : 0;
  4343. }
  4344. PUGI__FN bool xml_text::operator!() const
  4345. {
  4346. return !_data();
  4347. }
  4348. PUGI__FN bool xml_text::empty() const
  4349. {
  4350. return _data() == 0;
  4351. }
  4352. PUGI__FN const char_t* xml_text::get() const
  4353. {
  4354. xml_node_struct* d = _data();
  4355. return (d && d->value) ? d->value : PUGIXML_TEXT("");
  4356. }
  4357. PUGI__FN const char_t* xml_text::as_string(const char_t* def) const
  4358. {
  4359. xml_node_struct* d = _data();
  4360. return (d && d->value) ? d->value : def;
  4361. }
  4362. PUGI__FN int xml_text::as_int(int def) const
  4363. {
  4364. xml_node_struct* d = _data();
  4365. return impl::get_value_int(d ? d->value : 0, def);
  4366. }
  4367. PUGI__FN unsigned int xml_text::as_uint(unsigned int def) const
  4368. {
  4369. xml_node_struct* d = _data();
  4370. return impl::get_value_uint(d ? d->value : 0, def);
  4371. }
  4372. PUGI__FN double xml_text::as_double(double def) const
  4373. {
  4374. xml_node_struct* d = _data();
  4375. return impl::get_value_double(d ? d->value : 0, def);
  4376. }
  4377. PUGI__FN float xml_text::as_float(float def) const
  4378. {
  4379. xml_node_struct* d = _data();
  4380. return impl::get_value_float(d ? d->value : 0, def);
  4381. }
  4382. PUGI__FN bool xml_text::as_bool(bool def) const
  4383. {
  4384. xml_node_struct* d = _data();
  4385. return impl::get_value_bool(d ? d->value : 0, def);
  4386. }
  4387. #ifdef PUGIXML_HAS_LONG_LONG
  4388. PUGI__FN long long xml_text::as_llong(long long def) const
  4389. {
  4390. xml_node_struct* d = _data();
  4391. return impl::get_value_llong(d ? d->value : 0, def);
  4392. }
  4393. PUGI__FN unsigned long long xml_text::as_ullong(unsigned long long def) const
  4394. {
  4395. xml_node_struct* d = _data();
  4396. return impl::get_value_ullong(d ? d->value : 0, def);
  4397. }
  4398. #endif
  4399. PUGI__FN bool xml_text::set(const char_t* rhs)
  4400. {
  4401. xml_node_struct* dn = _data_new();
  4402. return dn ? impl::strcpy_insitu(dn->value, dn->header, impl::xml_memory_page_value_allocated_mask, rhs) : false;
  4403. }
  4404. PUGI__FN bool xml_text::set(int rhs)
  4405. {
  4406. xml_node_struct* dn = _data_new();
  4407. return dn ? impl::set_value_convert(dn->value, dn->header, impl::xml_memory_page_value_allocated_mask, rhs) : false;
  4408. }
  4409. PUGI__FN bool xml_text::set(unsigned int rhs)
  4410. {
  4411. xml_node_struct* dn = _data_new();
  4412. return dn ? impl::set_value_convert(dn->value, dn->header, impl::xml_memory_page_value_allocated_mask, rhs) : false;
  4413. }
  4414. PUGI__FN bool xml_text::set(double rhs)
  4415. {
  4416. xml_node_struct* dn = _data_new();
  4417. return dn ? impl::set_value_convert(dn->value, dn->header, impl::xml_memory_page_value_allocated_mask, rhs) : false;
  4418. }
  4419. PUGI__FN bool xml_text::set(bool rhs)
  4420. {
  4421. xml_node_struct* dn = _data_new();
  4422. return dn ? impl::set_value_convert(dn->value, dn->header, impl::xml_memory_page_value_allocated_mask, rhs) : false;
  4423. }
  4424. #ifdef PUGIXML_HAS_LONG_LONG
  4425. PUGI__FN bool xml_text::set(long long rhs)
  4426. {
  4427. xml_node_struct* dn = _data_new();
  4428. return dn ? impl::set_value_convert(dn->value, dn->header, impl::xml_memory_page_value_allocated_mask, rhs) : false;
  4429. }
  4430. PUGI__FN bool xml_text::set(unsigned long long rhs)
  4431. {
  4432. xml_node_struct* dn = _data_new();
  4433. return dn ? impl::set_value_convert(dn->value, dn->header, impl::xml_memory_page_value_allocated_mask, rhs) : false;
  4434. }
  4435. #endif
  4436. PUGI__FN xml_text& xml_text::operator=(const char_t* rhs)
  4437. {
  4438. set(rhs);
  4439. return *this;
  4440. }
  4441. PUGI__FN xml_text& xml_text::operator=(int rhs)
  4442. {
  4443. set(rhs);
  4444. return *this;
  4445. }
  4446. PUGI__FN xml_text& xml_text::operator=(unsigned int rhs)
  4447. {
  4448. set(rhs);
  4449. return *this;
  4450. }
  4451. PUGI__FN xml_text& xml_text::operator=(double rhs)
  4452. {
  4453. set(rhs);
  4454. return *this;
  4455. }
  4456. PUGI__FN xml_text& xml_text::operator=(bool rhs)
  4457. {
  4458. set(rhs);
  4459. return *this;
  4460. }
  4461. #ifdef PUGIXML_HAS_LONG_LONG
  4462. PUGI__FN xml_text& xml_text::operator=(long long rhs)
  4463. {
  4464. set(rhs);
  4465. return *this;
  4466. }
  4467. PUGI__FN xml_text& xml_text::operator=(unsigned long long rhs)
  4468. {
  4469. set(rhs);
  4470. return *this;
  4471. }
  4472. #endif
  4473. PUGI__FN xml_node xml_text::data() const
  4474. {
  4475. return xml_node(_data());
  4476. }
  4477. #ifdef __BORLANDC__
  4478. PUGI__FN bool operator&&(const xml_text& lhs, bool rhs)
  4479. {
  4480. return (bool)lhs && rhs;
  4481. }
  4482. PUGI__FN bool operator||(const xml_text& lhs, bool rhs)
  4483. {
  4484. return (bool)lhs || rhs;
  4485. }
  4486. #endif
  4487. PUGI__FN xml_node_iterator::xml_node_iterator()
  4488. {
  4489. }
  4490. PUGI__FN xml_node_iterator::xml_node_iterator(const xml_node& node): _wrap(node), _parent(node.parent())
  4491. {
  4492. }
  4493. PUGI__FN xml_node_iterator::xml_node_iterator(xml_node_struct* ref, xml_node_struct* parent): _wrap(ref), _parent(parent)
  4494. {
  4495. }
  4496. PUGI__FN bool xml_node_iterator::operator==(const xml_node_iterator& rhs) const
  4497. {
  4498. return _wrap._root == rhs._wrap._root && _parent._root == rhs._parent._root;
  4499. }
  4500. PUGI__FN bool xml_node_iterator::operator!=(const xml_node_iterator& rhs) const
  4501. {
  4502. return _wrap._root != rhs._wrap._root || _parent._root != rhs._parent._root;
  4503. }
  4504. PUGI__FN xml_node& xml_node_iterator::operator*() const
  4505. {
  4506. assert(_wrap._root);
  4507. return _wrap;
  4508. }
  4509. PUGI__FN xml_node* xml_node_iterator::operator->() const
  4510. {
  4511. assert(_wrap._root);
  4512. return const_cast<xml_node*>(&_wrap); // BCC32 workaround
  4513. }
  4514. PUGI__FN const xml_node_iterator& xml_node_iterator::operator++()
  4515. {
  4516. assert(_wrap._root);
  4517. _wrap._root = _wrap._root->next_sibling;
  4518. return *this;
  4519. }
  4520. PUGI__FN xml_node_iterator xml_node_iterator::operator++(int)
  4521. {
  4522. xml_node_iterator temp = *this;
  4523. ++*this;
  4524. return temp;
  4525. }
  4526. PUGI__FN const xml_node_iterator& xml_node_iterator::operator--()
  4527. {
  4528. _wrap = _wrap._root ? _wrap.previous_sibling() : _parent.last_child();
  4529. return *this;
  4530. }
  4531. PUGI__FN xml_node_iterator xml_node_iterator::operator--(int)
  4532. {
  4533. xml_node_iterator temp = *this;
  4534. --*this;
  4535. return temp;
  4536. }
  4537. PUGI__FN xml_attribute_iterator::xml_attribute_iterator()
  4538. {
  4539. }
  4540. PUGI__FN xml_attribute_iterator::xml_attribute_iterator(const xml_attribute& attr, const xml_node& parent): _wrap(attr), _parent(parent)
  4541. {
  4542. }
  4543. PUGI__FN xml_attribute_iterator::xml_attribute_iterator(xml_attribute_struct* ref, xml_node_struct* parent): _wrap(ref), _parent(parent)
  4544. {
  4545. }
  4546. PUGI__FN bool xml_attribute_iterator::operator==(const xml_attribute_iterator& rhs) const
  4547. {
  4548. return _wrap._attr == rhs._wrap._attr && _parent._root == rhs._parent._root;
  4549. }
  4550. PUGI__FN bool xml_attribute_iterator::operator!=(const xml_attribute_iterator& rhs) const
  4551. {
  4552. return _wrap._attr != rhs._wrap._attr || _parent._root != rhs._parent._root;
  4553. }
  4554. PUGI__FN xml_attribute& xml_attribute_iterator::operator*() const
  4555. {
  4556. assert(_wrap._attr);
  4557. return _wrap;
  4558. }
  4559. PUGI__FN xml_attribute* xml_attribute_iterator::operator->() const
  4560. {
  4561. assert(_wrap._attr);
  4562. return const_cast<xml_attribute*>(&_wrap); // BCC32 workaround
  4563. }
  4564. PUGI__FN const xml_attribute_iterator& xml_attribute_iterator::operator++()
  4565. {
  4566. assert(_wrap._attr);
  4567. _wrap._attr = _wrap._attr->next_attribute;
  4568. return *this;
  4569. }
  4570. PUGI__FN xml_attribute_iterator xml_attribute_iterator::operator++(int)
  4571. {
  4572. xml_attribute_iterator temp = *this;
  4573. ++*this;
  4574. return temp;
  4575. }
  4576. PUGI__FN const xml_attribute_iterator& xml_attribute_iterator::operator--()
  4577. {
  4578. _wrap = _wrap._attr ? _wrap.previous_attribute() : _parent.last_attribute();
  4579. return *this;
  4580. }
  4581. PUGI__FN xml_attribute_iterator xml_attribute_iterator::operator--(int)
  4582. {
  4583. xml_attribute_iterator temp = *this;
  4584. --*this;
  4585. return temp;
  4586. }
  4587. PUGI__FN xml_named_node_iterator::xml_named_node_iterator(): _name(0)
  4588. {
  4589. }
  4590. PUGI__FN xml_named_node_iterator::xml_named_node_iterator(const xml_node& node, const char_t* name): _wrap(node), _parent(node.parent()), _name(name)
  4591. {
  4592. }
  4593. PUGI__FN xml_named_node_iterator::xml_named_node_iterator(xml_node_struct* ref, xml_node_struct* parent, const char_t* name): _wrap(ref), _parent(parent), _name(name)
  4594. {
  4595. }
  4596. PUGI__FN bool xml_named_node_iterator::operator==(const xml_named_node_iterator& rhs) const
  4597. {
  4598. return _wrap._root == rhs._wrap._root && _parent._root == rhs._parent._root;
  4599. }
  4600. PUGI__FN bool xml_named_node_iterator::operator!=(const xml_named_node_iterator& rhs) const
  4601. {
  4602. return _wrap._root != rhs._wrap._root || _parent._root != rhs._parent._root;
  4603. }
  4604. PUGI__FN xml_node& xml_named_node_iterator::operator*() const
  4605. {
  4606. assert(_wrap._root);
  4607. return _wrap;
  4608. }
  4609. PUGI__FN xml_node* xml_named_node_iterator::operator->() const
  4610. {
  4611. assert(_wrap._root);
  4612. return const_cast<xml_node*>(&_wrap); // BCC32 workaround
  4613. }
  4614. PUGI__FN const xml_named_node_iterator& xml_named_node_iterator::operator++()
  4615. {
  4616. assert(_wrap._root);
  4617. _wrap = _wrap.next_sibling(_name);
  4618. return *this;
  4619. }
  4620. PUGI__FN xml_named_node_iterator xml_named_node_iterator::operator++(int)
  4621. {
  4622. xml_named_node_iterator temp = *this;
  4623. ++*this;
  4624. return temp;
  4625. }
  4626. PUGI__FN const xml_named_node_iterator& xml_named_node_iterator::operator--()
  4627. {
  4628. if (_wrap._root)
  4629. _wrap = _wrap.previous_sibling(_name);
  4630. else
  4631. {
  4632. _wrap = _parent.last_child();
  4633. if (!impl::strequal(_wrap.name(), _name))
  4634. _wrap = _wrap.previous_sibling(_name);
  4635. }
  4636. return *this;
  4637. }
  4638. PUGI__FN xml_named_node_iterator xml_named_node_iterator::operator--(int)
  4639. {
  4640. xml_named_node_iterator temp = *this;
  4641. --*this;
  4642. return temp;
  4643. }
  4644. PUGI__FN xml_parse_result::xml_parse_result(): status(status_internal_error), offset(0), encoding(encoding_auto)
  4645. {
  4646. }
  4647. PUGI__FN xml_parse_result::operator bool() const
  4648. {
  4649. return status == status_ok;
  4650. }
  4651. PUGI__FN const char* xml_parse_result::description() const
  4652. {
  4653. switch (status)
  4654. {
  4655. case status_ok: return "No error";
  4656. case status_file_not_found: return "File was not found";
  4657. case status_io_error: return "Error reading from file/stream";
  4658. case status_out_of_memory: return "Could not allocate memory";
  4659. case status_internal_error: return "Internal error occurred";
  4660. case status_unrecognized_tag: return "Could not determine tag type";
  4661. case status_bad_pi: return "Error parsing document declaration/processing instruction";
  4662. case status_bad_comment: return "Error parsing comment";
  4663. case status_bad_cdata: return "Error parsing CDATA section";
  4664. case status_bad_doctype: return "Error parsing document type declaration";
  4665. case status_bad_pcdata: return "Error parsing PCDATA section";
  4666. case status_bad_start_element: return "Error parsing start element tag";
  4667. case status_bad_attribute: return "Error parsing element attribute";
  4668. case status_bad_end_element: return "Error parsing end element tag";
  4669. case status_end_element_mismatch: return "Start-end tags mismatch";
  4670. case status_append_invalid_root: return "Unable to append nodes: root is not an element or document";
  4671. case status_no_document_element: return "No document element found";
  4672. default: return "Unknown error";
  4673. }
  4674. }
  4675. PUGI__FN xml_document::xml_document(): _buffer(0)
  4676. {
  4677. create();
  4678. }
  4679. PUGI__FN xml_document::~xml_document()
  4680. {
  4681. destroy();
  4682. }
  4683. PUGI__FN void xml_document::reset()
  4684. {
  4685. destroy();
  4686. create();
  4687. }
  4688. PUGI__FN void xml_document::reset(const xml_document& proto)
  4689. {
  4690. reset();
  4691. for (xml_node cur = proto.first_child(); cur; cur = cur.next_sibling())
  4692. append_copy(cur);
  4693. }
  4694. PUGI__FN void xml_document::create()
  4695. {
  4696. assert(!_root);
  4697. // initialize sentinel page
  4698. PUGI__STATIC_ASSERT(sizeof(impl::xml_memory_page) + sizeof(impl::xml_document_struct) + impl::xml_memory_page_alignment - sizeof(void*) <= sizeof(_memory));
  4699. // align upwards to page boundary
  4700. void* page_memory = reinterpret_cast<void*>((reinterpret_cast<uintptr_t>(_memory) + (impl::xml_memory_page_alignment - 1)) & ~(impl::xml_memory_page_alignment - 1));
  4701. // prepare page structure
  4702. impl::xml_memory_page* page = impl::xml_memory_page::construct(page_memory);
  4703. assert(page);
  4704. page->busy_size = impl::xml_memory_page_size;
  4705. // allocate new root
  4706. _root = new (reinterpret_cast<char*>(page) + sizeof(impl::xml_memory_page)) impl::xml_document_struct(page);
  4707. _root->prev_sibling_c = _root;
  4708. // setup sentinel page
  4709. page->allocator = static_cast<impl::xml_document_struct*>(_root);
  4710. // verify the document allocation
  4711. assert(reinterpret_cast<char*>(_root) + sizeof(impl::xml_document_struct) <= _memory + sizeof(_memory));
  4712. }
  4713. PUGI__FN void xml_document::destroy()
  4714. {
  4715. assert(_root);
  4716. // destroy static storage
  4717. if (_buffer)
  4718. {
  4719. impl::xml_memory::deallocate(_buffer);
  4720. _buffer = 0;
  4721. }
  4722. // destroy extra buffers (note: no need to destroy linked list nodes, they're allocated using document allocator)
  4723. for (impl::xml_extra_buffer* extra = static_cast<impl::xml_document_struct*>(_root)->extra_buffers; extra; extra = extra->next)
  4724. {
  4725. if (extra->buffer) impl::xml_memory::deallocate(extra->buffer);
  4726. }
  4727. // destroy dynamic storage, leave sentinel page (it's in static memory)
  4728. impl::xml_memory_page* root_page = reinterpret_cast<impl::xml_memory_page*>(_root->header & impl::xml_memory_page_pointer_mask);
  4729. assert(root_page && !root_page->prev);
  4730. assert(reinterpret_cast<char*>(root_page) >= _memory && reinterpret_cast<char*>(root_page) < _memory + sizeof(_memory));
  4731. for (impl::xml_memory_page* page = root_page->next; page; )
  4732. {
  4733. impl::xml_memory_page* next = page->next;
  4734. impl::xml_allocator::deallocate_page(page);
  4735. page = next;
  4736. }
  4737. _root = 0;
  4738. }
  4739. #ifndef PUGIXML_NO_STL
  4740. PUGI__FN xml_parse_result xml_document::load(std::basic_istream<char, std::char_traits<char> >& stream, unsigned int options, xml_encoding encoding)
  4741. {
  4742. reset();
  4743. return impl::load_stream_impl(*this, stream, options, encoding);
  4744. }
  4745. PUGI__FN xml_parse_result xml_document::load(std::basic_istream<wchar_t, std::char_traits<wchar_t> >& stream, unsigned int options)
  4746. {
  4747. reset();
  4748. return impl::load_stream_impl(*this, stream, options, encoding_wchar);
  4749. }
  4750. #endif
  4751. PUGI__FN xml_parse_result xml_document::load_string(const char_t* contents, unsigned int options)
  4752. {
  4753. // Force native encoding (skip autodetection)
  4754. #ifdef PUGIXML_WCHAR_MODE
  4755. xml_encoding encoding = encoding_wchar;
  4756. #else
  4757. xml_encoding encoding = encoding_utf8;
  4758. #endif
  4759. return load_buffer(contents, impl::strlength(contents) * sizeof(char_t), options, encoding);
  4760. }
  4761. PUGI__FN xml_parse_result xml_document::load(const char_t* contents, unsigned int options)
  4762. {
  4763. return load_string(contents, options);
  4764. }
  4765. PUGI__FN xml_parse_result xml_document::load_file(const char* path_, unsigned int options, xml_encoding encoding)
  4766. {
  4767. reset();
  4768. FILE* file = fopen(path_, "rb");
  4769. return impl::load_file_impl(*this, file, options, encoding);
  4770. }
  4771. PUGI__FN xml_parse_result xml_document::load_file(const wchar_t* path_, unsigned int options, xml_encoding encoding)
  4772. {
  4773. reset();
  4774. FILE* file = impl::open_file_wide(path_, L"rb");
  4775. return impl::load_file_impl(*this, file, options, encoding);
  4776. }
  4777. PUGI__FN xml_parse_result xml_document::load_buffer(const void* contents, size_t size, unsigned int options, xml_encoding encoding)
  4778. {
  4779. reset();
  4780. return impl::load_buffer_impl(static_cast<impl::xml_document_struct*>(_root), _root, const_cast<void*>(contents), size, options, encoding, false, false, &_buffer);
  4781. }
  4782. PUGI__FN xml_parse_result xml_document::load_buffer_inplace(void* contents, size_t size, unsigned int options, xml_encoding encoding)
  4783. {
  4784. reset();
  4785. return impl::load_buffer_impl(static_cast<impl::xml_document_struct*>(_root), _root, contents, size, options, encoding, true, false, &_buffer);
  4786. }
  4787. PUGI__FN xml_parse_result xml_document::load_buffer_inplace_own(void* contents, size_t size, unsigned int options, xml_encoding encoding)
  4788. {
  4789. reset();
  4790. return impl::load_buffer_impl(static_cast<impl::xml_document_struct*>(_root), _root, contents, size, options, encoding, true, true, &_buffer);
  4791. }
  4792. PUGI__FN void xml_document::save(xml_writer& writer, const char_t* indent, unsigned int flags, xml_encoding encoding) const
  4793. {
  4794. impl::xml_buffered_writer buffered_writer(writer, encoding);
  4795. if ((flags & format_write_bom) && encoding != encoding_latin1)
  4796. {
  4797. // BOM always represents the codepoint U+FEFF, so just write it in native encoding
  4798. #ifdef PUGIXML_WCHAR_MODE
  4799. unsigned int bom = 0xfeff;
  4800. buffered_writer.write(static_cast<wchar_t>(bom));
  4801. #else
  4802. buffered_writer.write('\xef', '\xbb', '\xbf');
  4803. #endif
  4804. }
  4805. if (!(flags & format_no_declaration) && !impl::has_declaration(_root))
  4806. {
  4807. buffered_writer.write_string(PUGIXML_TEXT("<?xml version=\"1.0\""));
  4808. if (encoding == encoding_latin1) buffered_writer.write_string(PUGIXML_TEXT(" encoding=\"ISO-8859-1\""));
  4809. buffered_writer.write('?', '>');
  4810. if (!(flags & format_raw)) buffered_writer.write('\n');
  4811. }
  4812. impl::node_output(buffered_writer, _root, indent, flags, 0);
  4813. }
  4814. #ifndef PUGIXML_NO_STL
  4815. PUGI__FN void xml_document::save(std::basic_ostream<char, std::char_traits<char> >& stream, const char_t* indent, unsigned int flags, xml_encoding encoding) const
  4816. {
  4817. xml_writer_stream writer(stream);
  4818. save(writer, indent, flags, encoding);
  4819. }
  4820. PUGI__FN void xml_document::save(std::basic_ostream<wchar_t, std::char_traits<wchar_t> >& stream, const char_t* indent, unsigned int flags) const
  4821. {
  4822. xml_writer_stream writer(stream);
  4823. save(writer, indent, flags, encoding_wchar);
  4824. }
  4825. #endif
  4826. PUGI__FN bool xml_document::save_file(const char* path_, const char_t* indent, unsigned int flags, xml_encoding encoding) const
  4827. {
  4828. FILE* file = fopen(path_, (flags & format_save_file_text) ? "w" : "wb");
  4829. return impl::save_file_impl(*this, file, indent, flags, encoding);
  4830. }
  4831. PUGI__FN bool xml_document::save_file(const wchar_t* path_, const char_t* indent, unsigned int flags, xml_encoding encoding) const
  4832. {
  4833. FILE* file = impl::open_file_wide(path_, (flags & format_save_file_text) ? L"w" : L"wb");
  4834. return impl::save_file_impl(*this, file, indent, flags, encoding);
  4835. }
  4836. PUGI__FN xml_node xml_document::document_element() const
  4837. {
  4838. assert(_root);
  4839. for (xml_node_struct* i = _root->first_child; i; i = i->next_sibling)
  4840. if (PUGI__NODETYPE(i) == node_element)
  4841. return xml_node(i);
  4842. return xml_node();
  4843. }
  4844. #ifndef PUGIXML_NO_STL
  4845. PUGI__FN std::string PUGIXML_FUNCTION as_utf8(const wchar_t* str)
  4846. {
  4847. assert(str);
  4848. return impl::as_utf8_impl(str, impl::strlength_wide(str));
  4849. }
  4850. PUGI__FN std::string PUGIXML_FUNCTION as_utf8(const std::basic_string<wchar_t>& str)
  4851. {
  4852. return impl::as_utf8_impl(str.c_str(), str.size());
  4853. }
  4854. PUGI__FN std::basic_string<wchar_t> PUGIXML_FUNCTION as_wide(const char* str)
  4855. {
  4856. assert(str);
  4857. return impl::as_wide_impl(str, strlen(str));
  4858. }
  4859. PUGI__FN std::basic_string<wchar_t> PUGIXML_FUNCTION as_wide(const std::string& str)
  4860. {
  4861. return impl::as_wide_impl(str.c_str(), str.size());
  4862. }
  4863. #endif
  4864. PUGI__FN void PUGIXML_FUNCTION set_memory_management_functions(allocation_function allocate, deallocation_function deallocate)
  4865. {
  4866. impl::xml_memory::allocate = allocate;
  4867. impl::xml_memory::deallocate = deallocate;
  4868. }
  4869. PUGI__FN allocation_function PUGIXML_FUNCTION get_memory_allocation_function()
  4870. {
  4871. return impl::xml_memory::allocate;
  4872. }
  4873. PUGI__FN deallocation_function PUGIXML_FUNCTION get_memory_deallocation_function()
  4874. {
  4875. return impl::xml_memory::deallocate;
  4876. }
  4877. }
  4878. #if !defined(PUGIXML_NO_STL) && (defined(_MSC_VER) || defined(__ICC))
  4879. namespace std
  4880. {
  4881. // Workarounds for (non-standard) iterator category detection for older versions (MSVC7/IC8 and earlier)
  4882. PUGI__FN std::bidirectional_iterator_tag _Iter_cat(const pugi::xml_node_iterator&)
  4883. {
  4884. return std::bidirectional_iterator_tag();
  4885. }
  4886. PUGI__FN std::bidirectional_iterator_tag _Iter_cat(const pugi::xml_attribute_iterator&)
  4887. {
  4888. return std::bidirectional_iterator_tag();
  4889. }
  4890. PUGI__FN std::bidirectional_iterator_tag _Iter_cat(const pugi::xml_named_node_iterator&)
  4891. {
  4892. return std::bidirectional_iterator_tag();
  4893. }
  4894. }
  4895. #endif
  4896. #if !defined(PUGIXML_NO_STL) && defined(__SUNPRO_CC)
  4897. namespace std
  4898. {
  4899. // Workarounds for (non-standard) iterator category detection
  4900. PUGI__FN std::bidirectional_iterator_tag __iterator_category(const pugi::xml_node_iterator&)
  4901. {
  4902. return std::bidirectional_iterator_tag();
  4903. }
  4904. PUGI__FN std::bidirectional_iterator_tag __iterator_category(const pugi::xml_attribute_iterator&)
  4905. {
  4906. return std::bidirectional_iterator_tag();
  4907. }
  4908. PUGI__FN std::bidirectional_iterator_tag __iterator_category(const pugi::xml_named_node_iterator&)
  4909. {
  4910. return std::bidirectional_iterator_tag();
  4911. }
  4912. }
  4913. #endif
  4914. #ifndef PUGIXML_NO_XPATH
  4915. // STL replacements
  4916. PUGI__NS_BEGIN
  4917. struct equal_to
  4918. {
  4919. template <typename T> bool operator()(const T& lhs, const T& rhs) const
  4920. {
  4921. return lhs == rhs;
  4922. }
  4923. };
  4924. struct not_equal_to
  4925. {
  4926. template <typename T> bool operator()(const T& lhs, const T& rhs) const
  4927. {
  4928. return lhs != rhs;
  4929. }
  4930. };
  4931. struct less
  4932. {
  4933. template <typename T> bool operator()(const T& lhs, const T& rhs) const
  4934. {
  4935. return lhs < rhs;
  4936. }
  4937. };
  4938. struct less_equal
  4939. {
  4940. template <typename T> bool operator()(const T& lhs, const T& rhs) const
  4941. {
  4942. return lhs <= rhs;
  4943. }
  4944. };
  4945. template <typename T> void swap(T& lhs, T& rhs)
  4946. {
  4947. T temp = lhs;
  4948. lhs = rhs;
  4949. rhs = temp;
  4950. }
  4951. template <typename I, typename Pred> I min_element(I begin, I end, const Pred& pred)
  4952. {
  4953. I result = begin;
  4954. for (I it = begin + 1; it != end; ++it)
  4955. if (pred(*it, *result))
  4956. result = it;
  4957. return result;
  4958. }
  4959. template <typename I> void reverse(I begin, I end)
  4960. {
  4961. while (end - begin > 1) swap(*begin++, *--end);
  4962. }
  4963. template <typename I> I unique(I begin, I end)
  4964. {
  4965. // fast skip head
  4966. while (end - begin > 1 && *begin != *(begin + 1)) begin++;
  4967. if (begin == end) return begin;
  4968. // last written element
  4969. I write = begin++;
  4970. // merge unique elements
  4971. while (begin != end)
  4972. {
  4973. if (*begin != *write)
  4974. *++write = *begin++;
  4975. else
  4976. begin++;
  4977. }
  4978. // past-the-end (write points to live element)
  4979. return write + 1;
  4980. }
  4981. template <typename I> void copy_backwards(I begin, I end, I target)
  4982. {
  4983. while (begin != end) *--target = *--end;
  4984. }
  4985. template <typename I, typename Pred, typename T> void insertion_sort(I begin, I end, const Pred& pred, T*)
  4986. {
  4987. assert(begin != end);
  4988. for (I it = begin + 1; it != end; ++it)
  4989. {
  4990. T val = *it;
  4991. if (pred(val, *begin))
  4992. {
  4993. // move to front
  4994. copy_backwards(begin, it, it + 1);
  4995. *begin = val;
  4996. }
  4997. else
  4998. {
  4999. I hole = it;
  5000. // move hole backwards
  5001. while (pred(val, *(hole - 1)))
  5002. {
  5003. *hole = *(hole - 1);
  5004. hole--;
  5005. }
  5006. // fill hole with element
  5007. *hole = val;
  5008. }
  5009. }
  5010. }
  5011. // std variant for elements with ==
  5012. template <typename I, typename Pred> void partition(I begin, I middle, I end, const Pred& pred, I* out_eqbeg, I* out_eqend)
  5013. {
  5014. I eqbeg = middle, eqend = middle + 1;
  5015. // expand equal range
  5016. while (eqbeg != begin && *(eqbeg - 1) == *eqbeg) --eqbeg;
  5017. while (eqend != end && *eqend == *eqbeg) ++eqend;
  5018. // process outer elements
  5019. I ltend = eqbeg, gtbeg = eqend;
  5020. for (;;)
  5021. {
  5022. // find the element from the right side that belongs to the left one
  5023. for (; gtbeg != end; ++gtbeg)
  5024. if (!pred(*eqbeg, *gtbeg))
  5025. {
  5026. if (*gtbeg == *eqbeg) swap(*gtbeg, *eqend++);
  5027. else break;
  5028. }
  5029. // find the element from the left side that belongs to the right one
  5030. for (; ltend != begin; --ltend)
  5031. if (!pred(*(ltend - 1), *eqbeg))
  5032. {
  5033. if (*eqbeg == *(ltend - 1)) swap(*(ltend - 1), *--eqbeg);
  5034. else break;
  5035. }
  5036. // scanned all elements
  5037. if (gtbeg == end && ltend == begin)
  5038. {
  5039. *out_eqbeg = eqbeg;
  5040. *out_eqend = eqend;
  5041. return;
  5042. }
  5043. // make room for elements by moving equal area
  5044. if (gtbeg == end)
  5045. {
  5046. if (--ltend != --eqbeg) swap(*ltend, *eqbeg);
  5047. swap(*eqbeg, *--eqend);
  5048. }
  5049. else if (ltend == begin)
  5050. {
  5051. if (eqend != gtbeg) swap(*eqbeg, *eqend);
  5052. ++eqend;
  5053. swap(*gtbeg++, *eqbeg++);
  5054. }
  5055. else swap(*gtbeg++, *--ltend);
  5056. }
  5057. }
  5058. template <typename I, typename Pred> void median3(I first, I middle, I last, const Pred& pred)
  5059. {
  5060. if (pred(*middle, *first)) swap(*middle, *first);
  5061. if (pred(*last, *middle)) swap(*last, *middle);
  5062. if (pred(*middle, *first)) swap(*middle, *first);
  5063. }
  5064. template <typename I, typename Pred> void median(I first, I middle, I last, const Pred& pred)
  5065. {
  5066. if (last - first <= 40)
  5067. {
  5068. // median of three for small chunks
  5069. median3(first, middle, last, pred);
  5070. }
  5071. else
  5072. {
  5073. // median of nine
  5074. size_t step = (last - first + 1) / 8;
  5075. median3(first, first + step, first + 2 * step, pred);
  5076. median3(middle - step, middle, middle + step, pred);
  5077. median3(last - 2 * step, last - step, last, pred);
  5078. median3(first + step, middle, last - step, pred);
  5079. }
  5080. }
  5081. template <typename I, typename Pred> void sort(I begin, I end, const Pred& pred)
  5082. {
  5083. // sort large chunks
  5084. while (end - begin > 32)
  5085. {
  5086. // find median element
  5087. I middle = begin + (end - begin) / 2;
  5088. median(begin, middle, end - 1, pred);
  5089. // partition in three chunks (< = >)
  5090. I eqbeg, eqend;
  5091. partition(begin, middle, end, pred, &eqbeg, &eqend);
  5092. // loop on larger half
  5093. if (eqbeg - begin > end - eqend)
  5094. {
  5095. sort(eqend, end, pred);
  5096. end = eqbeg;
  5097. }
  5098. else
  5099. {
  5100. sort(begin, eqbeg, pred);
  5101. begin = eqend;
  5102. }
  5103. }
  5104. // insertion sort small chunk
  5105. if (begin != end) insertion_sort(begin, end, pred, &*begin);
  5106. }
  5107. PUGI__NS_END
  5108. // Allocator used for AST and evaluation stacks
  5109. PUGI__NS_BEGIN
  5110. struct xpath_memory_block
  5111. {
  5112. xpath_memory_block* next;
  5113. size_t capacity;
  5114. char data[
  5115. #ifdef PUGIXML_MEMORY_XPATH_PAGE_SIZE
  5116. PUGIXML_MEMORY_XPATH_PAGE_SIZE
  5117. #else
  5118. 4096
  5119. #endif
  5120. ];
  5121. };
  5122. class xpath_allocator
  5123. {
  5124. xpath_memory_block* _root;
  5125. size_t _root_size;
  5126. public:
  5127. #ifdef PUGIXML_NO_EXCEPTIONS
  5128. jmp_buf* error_handler;
  5129. #endif
  5130. xpath_allocator(xpath_memory_block* root, size_t root_size = 0): _root(root), _root_size(root_size)
  5131. {
  5132. #ifdef PUGIXML_NO_EXCEPTIONS
  5133. error_handler = 0;
  5134. #endif
  5135. }
  5136. void* allocate_nothrow(size_t size)
  5137. {
  5138. // align size so that we're able to store pointers in subsequent blocks
  5139. size = (size + sizeof(void*) - 1) & ~(sizeof(void*) - 1);
  5140. if (_root_size + size <= _root->capacity)
  5141. {
  5142. void* buf = _root->data + _root_size;
  5143. _root_size += size;
  5144. return buf;
  5145. }
  5146. else
  5147. {
  5148. // make sure we have at least 1/4th of the page free after allocation to satisfy subsequent allocation requests
  5149. size_t block_capacity_base = sizeof(_root->data);
  5150. size_t block_capacity_req = size + block_capacity_base / 4;
  5151. size_t block_capacity = (block_capacity_base > block_capacity_req) ? block_capacity_base : block_capacity_req;
  5152. size_t block_size = block_capacity + offsetof(xpath_memory_block, data);
  5153. xpath_memory_block* block = static_cast<xpath_memory_block*>(xml_memory::allocate(block_size));
  5154. if (!block) return 0;
  5155. block->next = _root;
  5156. block->capacity = block_capacity;
  5157. _root = block;
  5158. _root_size = size;
  5159. return block->data;
  5160. }
  5161. }
  5162. void* allocate(size_t size)
  5163. {
  5164. void* result = allocate_nothrow(size);
  5165. if (!result)
  5166. {
  5167. #ifdef PUGIXML_NO_EXCEPTIONS
  5168. assert(error_handler);
  5169. longjmp(*error_handler, 1);
  5170. #else
  5171. throw std::bad_alloc();
  5172. #endif
  5173. }
  5174. return result;
  5175. }
  5176. void* reallocate(void* ptr, size_t old_size, size_t new_size)
  5177. {
  5178. // align size so that we're able to store pointers in subsequent blocks
  5179. old_size = (old_size + sizeof(void*) - 1) & ~(sizeof(void*) - 1);
  5180. new_size = (new_size + sizeof(void*) - 1) & ~(sizeof(void*) - 1);
  5181. // we can only reallocate the last object
  5182. assert(ptr == 0 || static_cast<char*>(ptr) + old_size == _root->data + _root_size);
  5183. // adjust root size so that we have not allocated the object at all
  5184. bool only_object = (_root_size == old_size);
  5185. if (ptr) _root_size -= old_size;
  5186. // allocate a new version (this will obviously reuse the memory if possible)
  5187. void* result = allocate(new_size);
  5188. assert(result);
  5189. // we have a new block
  5190. if (result != ptr && ptr)
  5191. {
  5192. // copy old data
  5193. assert(new_size >= old_size);
  5194. memcpy(result, ptr, old_size);
  5195. // free the previous page if it had no other objects
  5196. if (only_object)
  5197. {
  5198. assert(_root->data == result);
  5199. assert(_root->next);
  5200. xpath_memory_block* next = _root->next->next;
  5201. if (next)
  5202. {
  5203. // deallocate the whole page, unless it was the first one
  5204. xml_memory::deallocate(_root->next);
  5205. _root->next = next;
  5206. }
  5207. }
  5208. }
  5209. return result;
  5210. }
  5211. void revert(const xpath_allocator& state)
  5212. {
  5213. // free all new pages
  5214. xpath_memory_block* cur = _root;
  5215. while (cur != state._root)
  5216. {
  5217. xpath_memory_block* next = cur->next;
  5218. xml_memory::deallocate(cur);
  5219. cur = next;
  5220. }
  5221. // restore state
  5222. _root = state._root;
  5223. _root_size = state._root_size;
  5224. }
  5225. void release()
  5226. {
  5227. xpath_memory_block* cur = _root;
  5228. assert(cur);
  5229. while (cur->next)
  5230. {
  5231. xpath_memory_block* next = cur->next;
  5232. xml_memory::deallocate(cur);
  5233. cur = next;
  5234. }
  5235. }
  5236. };
  5237. struct xpath_allocator_capture
  5238. {
  5239. xpath_allocator_capture(xpath_allocator* alloc): _target(alloc), _state(*alloc)
  5240. {
  5241. }
  5242. ~xpath_allocator_capture()
  5243. {
  5244. _target->revert(_state);
  5245. }
  5246. xpath_allocator* _target;
  5247. xpath_allocator _state;
  5248. };
  5249. struct xpath_stack
  5250. {
  5251. xpath_allocator* result;
  5252. xpath_allocator* temp;
  5253. };
  5254. struct xpath_stack_data
  5255. {
  5256. xpath_memory_block blocks[2];
  5257. xpath_allocator result;
  5258. xpath_allocator temp;
  5259. xpath_stack stack;
  5260. #ifdef PUGIXML_NO_EXCEPTIONS
  5261. jmp_buf error_handler;
  5262. #endif
  5263. xpath_stack_data(): result(blocks + 0), temp(blocks + 1)
  5264. {
  5265. blocks[0].next = blocks[1].next = 0;
  5266. blocks[0].capacity = blocks[1].capacity = sizeof(blocks[0].data);
  5267. stack.result = &result;
  5268. stack.temp = &temp;
  5269. #ifdef PUGIXML_NO_EXCEPTIONS
  5270. result.error_handler = temp.error_handler = &error_handler;
  5271. #endif
  5272. }
  5273. ~xpath_stack_data()
  5274. {
  5275. result.release();
  5276. temp.release();
  5277. }
  5278. };
  5279. PUGI__NS_END
  5280. // String class
  5281. PUGI__NS_BEGIN
  5282. class xpath_string
  5283. {
  5284. const char_t* _buffer;
  5285. bool _uses_heap;
  5286. size_t _length_heap;
  5287. static char_t* duplicate_string(const char_t* string, size_t length, xpath_allocator* alloc)
  5288. {
  5289. char_t* result = static_cast<char_t*>(alloc->allocate((length + 1) * sizeof(char_t)));
  5290. assert(result);
  5291. memcpy(result, string, length * sizeof(char_t));
  5292. result[length] = 0;
  5293. return result;
  5294. }
  5295. xpath_string(const char_t* buffer, bool uses_heap_, size_t length_heap): _buffer(buffer), _uses_heap(uses_heap_), _length_heap(length_heap)
  5296. {
  5297. }
  5298. public:
  5299. static xpath_string from_const(const char_t* str)
  5300. {
  5301. return xpath_string(str, false, 0);
  5302. }
  5303. static xpath_string from_heap_preallocated(const char_t* begin, const char_t* end)
  5304. {
  5305. assert(begin <= end && *end == 0);
  5306. return xpath_string(begin, true, static_cast<size_t>(end - begin));
  5307. }
  5308. static xpath_string from_heap(const char_t* begin, const char_t* end, xpath_allocator* alloc)
  5309. {
  5310. assert(begin <= end);
  5311. size_t length = static_cast<size_t>(end - begin);
  5312. return length == 0 ? xpath_string() : xpath_string(duplicate_string(begin, length, alloc), true, length);
  5313. }
  5314. xpath_string(): _buffer(PUGIXML_TEXT("")), _uses_heap(false), _length_heap(0)
  5315. {
  5316. }
  5317. void append(const xpath_string& o, xpath_allocator* alloc)
  5318. {
  5319. // skip empty sources
  5320. if (!*o._buffer) return;
  5321. // fast append for constant empty target and constant source
  5322. if (!*_buffer && !_uses_heap && !o._uses_heap)
  5323. {
  5324. _buffer = o._buffer;
  5325. }
  5326. else
  5327. {
  5328. // need to make heap copy
  5329. size_t target_length = length();
  5330. size_t source_length = o.length();
  5331. size_t result_length = target_length + source_length;
  5332. // allocate new buffer
  5333. char_t* result = static_cast<char_t*>(alloc->reallocate(_uses_heap ? const_cast<char_t*>(_buffer) : 0, (target_length + 1) * sizeof(char_t), (result_length + 1) * sizeof(char_t)));
  5334. assert(result);
  5335. // append first string to the new buffer in case there was no reallocation
  5336. if (!_uses_heap) memcpy(result, _buffer, target_length * sizeof(char_t));
  5337. // append second string to the new buffer
  5338. memcpy(result + target_length, o._buffer, source_length * sizeof(char_t));
  5339. result[result_length] = 0;
  5340. // finalize
  5341. _buffer = result;
  5342. _uses_heap = true;
  5343. _length_heap = result_length;
  5344. }
  5345. }
  5346. const char_t* c_str() const
  5347. {
  5348. return _buffer;
  5349. }
  5350. size_t length() const
  5351. {
  5352. return _uses_heap ? _length_heap : strlength(_buffer);
  5353. }
  5354. char_t* data(xpath_allocator* alloc)
  5355. {
  5356. // make private heap copy
  5357. if (!_uses_heap)
  5358. {
  5359. size_t length_ = strlength(_buffer);
  5360. _buffer = duplicate_string(_buffer, length_, alloc);
  5361. _uses_heap = true;
  5362. _length_heap = length_;
  5363. }
  5364. return const_cast<char_t*>(_buffer);
  5365. }
  5366. bool empty() const
  5367. {
  5368. return *_buffer == 0;
  5369. }
  5370. bool operator==(const xpath_string& o) const
  5371. {
  5372. return strequal(_buffer, o._buffer);
  5373. }
  5374. bool operator!=(const xpath_string& o) const
  5375. {
  5376. return !strequal(_buffer, o._buffer);
  5377. }
  5378. bool uses_heap() const
  5379. {
  5380. return _uses_heap;
  5381. }
  5382. };
  5383. PUGI__NS_END
  5384. PUGI__NS_BEGIN
  5385. PUGI__FN bool starts_with(const char_t* string, const char_t* pattern)
  5386. {
  5387. while (*pattern && *string == *pattern)
  5388. {
  5389. string++;
  5390. pattern++;
  5391. }
  5392. return *pattern == 0;
  5393. }
  5394. PUGI__FN const char_t* find_char(const char_t* s, char_t c)
  5395. {
  5396. #ifdef PUGIXML_WCHAR_MODE
  5397. return wcschr(s, c);
  5398. #else
  5399. return strchr(s, c);
  5400. #endif
  5401. }
  5402. PUGI__FN const char_t* find_substring(const char_t* s, const char_t* p)
  5403. {
  5404. #ifdef PUGIXML_WCHAR_MODE
  5405. // MSVC6 wcsstr bug workaround (if s is empty it always returns 0)
  5406. return (*p == 0) ? s : wcsstr(s, p);
  5407. #else
  5408. return strstr(s, p);
  5409. #endif
  5410. }
  5411. // Converts symbol to lower case, if it is an ASCII one
  5412. PUGI__FN char_t tolower_ascii(char_t ch)
  5413. {
  5414. return static_cast<unsigned int>(ch - 'A') < 26 ? static_cast<char_t>(ch | ' ') : ch;
  5415. }
  5416. PUGI__FN xpath_string string_value(const xpath_node& na, xpath_allocator* alloc)
  5417. {
  5418. if (na.attribute())
  5419. return xpath_string::from_const(na.attribute().value());
  5420. else
  5421. {
  5422. xml_node n = na.node();
  5423. switch (n.type())
  5424. {
  5425. case node_pcdata:
  5426. case node_cdata:
  5427. case node_comment:
  5428. case node_pi:
  5429. return xpath_string::from_const(n.value());
  5430. case node_document:
  5431. case node_element:
  5432. {
  5433. xpath_string result;
  5434. xml_node cur = n.first_child();
  5435. while (cur && cur != n)
  5436. {
  5437. if (cur.type() == node_pcdata || cur.type() == node_cdata)
  5438. result.append(xpath_string::from_const(cur.value()), alloc);
  5439. if (cur.first_child())
  5440. cur = cur.first_child();
  5441. else if (cur.next_sibling())
  5442. cur = cur.next_sibling();
  5443. else
  5444. {
  5445. while (!cur.next_sibling() && cur != n)
  5446. cur = cur.parent();
  5447. if (cur != n) cur = cur.next_sibling();
  5448. }
  5449. }
  5450. return result;
  5451. }
  5452. default:
  5453. return xpath_string();
  5454. }
  5455. }
  5456. }
  5457. PUGI__FN bool node_is_before_sibling(xml_node_struct* ln, xml_node_struct* rn)
  5458. {
  5459. assert(ln->parent == rn->parent);
  5460. // there is no common ancestor (the shared parent is null), nodes are from different documents
  5461. if (!ln->parent) return ln < rn;
  5462. // determine sibling order
  5463. xml_node_struct* ls = ln;
  5464. xml_node_struct* rs = rn;
  5465. while (ls && rs)
  5466. {
  5467. if (ls == rn) return true;
  5468. if (rs == ln) return false;
  5469. ls = ls->next_sibling;
  5470. rs = rs->next_sibling;
  5471. }
  5472. // if rn sibling chain ended ln must be before rn
  5473. return !rs;
  5474. }
  5475. PUGI__FN bool node_is_before(xml_node_struct* ln, xml_node_struct* rn)
  5476. {
  5477. // find common ancestor at the same depth, if any
  5478. xml_node_struct* lp = ln;
  5479. xml_node_struct* rp = rn;
  5480. while (lp && rp && lp->parent != rp->parent)
  5481. {
  5482. lp = lp->parent;
  5483. rp = rp->parent;
  5484. }
  5485. // parents are the same!
  5486. if (lp && rp) return node_is_before_sibling(lp, rp);
  5487. // nodes are at different depths, need to normalize heights
  5488. bool left_higher = !lp;
  5489. while (lp)
  5490. {
  5491. lp = lp->parent;
  5492. ln = ln->parent;
  5493. }
  5494. while (rp)
  5495. {
  5496. rp = rp->parent;
  5497. rn = rn->parent;
  5498. }
  5499. // one node is the ancestor of the other
  5500. if (ln == rn) return left_higher;
  5501. // find common ancestor... again
  5502. while (ln->parent != rn->parent)
  5503. {
  5504. ln = ln->parent;
  5505. rn = rn->parent;
  5506. }
  5507. return node_is_before_sibling(ln, rn);
  5508. }
  5509. PUGI__FN bool node_is_ancestor(xml_node_struct* parent, xml_node_struct* node)
  5510. {
  5511. while (node && node != parent) node = node->parent;
  5512. return parent && node == parent;
  5513. }
  5514. PUGI__FN const void* document_buffer_order(const xpath_node& xnode)
  5515. {
  5516. xml_node_struct* node = xnode.node().internal_object();
  5517. if (node)
  5518. {
  5519. if ((get_document(node).header & xml_memory_page_contents_shared_mask) == 0)
  5520. {
  5521. if (node->name && (node->header & impl::xml_memory_page_name_allocated_or_shared_mask) == 0) return node->name;
  5522. if (node->value && (node->header & impl::xml_memory_page_value_allocated_or_shared_mask) == 0) return node->value;
  5523. }
  5524. return 0;
  5525. }
  5526. xml_attribute_struct* attr = xnode.attribute().internal_object();
  5527. if (attr)
  5528. {
  5529. if ((get_document(attr).header & xml_memory_page_contents_shared_mask) == 0)
  5530. {
  5531. if ((attr->header & impl::xml_memory_page_name_allocated_or_shared_mask) == 0) return attr->name;
  5532. if ((attr->header & impl::xml_memory_page_value_allocated_or_shared_mask) == 0) return attr->value;
  5533. }
  5534. return 0;
  5535. }
  5536. return 0;
  5537. }
  5538. struct document_order_comparator
  5539. {
  5540. bool operator()(const xpath_node& lhs, const xpath_node& rhs) const
  5541. {
  5542. // optimized document order based check
  5543. const void* lo = document_buffer_order(lhs);
  5544. const void* ro = document_buffer_order(rhs);
  5545. if (lo && ro) return lo < ro;
  5546. // slow comparison
  5547. xml_node ln = lhs.node(), rn = rhs.node();
  5548. // compare attributes
  5549. if (lhs.attribute() && rhs.attribute())
  5550. {
  5551. // shared parent
  5552. if (lhs.parent() == rhs.parent())
  5553. {
  5554. // determine sibling order
  5555. for (xml_attribute a = lhs.attribute(); a; a = a.next_attribute())
  5556. if (a == rhs.attribute())
  5557. return true;
  5558. return false;
  5559. }
  5560. // compare attribute parents
  5561. ln = lhs.parent();
  5562. rn = rhs.parent();
  5563. }
  5564. else if (lhs.attribute())
  5565. {
  5566. // attributes go after the parent element
  5567. if (lhs.parent() == rhs.node()) return false;
  5568. ln = lhs.parent();
  5569. }
  5570. else if (rhs.attribute())
  5571. {
  5572. // attributes go after the parent element
  5573. if (rhs.parent() == lhs.node()) return true;
  5574. rn = rhs.parent();
  5575. }
  5576. if (ln == rn) return false;
  5577. if (!ln || !rn) return ln < rn;
  5578. return node_is_before(ln.internal_object(), rn.internal_object());
  5579. }
  5580. };
  5581. struct duplicate_comparator
  5582. {
  5583. bool operator()(const xpath_node& lhs, const xpath_node& rhs) const
  5584. {
  5585. if (lhs.attribute()) return rhs.attribute() ? lhs.attribute() < rhs.attribute() : true;
  5586. else return rhs.attribute() ? false : lhs.node() < rhs.node();
  5587. }
  5588. };
  5589. PUGI__FN double gen_nan()
  5590. {
  5591. #if defined(__STDC_IEC_559__) || ((FLT_RADIX - 0 == 2) && (FLT_MAX_EXP - 0 == 128) && (FLT_MANT_DIG - 0 == 24))
  5592. union { float f; uint32_t i; } u[sizeof(float) == sizeof(uint32_t) ? 1 : -1];
  5593. u[0].i = 0x7fc00000;
  5594. return u[0].f;
  5595. #else
  5596. // fallback
  5597. const volatile double zero = 0.0;
  5598. return zero / zero;
  5599. #endif
  5600. }
  5601. PUGI__FN bool is_nan(double value)
  5602. {
  5603. #if defined(PUGI__MSVC_CRT_VERSION) || defined(__BORLANDC__)
  5604. return !!_isnan(value);
  5605. #elif defined(fpclassify) && defined(FP_NAN)
  5606. return fpclassify(value) == FP_NAN;
  5607. #else
  5608. // fallback
  5609. const volatile double v = value;
  5610. return v != v;
  5611. #endif
  5612. }
  5613. PUGI__FN const char_t* convert_number_to_string_special(double value)
  5614. {
  5615. #if defined(PUGI__MSVC_CRT_VERSION) || defined(__BORLANDC__)
  5616. if (_finite(value)) return (value == 0) ? PUGIXML_TEXT("0") : 0;
  5617. if (_isnan(value)) return PUGIXML_TEXT("NaN");
  5618. return value > 0 ? PUGIXML_TEXT("Infinity") : PUGIXML_TEXT("-Infinity");
  5619. #elif defined(fpclassify) && defined(FP_NAN) && defined(FP_INFINITE) && defined(FP_ZERO)
  5620. switch (fpclassify(value))
  5621. {
  5622. case FP_NAN:
  5623. return PUGIXML_TEXT("NaN");
  5624. case FP_INFINITE:
  5625. return value > 0 ? PUGIXML_TEXT("Infinity") : PUGIXML_TEXT("-Infinity");
  5626. case FP_ZERO:
  5627. return PUGIXML_TEXT("0");
  5628. default:
  5629. return 0;
  5630. }
  5631. #else
  5632. // fallback
  5633. const volatile double v = value;
  5634. if (v == 0) return PUGIXML_TEXT("0");
  5635. if (v != v) return PUGIXML_TEXT("NaN");
  5636. if (v * 2 == v) return value > 0 ? PUGIXML_TEXT("Infinity") : PUGIXML_TEXT("-Infinity");
  5637. return 0;
  5638. #endif
  5639. }
  5640. PUGI__FN bool convert_number_to_boolean(double value)
  5641. {
  5642. return (value != 0 && !is_nan(value));
  5643. }
  5644. PUGI__FN void truncate_zeros(char* begin, char* end)
  5645. {
  5646. while (begin != end && end[-1] == '0') end--;
  5647. *end = 0;
  5648. }
  5649. // gets mantissa digits in the form of 0.xxxxx with 0. implied and the exponent
  5650. #if defined(PUGI__MSVC_CRT_VERSION) && PUGI__MSVC_CRT_VERSION >= 1400 && !defined(_WIN32_WCE)
  5651. PUGI__FN void convert_number_to_mantissa_exponent(double value, char* buffer, size_t buffer_size, char** out_mantissa, int* out_exponent)
  5652. {
  5653. // get base values
  5654. int sign, exponent;
  5655. _ecvt_s(buffer, buffer_size, value, DBL_DIG + 1, &exponent, &sign);
  5656. // truncate redundant zeros
  5657. truncate_zeros(buffer, buffer + strlen(buffer));
  5658. // fill results
  5659. *out_mantissa = buffer;
  5660. *out_exponent = exponent;
  5661. }
  5662. #else
  5663. PUGI__FN void convert_number_to_mantissa_exponent(double value, char* buffer, size_t buffer_size, char** out_mantissa, int* out_exponent)
  5664. {
  5665. // get a scientific notation value with IEEE DBL_DIG decimals
  5666. sprintf(buffer, "%.*e", DBL_DIG, value);
  5667. assert(strlen(buffer) < buffer_size);
  5668. (void)!buffer_size;
  5669. // get the exponent (possibly negative)
  5670. char* exponent_string = strchr(buffer, 'e');
  5671. assert(exponent_string);
  5672. int exponent = atoi(exponent_string + 1);
  5673. // extract mantissa string: skip sign
  5674. char* mantissa = buffer[0] == '-' ? buffer + 1 : buffer;
  5675. assert(mantissa[0] != '0' && mantissa[1] == '.');
  5676. // divide mantissa by 10 to eliminate integer part
  5677. mantissa[1] = mantissa[0];
  5678. mantissa++;
  5679. exponent++;
  5680. // remove extra mantissa digits and zero-terminate mantissa
  5681. truncate_zeros(mantissa, exponent_string);
  5682. // fill results
  5683. *out_mantissa = mantissa;
  5684. *out_exponent = exponent;
  5685. }
  5686. #endif
  5687. PUGI__FN xpath_string convert_number_to_string(double value, xpath_allocator* alloc)
  5688. {
  5689. // try special number conversion
  5690. const char_t* special = convert_number_to_string_special(value);
  5691. if (special) return xpath_string::from_const(special);
  5692. // get mantissa + exponent form
  5693. char mantissa_buffer[32];
  5694. char* mantissa;
  5695. int exponent;
  5696. convert_number_to_mantissa_exponent(value, mantissa_buffer, sizeof(mantissa_buffer), &mantissa, &exponent);
  5697. // allocate a buffer of suitable length for the number
  5698. size_t result_size = strlen(mantissa_buffer) + (exponent > 0 ? exponent : -exponent) + 4;
  5699. char_t* result = static_cast<char_t*>(alloc->allocate(sizeof(char_t) * result_size));
  5700. assert(result);
  5701. // make the number!
  5702. char_t* s = result;
  5703. // sign
  5704. if (value < 0) *s++ = '-';
  5705. // integer part
  5706. if (exponent <= 0)
  5707. {
  5708. *s++ = '0';
  5709. }
  5710. else
  5711. {
  5712. while (exponent > 0)
  5713. {
  5714. assert(*mantissa == 0 || static_cast<unsigned int>(static_cast<unsigned int>(*mantissa) - '0') <= 9);
  5715. *s++ = *mantissa ? *mantissa++ : '0';
  5716. exponent--;
  5717. }
  5718. }
  5719. // fractional part
  5720. if (*mantissa)
  5721. {
  5722. // decimal point
  5723. *s++ = '.';
  5724. // extra zeroes from negative exponent
  5725. while (exponent < 0)
  5726. {
  5727. *s++ = '0';
  5728. exponent++;
  5729. }
  5730. // extra mantissa digits
  5731. while (*mantissa)
  5732. {
  5733. assert(static_cast<unsigned int>(*mantissa - '0') <= 9);
  5734. *s++ = *mantissa++;
  5735. }
  5736. }
  5737. // zero-terminate
  5738. assert(s < result + result_size);
  5739. *s = 0;
  5740. return xpath_string::from_heap_preallocated(result, s);
  5741. }
  5742. PUGI__FN bool check_string_to_number_format(const char_t* string)
  5743. {
  5744. // parse leading whitespace
  5745. while (PUGI__IS_CHARTYPE(*string, ct_space)) ++string;
  5746. // parse sign
  5747. if (*string == '-') ++string;
  5748. if (!*string) return false;
  5749. // if there is no integer part, there should be a decimal part with at least one digit
  5750. if (!PUGI__IS_CHARTYPEX(string[0], ctx_digit) && (string[0] != '.' || !PUGI__IS_CHARTYPEX(string[1], ctx_digit))) return false;
  5751. // parse integer part
  5752. while (PUGI__IS_CHARTYPEX(*string, ctx_digit)) ++string;
  5753. // parse decimal part
  5754. if (*string == '.')
  5755. {
  5756. ++string;
  5757. while (PUGI__IS_CHARTYPEX(*string, ctx_digit)) ++string;
  5758. }
  5759. // parse trailing whitespace
  5760. while (PUGI__IS_CHARTYPE(*string, ct_space)) ++string;
  5761. return *string == 0;
  5762. }
  5763. PUGI__FN double convert_string_to_number(const char_t* string)
  5764. {
  5765. // check string format
  5766. if (!check_string_to_number_format(string)) return gen_nan();
  5767. // parse string
  5768. #ifdef PUGIXML_WCHAR_MODE
  5769. return wcstod(string, 0);
  5770. #else
  5771. return atof(string);
  5772. #endif
  5773. }
  5774. PUGI__FN bool convert_string_to_number_scratch(char_t (&buffer)[32], const char_t* begin, const char_t* end, double* out_result)
  5775. {
  5776. size_t length = static_cast<size_t>(end - begin);
  5777. char_t* scratch = buffer;
  5778. if (length >= sizeof(buffer) / sizeof(buffer[0]))
  5779. {
  5780. // need to make dummy on-heap copy
  5781. scratch = static_cast<char_t*>(xml_memory::allocate((length + 1) * sizeof(char_t)));
  5782. if (!scratch) return false;
  5783. }
  5784. // copy string to zero-terminated buffer and perform conversion
  5785. memcpy(scratch, begin, length * sizeof(char_t));
  5786. scratch[length] = 0;
  5787. *out_result = convert_string_to_number(scratch);
  5788. // free dummy buffer
  5789. if (scratch != buffer) xml_memory::deallocate(scratch);
  5790. return true;
  5791. }
  5792. PUGI__FN double round_nearest(double value)
  5793. {
  5794. return floor(value + 0.5);
  5795. }
  5796. PUGI__FN double round_nearest_nzero(double value)
  5797. {
  5798. // same as round_nearest, but returns -0 for [-0.5, -0]
  5799. // ceil is used to differentiate between +0 and -0 (we return -0 for [-0.5, -0] and +0 for +0)
  5800. return (value >= -0.5 && value <= 0) ? ceil(value) : floor(value + 0.5);
  5801. }
  5802. PUGI__FN const char_t* qualified_name(const xpath_node& node)
  5803. {
  5804. return node.attribute() ? node.attribute().name() : node.node().name();
  5805. }
  5806. PUGI__FN const char_t* local_name(const xpath_node& node)
  5807. {
  5808. const char_t* name = qualified_name(node);
  5809. const char_t* p = find_char(name, ':');
  5810. return p ? p + 1 : name;
  5811. }
  5812. struct namespace_uri_predicate
  5813. {
  5814. const char_t* prefix;
  5815. size_t prefix_length;
  5816. namespace_uri_predicate(const char_t* name)
  5817. {
  5818. const char_t* pos = find_char(name, ':');
  5819. prefix = pos ? name : 0;
  5820. prefix_length = pos ? static_cast<size_t>(pos - name) : 0;
  5821. }
  5822. bool operator()(xml_attribute a) const
  5823. {
  5824. const char_t* name = a.name();
  5825. if (!starts_with(name, PUGIXML_TEXT("xmlns"))) return false;
  5826. return prefix ? name[5] == ':' && strequalrange(name + 6, prefix, prefix_length) : name[5] == 0;
  5827. }
  5828. };
  5829. PUGI__FN const char_t* namespace_uri(xml_node node)
  5830. {
  5831. namespace_uri_predicate pred = node.name();
  5832. xml_node p = node;
  5833. while (p)
  5834. {
  5835. xml_attribute a = p.find_attribute(pred);
  5836. if (a) return a.value();
  5837. p = p.parent();
  5838. }
  5839. return PUGIXML_TEXT("");
  5840. }
  5841. PUGI__FN const char_t* namespace_uri(xml_attribute attr, xml_node parent)
  5842. {
  5843. namespace_uri_predicate pred = attr.name();
  5844. // Default namespace does not apply to attributes
  5845. if (!pred.prefix) return PUGIXML_TEXT("");
  5846. xml_node p = parent;
  5847. while (p)
  5848. {
  5849. xml_attribute a = p.find_attribute(pred);
  5850. if (a) return a.value();
  5851. p = p.parent();
  5852. }
  5853. return PUGIXML_TEXT("");
  5854. }
  5855. PUGI__FN const char_t* namespace_uri(const xpath_node& node)
  5856. {
  5857. return node.attribute() ? namespace_uri(node.attribute(), node.parent()) : namespace_uri(node.node());
  5858. }
  5859. PUGI__FN void normalize_space(char_t* buffer)
  5860. {
  5861. char_t* write = buffer;
  5862. for (char_t* it = buffer; *it; )
  5863. {
  5864. char_t ch = *it++;
  5865. if (PUGI__IS_CHARTYPE(ch, ct_space))
  5866. {
  5867. // replace whitespace sequence with single space
  5868. while (PUGI__IS_CHARTYPE(*it, ct_space)) it++;
  5869. // avoid leading spaces
  5870. if (write != buffer) *write++ = ' ';
  5871. }
  5872. else *write++ = ch;
  5873. }
  5874. // remove trailing space
  5875. if (write != buffer && PUGI__IS_CHARTYPE(write[-1], ct_space)) write--;
  5876. // zero-terminate
  5877. *write = 0;
  5878. }
  5879. PUGI__FN void translate(char_t* buffer, const char_t* from, const char_t* to, size_t to_length)
  5880. {
  5881. char_t* write = buffer;
  5882. while (*buffer)
  5883. {
  5884. PUGI__DMC_VOLATILE char_t ch = *buffer++;
  5885. const char_t* pos = find_char(from, ch);
  5886. if (!pos)
  5887. *write++ = ch; // do not process
  5888. else if (static_cast<size_t>(pos - from) < to_length)
  5889. *write++ = to[pos - from]; // replace
  5890. }
  5891. // zero-terminate
  5892. *write = 0;
  5893. }
  5894. PUGI__FN unsigned char* translate_table_generate(xpath_allocator* alloc, const char_t* from, const char_t* to)
  5895. {
  5896. unsigned char table[128] = {0};
  5897. while (*from)
  5898. {
  5899. unsigned int fc = static_cast<unsigned int>(*from);
  5900. unsigned int tc = static_cast<unsigned int>(*to);
  5901. if (fc >= 128 || tc >= 128)
  5902. return 0;
  5903. // code=128 means "skip character"
  5904. if (!table[fc])
  5905. table[fc] = static_cast<unsigned char>(tc ? tc : 128);
  5906. from++;
  5907. if (tc) to++;
  5908. }
  5909. for (int i = 0; i < 128; ++i)
  5910. if (!table[i])
  5911. table[i] = static_cast<unsigned char>(i);
  5912. void* result = alloc->allocate_nothrow(sizeof(table));
  5913. if (result)
  5914. {
  5915. memcpy(result, table, sizeof(table));
  5916. }
  5917. return static_cast<unsigned char*>(result);
  5918. }
  5919. PUGI__FN void translate_table(char_t* buffer, const unsigned char* table)
  5920. {
  5921. char_t* write = buffer;
  5922. while (*buffer)
  5923. {
  5924. char_t ch = *buffer++;
  5925. unsigned int index = static_cast<unsigned int>(ch);
  5926. if (index < 128)
  5927. {
  5928. unsigned char code = table[index];
  5929. // code=128 means "skip character" (table size is 128 so 128 can be a special value)
  5930. // this code skips these characters without extra branches
  5931. *write = static_cast<char_t>(code);
  5932. write += 1 - (code >> 7);
  5933. }
  5934. else
  5935. {
  5936. *write++ = ch;
  5937. }
  5938. }
  5939. // zero-terminate
  5940. *write = 0;
  5941. }
  5942. inline bool is_xpath_attribute(const char_t* name)
  5943. {
  5944. return !(starts_with(name, PUGIXML_TEXT("xmlns")) && (name[5] == 0 || name[5] == ':'));
  5945. }
  5946. struct xpath_variable_boolean: xpath_variable
  5947. {
  5948. xpath_variable_boolean(): value(false)
  5949. {
  5950. }
  5951. bool value;
  5952. char_t name[1];
  5953. };
  5954. struct xpath_variable_number: xpath_variable
  5955. {
  5956. xpath_variable_number(): value(0)
  5957. {
  5958. }
  5959. double value;
  5960. char_t name[1];
  5961. };
  5962. struct xpath_variable_string: xpath_variable
  5963. {
  5964. xpath_variable_string(): value(0)
  5965. {
  5966. }
  5967. ~xpath_variable_string()
  5968. {
  5969. if (value) xml_memory::deallocate(value);
  5970. }
  5971. char_t* value;
  5972. char_t name[1];
  5973. };
  5974. struct xpath_variable_node_set: xpath_variable
  5975. {
  5976. xpath_node_set value;
  5977. char_t name[1];
  5978. };
  5979. static const xpath_node_set dummy_node_set;
  5980. PUGI__FN unsigned int hash_string(const char_t* str)
  5981. {
  5982. // Jenkins one-at-a-time hash (http://en.wikipedia.org/wiki/Jenkins_hash_function#one-at-a-time)
  5983. unsigned int result = 0;
  5984. while (*str)
  5985. {
  5986. result += static_cast<unsigned int>(*str++);
  5987. result += result << 10;
  5988. result ^= result >> 6;
  5989. }
  5990. result += result << 3;
  5991. result ^= result >> 11;
  5992. result += result << 15;
  5993. return result;
  5994. }
  5995. template <typename T> PUGI__FN T* new_xpath_variable(const char_t* name)
  5996. {
  5997. size_t length = strlength(name);
  5998. if (length == 0) return 0; // empty variable names are invalid
  5999. // $$ we can't use offsetof(T, name) because T is non-POD, so we just allocate additional length characters
  6000. void* memory = xml_memory::allocate(sizeof(T) + length * sizeof(char_t));
  6001. if (!memory) return 0;
  6002. T* result = new (memory) T();
  6003. memcpy(result->name, name, (length + 1) * sizeof(char_t));
  6004. return result;
  6005. }
  6006. PUGI__FN xpath_variable* new_xpath_variable(xpath_value_type type, const char_t* name)
  6007. {
  6008. switch (type)
  6009. {
  6010. case xpath_type_node_set:
  6011. return new_xpath_variable<xpath_variable_node_set>(name);
  6012. case xpath_type_number:
  6013. return new_xpath_variable<xpath_variable_number>(name);
  6014. case xpath_type_string:
  6015. return new_xpath_variable<xpath_variable_string>(name);
  6016. case xpath_type_boolean:
  6017. return new_xpath_variable<xpath_variable_boolean>(name);
  6018. default:
  6019. return 0;
  6020. }
  6021. }
  6022. template <typename T> PUGI__FN void delete_xpath_variable(T* var)
  6023. {
  6024. var->~T();
  6025. xml_memory::deallocate(var);
  6026. }
  6027. PUGI__FN void delete_xpath_variable(xpath_value_type type, xpath_variable* var)
  6028. {
  6029. switch (type)
  6030. {
  6031. case xpath_type_node_set:
  6032. delete_xpath_variable(static_cast<xpath_variable_node_set*>(var));
  6033. break;
  6034. case xpath_type_number:
  6035. delete_xpath_variable(static_cast<xpath_variable_number*>(var));
  6036. break;
  6037. case xpath_type_string:
  6038. delete_xpath_variable(static_cast<xpath_variable_string*>(var));
  6039. break;
  6040. case xpath_type_boolean:
  6041. delete_xpath_variable(static_cast<xpath_variable_boolean*>(var));
  6042. break;
  6043. default:
  6044. assert(!"Invalid variable type");
  6045. }
  6046. }
  6047. PUGI__FN xpath_variable* get_variable_scratch(char_t (&buffer)[32], xpath_variable_set* set, const char_t* begin, const char_t* end)
  6048. {
  6049. size_t length = static_cast<size_t>(end - begin);
  6050. char_t* scratch = buffer;
  6051. if (length >= sizeof(buffer) / sizeof(buffer[0]))
  6052. {
  6053. // need to make dummy on-heap copy
  6054. scratch = static_cast<char_t*>(xml_memory::allocate((length + 1) * sizeof(char_t)));
  6055. if (!scratch) return 0;
  6056. }
  6057. // copy string to zero-terminated buffer and perform lookup
  6058. memcpy(scratch, begin, length * sizeof(char_t));
  6059. scratch[length] = 0;
  6060. xpath_variable* result = set->get(scratch);
  6061. // free dummy buffer
  6062. if (scratch != buffer) xml_memory::deallocate(scratch);
  6063. return result;
  6064. }
  6065. PUGI__NS_END
  6066. // Internal node set class
  6067. PUGI__NS_BEGIN
  6068. PUGI__FN xpath_node_set::type_t xpath_get_order(const xpath_node* begin, const xpath_node* end)
  6069. {
  6070. if (end - begin < 2)
  6071. return xpath_node_set::type_sorted;
  6072. document_order_comparator cmp;
  6073. bool first = cmp(begin[0], begin[1]);
  6074. for (const xpath_node* it = begin + 1; it + 1 < end; ++it)
  6075. if (cmp(it[0], it[1]) != first)
  6076. return xpath_node_set::type_unsorted;
  6077. return first ? xpath_node_set::type_sorted : xpath_node_set::type_sorted_reverse;
  6078. }
  6079. PUGI__FN xpath_node_set::type_t xpath_sort(xpath_node* begin, xpath_node* end, xpath_node_set::type_t type, bool rev)
  6080. {
  6081. xpath_node_set::type_t order = rev ? xpath_node_set::type_sorted_reverse : xpath_node_set::type_sorted;
  6082. if (type == xpath_node_set::type_unsorted)
  6083. {
  6084. xpath_node_set::type_t sorted = xpath_get_order(begin, end);
  6085. if (sorted == xpath_node_set::type_unsorted)
  6086. {
  6087. sort(begin, end, document_order_comparator());
  6088. type = xpath_node_set::type_sorted;
  6089. }
  6090. else
  6091. type = sorted;
  6092. }
  6093. if (type != order) reverse(begin, end);
  6094. return order;
  6095. }
  6096. PUGI__FN xpath_node xpath_first(const xpath_node* begin, const xpath_node* end, xpath_node_set::type_t type)
  6097. {
  6098. if (begin == end) return xpath_node();
  6099. switch (type)
  6100. {
  6101. case xpath_node_set::type_sorted:
  6102. return *begin;
  6103. case xpath_node_set::type_sorted_reverse:
  6104. return *(end - 1);
  6105. case xpath_node_set::type_unsorted:
  6106. return *min_element(begin, end, document_order_comparator());
  6107. default:
  6108. assert(!"Invalid node set type");
  6109. return xpath_node();
  6110. }
  6111. }
  6112. class xpath_node_set_raw
  6113. {
  6114. xpath_node_set::type_t _type;
  6115. xpath_node* _begin;
  6116. xpath_node* _end;
  6117. xpath_node* _eos;
  6118. public:
  6119. xpath_node_set_raw(): _type(xpath_node_set::type_unsorted), _begin(0), _end(0), _eos(0)
  6120. {
  6121. }
  6122. xpath_node* begin() const
  6123. {
  6124. return _begin;
  6125. }
  6126. xpath_node* end() const
  6127. {
  6128. return _end;
  6129. }
  6130. bool empty() const
  6131. {
  6132. return _begin == _end;
  6133. }
  6134. size_t size() const
  6135. {
  6136. return static_cast<size_t>(_end - _begin);
  6137. }
  6138. xpath_node first() const
  6139. {
  6140. return xpath_first(_begin, _end, _type);
  6141. }
  6142. void push_back_grow(const xpath_node& node, xpath_allocator* alloc);
  6143. void push_back(const xpath_node& node, xpath_allocator* alloc)
  6144. {
  6145. if (_end != _eos)
  6146. *_end++ = node;
  6147. else
  6148. push_back_grow(node, alloc);
  6149. }
  6150. void append(const xpath_node* begin_, const xpath_node* end_, xpath_allocator* alloc)
  6151. {
  6152. if (begin_ == end_) return;
  6153. size_t size_ = static_cast<size_t>(_end - _begin);
  6154. size_t capacity = static_cast<size_t>(_eos - _begin);
  6155. size_t count = static_cast<size_t>(end_ - begin_);
  6156. if (size_ + count > capacity)
  6157. {
  6158. // reallocate the old array or allocate a new one
  6159. xpath_node* data = static_cast<xpath_node*>(alloc->reallocate(_begin, capacity * sizeof(xpath_node), (size_ + count) * sizeof(xpath_node)));
  6160. assert(data);
  6161. // finalize
  6162. _begin = data;
  6163. _end = data + size_;
  6164. _eos = data + size_ + count;
  6165. }
  6166. memcpy(_end, begin_, count * sizeof(xpath_node));
  6167. _end += count;
  6168. }
  6169. void sort_do()
  6170. {
  6171. _type = xpath_sort(_begin, _end, _type, false);
  6172. }
  6173. void truncate(xpath_node* pos)
  6174. {
  6175. assert(_begin <= pos && pos <= _end);
  6176. _end = pos;
  6177. }
  6178. void remove_duplicates()
  6179. {
  6180. if (_type == xpath_node_set::type_unsorted)
  6181. sort(_begin, _end, duplicate_comparator());
  6182. _end = unique(_begin, _end);
  6183. }
  6184. xpath_node_set::type_t type() const
  6185. {
  6186. return _type;
  6187. }
  6188. void set_type(xpath_node_set::type_t value)
  6189. {
  6190. _type = value;
  6191. }
  6192. };
  6193. PUGI__FN_NO_INLINE void xpath_node_set_raw::push_back_grow(const xpath_node& node, xpath_allocator* alloc)
  6194. {
  6195. size_t capacity = static_cast<size_t>(_eos - _begin);
  6196. // get new capacity (1.5x rule)
  6197. size_t new_capacity = capacity + capacity / 2 + 1;
  6198. // reallocate the old array or allocate a new one
  6199. xpath_node* data = static_cast<xpath_node*>(alloc->reallocate(_begin, capacity * sizeof(xpath_node), new_capacity * sizeof(xpath_node)));
  6200. assert(data);
  6201. // finalize
  6202. _begin = data;
  6203. _end = data + capacity;
  6204. _eos = data + new_capacity;
  6205. // push
  6206. *_end++ = node;
  6207. }
  6208. PUGI__NS_END
  6209. PUGI__NS_BEGIN
  6210. struct xpath_context
  6211. {
  6212. xpath_node n;
  6213. size_t position, size;
  6214. xpath_context(const xpath_node& n_, size_t position_, size_t size_): n(n_), position(position_), size(size_)
  6215. {
  6216. }
  6217. };
  6218. enum lexeme_t
  6219. {
  6220. lex_none = 0,
  6221. lex_equal,
  6222. lex_not_equal,
  6223. lex_less,
  6224. lex_greater,
  6225. lex_less_or_equal,
  6226. lex_greater_or_equal,
  6227. lex_plus,
  6228. lex_minus,
  6229. lex_multiply,
  6230. lex_union,
  6231. lex_var_ref,
  6232. lex_open_brace,
  6233. lex_close_brace,
  6234. lex_quoted_string,
  6235. lex_number,
  6236. lex_slash,
  6237. lex_double_slash,
  6238. lex_open_square_brace,
  6239. lex_close_square_brace,
  6240. lex_string,
  6241. lex_comma,
  6242. lex_axis_attribute,
  6243. lex_dot,
  6244. lex_double_dot,
  6245. lex_double_colon,
  6246. lex_eof
  6247. };
  6248. struct xpath_lexer_string
  6249. {
  6250. const char_t* begin;
  6251. const char_t* end;
  6252. xpath_lexer_string(): begin(0), end(0)
  6253. {
  6254. }
  6255. bool operator==(const char_t* other) const
  6256. {
  6257. size_t length = static_cast<size_t>(end - begin);
  6258. return strequalrange(other, begin, length);
  6259. }
  6260. };
  6261. class xpath_lexer
  6262. {
  6263. const char_t* _cur;
  6264. const char_t* _cur_lexeme_pos;
  6265. xpath_lexer_string _cur_lexeme_contents;
  6266. lexeme_t _cur_lexeme;
  6267. public:
  6268. explicit xpath_lexer(const char_t* query): _cur(query)
  6269. {
  6270. next();
  6271. }
  6272. const char_t* state() const
  6273. {
  6274. return _cur;
  6275. }
  6276. void next()
  6277. {
  6278. const char_t* cur = _cur;
  6279. while (PUGI__IS_CHARTYPE(*cur, ct_space)) ++cur;
  6280. // save lexeme position for error reporting
  6281. _cur_lexeme_pos = cur;
  6282. switch (*cur)
  6283. {
  6284. case 0:
  6285. _cur_lexeme = lex_eof;
  6286. break;
  6287. case '>':
  6288. if (*(cur+1) == '=')
  6289. {
  6290. cur += 2;
  6291. _cur_lexeme = lex_greater_or_equal;
  6292. }
  6293. else
  6294. {
  6295. cur += 1;
  6296. _cur_lexeme = lex_greater;
  6297. }
  6298. break;
  6299. case '<':
  6300. if (*(cur+1) == '=')
  6301. {
  6302. cur += 2;
  6303. _cur_lexeme = lex_less_or_equal;
  6304. }
  6305. else
  6306. {
  6307. cur += 1;
  6308. _cur_lexeme = lex_less;
  6309. }
  6310. break;
  6311. case '!':
  6312. if (*(cur+1) == '=')
  6313. {
  6314. cur += 2;
  6315. _cur_lexeme = lex_not_equal;
  6316. }
  6317. else
  6318. {
  6319. _cur_lexeme = lex_none;
  6320. }
  6321. break;
  6322. case '=':
  6323. cur += 1;
  6324. _cur_lexeme = lex_equal;
  6325. break;
  6326. case '+':
  6327. cur += 1;
  6328. _cur_lexeme = lex_plus;
  6329. break;
  6330. case '-':
  6331. cur += 1;
  6332. _cur_lexeme = lex_minus;
  6333. break;
  6334. case '*':
  6335. cur += 1;
  6336. _cur_lexeme = lex_multiply;
  6337. break;
  6338. case '|':
  6339. cur += 1;
  6340. _cur_lexeme = lex_union;
  6341. break;
  6342. case '$':
  6343. cur += 1;
  6344. if (PUGI__IS_CHARTYPEX(*cur, ctx_start_symbol))
  6345. {
  6346. _cur_lexeme_contents.begin = cur;
  6347. while (PUGI__IS_CHARTYPEX(*cur, ctx_symbol)) cur++;
  6348. if (cur[0] == ':' && PUGI__IS_CHARTYPEX(cur[1], ctx_symbol)) // qname
  6349. {
  6350. cur++; // :
  6351. while (PUGI__IS_CHARTYPEX(*cur, ctx_symbol)) cur++;
  6352. }
  6353. _cur_lexeme_contents.end = cur;
  6354. _cur_lexeme = lex_var_ref;
  6355. }
  6356. else
  6357. {
  6358. _cur_lexeme = lex_none;
  6359. }
  6360. break;
  6361. case '(':
  6362. cur += 1;
  6363. _cur_lexeme = lex_open_brace;
  6364. break;
  6365. case ')':
  6366. cur += 1;
  6367. _cur_lexeme = lex_close_brace;
  6368. break;
  6369. case '[':
  6370. cur += 1;
  6371. _cur_lexeme = lex_open_square_brace;
  6372. break;
  6373. case ']':
  6374. cur += 1;
  6375. _cur_lexeme = lex_close_square_brace;
  6376. break;
  6377. case ',':
  6378. cur += 1;
  6379. _cur_lexeme = lex_comma;
  6380. break;
  6381. case '/':
  6382. if (*(cur+1) == '/')
  6383. {
  6384. cur += 2;
  6385. _cur_lexeme = lex_double_slash;
  6386. }
  6387. else
  6388. {
  6389. cur += 1;
  6390. _cur_lexeme = lex_slash;
  6391. }
  6392. break;
  6393. case '.':
  6394. if (*(cur+1) == '.')
  6395. {
  6396. cur += 2;
  6397. _cur_lexeme = lex_double_dot;
  6398. }
  6399. else if (PUGI__IS_CHARTYPEX(*(cur+1), ctx_digit))
  6400. {
  6401. _cur_lexeme_contents.begin = cur; // .
  6402. ++cur;
  6403. while (PUGI__IS_CHARTYPEX(*cur, ctx_digit)) cur++;
  6404. _cur_lexeme_contents.end = cur;
  6405. _cur_lexeme = lex_number;
  6406. }
  6407. else
  6408. {
  6409. cur += 1;
  6410. _cur_lexeme = lex_dot;
  6411. }
  6412. break;
  6413. case '@':
  6414. cur += 1;
  6415. _cur_lexeme = lex_axis_attribute;
  6416. break;
  6417. case '"':
  6418. case '\'':
  6419. {
  6420. char_t terminator = *cur;
  6421. ++cur;
  6422. _cur_lexeme_contents.begin = cur;
  6423. while (*cur && *cur != terminator) cur++;
  6424. _cur_lexeme_contents.end = cur;
  6425. if (!*cur)
  6426. _cur_lexeme = lex_none;
  6427. else
  6428. {
  6429. cur += 1;
  6430. _cur_lexeme = lex_quoted_string;
  6431. }
  6432. break;
  6433. }
  6434. case ':':
  6435. if (*(cur+1) == ':')
  6436. {
  6437. cur += 2;
  6438. _cur_lexeme = lex_double_colon;
  6439. }
  6440. else
  6441. {
  6442. _cur_lexeme = lex_none;
  6443. }
  6444. break;
  6445. default:
  6446. if (PUGI__IS_CHARTYPEX(*cur, ctx_digit))
  6447. {
  6448. _cur_lexeme_contents.begin = cur;
  6449. while (PUGI__IS_CHARTYPEX(*cur, ctx_digit)) cur++;
  6450. if (*cur == '.')
  6451. {
  6452. cur++;
  6453. while (PUGI__IS_CHARTYPEX(*cur, ctx_digit)) cur++;
  6454. }
  6455. _cur_lexeme_contents.end = cur;
  6456. _cur_lexeme = lex_number;
  6457. }
  6458. else if (PUGI__IS_CHARTYPEX(*cur, ctx_start_symbol))
  6459. {
  6460. _cur_lexeme_contents.begin = cur;
  6461. while (PUGI__IS_CHARTYPEX(*cur, ctx_symbol)) cur++;
  6462. if (cur[0] == ':')
  6463. {
  6464. if (cur[1] == '*') // namespace test ncname:*
  6465. {
  6466. cur += 2; // :*
  6467. }
  6468. else if (PUGI__IS_CHARTYPEX(cur[1], ctx_symbol)) // namespace test qname
  6469. {
  6470. cur++; // :
  6471. while (PUGI__IS_CHARTYPEX(*cur, ctx_symbol)) cur++;
  6472. }
  6473. }
  6474. _cur_lexeme_contents.end = cur;
  6475. _cur_lexeme = lex_string;
  6476. }
  6477. else
  6478. {
  6479. _cur_lexeme = lex_none;
  6480. }
  6481. }
  6482. _cur = cur;
  6483. }
  6484. lexeme_t current() const
  6485. {
  6486. return _cur_lexeme;
  6487. }
  6488. const char_t* current_pos() const
  6489. {
  6490. return _cur_lexeme_pos;
  6491. }
  6492. const xpath_lexer_string& contents() const
  6493. {
  6494. assert(_cur_lexeme == lex_var_ref || _cur_lexeme == lex_number || _cur_lexeme == lex_string || _cur_lexeme == lex_quoted_string);
  6495. return _cur_lexeme_contents;
  6496. }
  6497. };
  6498. enum ast_type_t
  6499. {
  6500. ast_unknown,
  6501. ast_op_or, // left or right
  6502. ast_op_and, // left and right
  6503. ast_op_equal, // left = right
  6504. ast_op_not_equal, // left != right
  6505. ast_op_less, // left < right
  6506. ast_op_greater, // left > right
  6507. ast_op_less_or_equal, // left <= right
  6508. ast_op_greater_or_equal, // left >= right
  6509. ast_op_add, // left + right
  6510. ast_op_subtract, // left - right
  6511. ast_op_multiply, // left * right
  6512. ast_op_divide, // left / right
  6513. ast_op_mod, // left % right
  6514. ast_op_negate, // left - right
  6515. ast_op_union, // left | right
  6516. ast_predicate, // apply predicate to set; next points to next predicate
  6517. ast_filter, // select * from left where right
  6518. ast_string_constant, // string constant
  6519. ast_number_constant, // number constant
  6520. ast_variable, // variable
  6521. ast_func_last, // last()
  6522. ast_func_position, // position()
  6523. ast_func_count, // count(left)
  6524. ast_func_id, // id(left)
  6525. ast_func_local_name_0, // local-name()
  6526. ast_func_local_name_1, // local-name(left)
  6527. ast_func_namespace_uri_0, // namespace-uri()
  6528. ast_func_namespace_uri_1, // namespace-uri(left)
  6529. ast_func_name_0, // name()
  6530. ast_func_name_1, // name(left)
  6531. ast_func_string_0, // string()
  6532. ast_func_string_1, // string(left)
  6533. ast_func_concat, // concat(left, right, siblings)
  6534. ast_func_starts_with, // starts_with(left, right)
  6535. ast_func_contains, // contains(left, right)
  6536. ast_func_substring_before, // substring-before(left, right)
  6537. ast_func_substring_after, // substring-after(left, right)
  6538. ast_func_substring_2, // substring(left, right)
  6539. ast_func_substring_3, // substring(left, right, third)
  6540. ast_func_string_length_0, // string-length()
  6541. ast_func_string_length_1, // string-length(left)
  6542. ast_func_normalize_space_0, // normalize-space()
  6543. ast_func_normalize_space_1, // normalize-space(left)
  6544. ast_func_translate, // translate(left, right, third)
  6545. ast_func_boolean, // boolean(left)
  6546. ast_func_not, // not(left)
  6547. ast_func_true, // true()
  6548. ast_func_false, // false()
  6549. ast_func_lang, // lang(left)
  6550. ast_func_number_0, // number()
  6551. ast_func_number_1, // number(left)
  6552. ast_func_sum, // sum(left)
  6553. ast_func_floor, // floor(left)
  6554. ast_func_ceiling, // ceiling(left)
  6555. ast_func_round, // round(left)
  6556. ast_step, // process set left with step
  6557. ast_step_root, // select root node
  6558. ast_opt_translate_table, // translate(left, right, third) where right/third are constants
  6559. ast_opt_compare_attribute // @name = 'string'
  6560. };
  6561. enum axis_t
  6562. {
  6563. axis_ancestor,
  6564. axis_ancestor_or_self,
  6565. axis_attribute,
  6566. axis_child,
  6567. axis_descendant,
  6568. axis_descendant_or_self,
  6569. axis_following,
  6570. axis_following_sibling,
  6571. axis_namespace,
  6572. axis_parent,
  6573. axis_preceding,
  6574. axis_preceding_sibling,
  6575. axis_self
  6576. };
  6577. enum nodetest_t
  6578. {
  6579. nodetest_none,
  6580. nodetest_name,
  6581. nodetest_type_node,
  6582. nodetest_type_comment,
  6583. nodetest_type_pi,
  6584. nodetest_type_text,
  6585. nodetest_pi,
  6586. nodetest_all,
  6587. nodetest_all_in_namespace
  6588. };
  6589. enum predicate_t
  6590. {
  6591. predicate_default,
  6592. predicate_posinv,
  6593. predicate_constant,
  6594. predicate_constant_one
  6595. };
  6596. enum nodeset_eval_t
  6597. {
  6598. nodeset_eval_all,
  6599. nodeset_eval_any,
  6600. nodeset_eval_first
  6601. };
  6602. template <axis_t N> struct axis_to_type
  6603. {
  6604. static const axis_t axis;
  6605. };
  6606. template <axis_t N> const axis_t axis_to_type<N>::axis = N;
  6607. class xpath_ast_node
  6608. {
  6609. private:
  6610. // node type
  6611. char _type;
  6612. char _rettype;
  6613. // for ast_step
  6614. char _axis;
  6615. // for ast_step/ast_predicate/ast_filter
  6616. char _test;
  6617. // tree node structure
  6618. xpath_ast_node* _left;
  6619. xpath_ast_node* _right;
  6620. xpath_ast_node* _next;
  6621. union
  6622. {
  6623. // value for ast_string_constant
  6624. const char_t* string;
  6625. // value for ast_number_constant
  6626. double number;
  6627. // variable for ast_variable
  6628. xpath_variable* variable;
  6629. // node test for ast_step (node name/namespace/node type/pi target)
  6630. const char_t* nodetest;
  6631. // table for ast_opt_translate_table
  6632. const unsigned char* table;
  6633. } _data;
  6634. xpath_ast_node(const xpath_ast_node&);
  6635. xpath_ast_node& operator=(const xpath_ast_node&);
  6636. template <class Comp> static bool compare_eq(xpath_ast_node* lhs, xpath_ast_node* rhs, const xpath_context& c, const xpath_stack& stack, const Comp& comp)
  6637. {
  6638. xpath_value_type lt = lhs->rettype(), rt = rhs->rettype();
  6639. if (lt != xpath_type_node_set && rt != xpath_type_node_set)
  6640. {
  6641. if (lt == xpath_type_boolean || rt == xpath_type_boolean)
  6642. return comp(lhs->eval_boolean(c, stack), rhs->eval_boolean(c, stack));
  6643. else if (lt == xpath_type_number || rt == xpath_type_number)
  6644. return comp(lhs->eval_number(c, stack), rhs->eval_number(c, stack));
  6645. else if (lt == xpath_type_string || rt == xpath_type_string)
  6646. {
  6647. xpath_allocator_capture cr(stack.result);
  6648. xpath_string ls = lhs->eval_string(c, stack);
  6649. xpath_string rs = rhs->eval_string(c, stack);
  6650. return comp(ls, rs);
  6651. }
  6652. }
  6653. else if (lt == xpath_type_node_set && rt == xpath_type_node_set)
  6654. {
  6655. xpath_allocator_capture cr(stack.result);
  6656. xpath_node_set_raw ls = lhs->eval_node_set(c, stack, nodeset_eval_all);
  6657. xpath_node_set_raw rs = rhs->eval_node_set(c, stack, nodeset_eval_all);
  6658. for (const xpath_node* li = ls.begin(); li != ls.end(); ++li)
  6659. for (const xpath_node* ri = rs.begin(); ri != rs.end(); ++ri)
  6660. {
  6661. xpath_allocator_capture cri(stack.result);
  6662. if (comp(string_value(*li, stack.result), string_value(*ri, stack.result)))
  6663. return true;
  6664. }
  6665. return false;
  6666. }
  6667. else
  6668. {
  6669. if (lt == xpath_type_node_set)
  6670. {
  6671. swap(lhs, rhs);
  6672. swap(lt, rt);
  6673. }
  6674. if (lt == xpath_type_boolean)
  6675. return comp(lhs->eval_boolean(c, stack), rhs->eval_boolean(c, stack));
  6676. else if (lt == xpath_type_number)
  6677. {
  6678. xpath_allocator_capture cr(stack.result);
  6679. double l = lhs->eval_number(c, stack);
  6680. xpath_node_set_raw rs = rhs->eval_node_set(c, stack, nodeset_eval_all);
  6681. for (const xpath_node* ri = rs.begin(); ri != rs.end(); ++ri)
  6682. {
  6683. xpath_allocator_capture cri(stack.result);
  6684. if (comp(l, convert_string_to_number(string_value(*ri, stack.result).c_str())))
  6685. return true;
  6686. }
  6687. return false;
  6688. }
  6689. else if (lt == xpath_type_string)
  6690. {
  6691. xpath_allocator_capture cr(stack.result);
  6692. xpath_string l = lhs->eval_string(c, stack);
  6693. xpath_node_set_raw rs = rhs->eval_node_set(c, stack, nodeset_eval_all);
  6694. for (const xpath_node* ri = rs.begin(); ri != rs.end(); ++ri)
  6695. {
  6696. xpath_allocator_capture cri(stack.result);
  6697. if (comp(l, string_value(*ri, stack.result)))
  6698. return true;
  6699. }
  6700. return false;
  6701. }
  6702. }
  6703. assert(!"Wrong types");
  6704. return false;
  6705. }
  6706. static bool eval_once(xpath_node_set::type_t type, nodeset_eval_t eval)
  6707. {
  6708. return type == xpath_node_set::type_sorted ? eval != nodeset_eval_all : eval == nodeset_eval_any;
  6709. }
  6710. template <class Comp> static bool compare_rel(xpath_ast_node* lhs, xpath_ast_node* rhs, const xpath_context& c, const xpath_stack& stack, const Comp& comp)
  6711. {
  6712. xpath_value_type lt = lhs->rettype(), rt = rhs->rettype();
  6713. if (lt != xpath_type_node_set && rt != xpath_type_node_set)
  6714. return comp(lhs->eval_number(c, stack), rhs->eval_number(c, stack));
  6715. else if (lt == xpath_type_node_set && rt == xpath_type_node_set)
  6716. {
  6717. xpath_allocator_capture cr(stack.result);
  6718. xpath_node_set_raw ls = lhs->eval_node_set(c, stack, nodeset_eval_all);
  6719. xpath_node_set_raw rs = rhs->eval_node_set(c, stack, nodeset_eval_all);
  6720. for (const xpath_node* li = ls.begin(); li != ls.end(); ++li)
  6721. {
  6722. xpath_allocator_capture cri(stack.result);
  6723. double l = convert_string_to_number(string_value(*li, stack.result).c_str());
  6724. for (const xpath_node* ri = rs.begin(); ri != rs.end(); ++ri)
  6725. {
  6726. xpath_allocator_capture crii(stack.result);
  6727. if (comp(l, convert_string_to_number(string_value(*ri, stack.result).c_str())))
  6728. return true;
  6729. }
  6730. }
  6731. return false;
  6732. }
  6733. else if (lt != xpath_type_node_set && rt == xpath_type_node_set)
  6734. {
  6735. xpath_allocator_capture cr(stack.result);
  6736. double l = lhs->eval_number(c, stack);
  6737. xpath_node_set_raw rs = rhs->eval_node_set(c, stack, nodeset_eval_all);
  6738. for (const xpath_node* ri = rs.begin(); ri != rs.end(); ++ri)
  6739. {
  6740. xpath_allocator_capture cri(stack.result);
  6741. if (comp(l, convert_string_to_number(string_value(*ri, stack.result).c_str())))
  6742. return true;
  6743. }
  6744. return false;
  6745. }
  6746. else if (lt == xpath_type_node_set && rt != xpath_type_node_set)
  6747. {
  6748. xpath_allocator_capture cr(stack.result);
  6749. xpath_node_set_raw ls = lhs->eval_node_set(c, stack, nodeset_eval_all);
  6750. double r = rhs->eval_number(c, stack);
  6751. for (const xpath_node* li = ls.begin(); li != ls.end(); ++li)
  6752. {
  6753. xpath_allocator_capture cri(stack.result);
  6754. if (comp(convert_string_to_number(string_value(*li, stack.result).c_str()), r))
  6755. return true;
  6756. }
  6757. return false;
  6758. }
  6759. else
  6760. {
  6761. assert(!"Wrong types");
  6762. return false;
  6763. }
  6764. }
  6765. static void apply_predicate_boolean(xpath_node_set_raw& ns, size_t first, xpath_ast_node* expr, const xpath_stack& stack, bool once)
  6766. {
  6767. assert(ns.size() >= first);
  6768. assert(expr->rettype() != xpath_type_number);
  6769. size_t i = 1;
  6770. size_t size = ns.size() - first;
  6771. xpath_node* last = ns.begin() + first;
  6772. // remove_if... or well, sort of
  6773. for (xpath_node* it = last; it != ns.end(); ++it, ++i)
  6774. {
  6775. xpath_context c(*it, i, size);
  6776. if (expr->eval_boolean(c, stack))
  6777. {
  6778. *last++ = *it;
  6779. if (once) break;
  6780. }
  6781. }
  6782. ns.truncate(last);
  6783. }
  6784. static void apply_predicate_number(xpath_node_set_raw& ns, size_t first, xpath_ast_node* expr, const xpath_stack& stack, bool once)
  6785. {
  6786. assert(ns.size() >= first);
  6787. assert(expr->rettype() == xpath_type_number);
  6788. size_t i = 1;
  6789. size_t size = ns.size() - first;
  6790. xpath_node* last = ns.begin() + first;
  6791. // remove_if... or well, sort of
  6792. for (xpath_node* it = last; it != ns.end(); ++it, ++i)
  6793. {
  6794. xpath_context c(*it, i, size);
  6795. if (expr->eval_number(c, stack) == i)
  6796. {
  6797. *last++ = *it;
  6798. if (once) break;
  6799. }
  6800. }
  6801. ns.truncate(last);
  6802. }
  6803. static void apply_predicate_number_const(xpath_node_set_raw& ns, size_t first, xpath_ast_node* expr, const xpath_stack& stack)
  6804. {
  6805. assert(ns.size() >= first);
  6806. assert(expr->rettype() == xpath_type_number);
  6807. size_t size = ns.size() - first;
  6808. xpath_node* last = ns.begin() + first;
  6809. xpath_context c(xpath_node(), 1, size);
  6810. double er = expr->eval_number(c, stack);
  6811. if (er >= 1.0 && er <= size)
  6812. {
  6813. size_t eri = static_cast<size_t>(er);
  6814. if (er == eri)
  6815. {
  6816. xpath_node r = last[eri - 1];
  6817. *last++ = r;
  6818. }
  6819. }
  6820. ns.truncate(last);
  6821. }
  6822. void apply_predicate(xpath_node_set_raw& ns, size_t first, const xpath_stack& stack, bool once)
  6823. {
  6824. if (ns.size() == first) return;
  6825. assert(_type == ast_filter || _type == ast_predicate);
  6826. if (_test == predicate_constant || _test == predicate_constant_one)
  6827. apply_predicate_number_const(ns, first, _right, stack);
  6828. else if (_right->rettype() == xpath_type_number)
  6829. apply_predicate_number(ns, first, _right, stack, once);
  6830. else
  6831. apply_predicate_boolean(ns, first, _right, stack, once);
  6832. }
  6833. void apply_predicates(xpath_node_set_raw& ns, size_t first, const xpath_stack& stack, nodeset_eval_t eval)
  6834. {
  6835. if (ns.size() == first) return;
  6836. bool last_once = eval_once(ns.type(), eval);
  6837. for (xpath_ast_node* pred = _right; pred; pred = pred->_next)
  6838. pred->apply_predicate(ns, first, stack, !pred->_next && last_once);
  6839. }
  6840. bool step_push(xpath_node_set_raw& ns, xml_attribute_struct* a, xml_node_struct* parent, xpath_allocator* alloc)
  6841. {
  6842. assert(a);
  6843. const char_t* name = a->name ? a->name : PUGIXML_TEXT("");
  6844. switch (_test)
  6845. {
  6846. case nodetest_name:
  6847. if (strequal(name, _data.nodetest) && is_xpath_attribute(name))
  6848. {
  6849. ns.push_back(xpath_node(xml_attribute(a), xml_node(parent)), alloc);
  6850. return true;
  6851. }
  6852. break;
  6853. case nodetest_type_node:
  6854. case nodetest_all:
  6855. if (is_xpath_attribute(name))
  6856. {
  6857. ns.push_back(xpath_node(xml_attribute(a), xml_node(parent)), alloc);
  6858. return true;
  6859. }
  6860. break;
  6861. case nodetest_all_in_namespace:
  6862. if (starts_with(name, _data.nodetest) && is_xpath_attribute(name))
  6863. {
  6864. ns.push_back(xpath_node(xml_attribute(a), xml_node(parent)), alloc);
  6865. return true;
  6866. }
  6867. break;
  6868. default:
  6869. ;
  6870. }
  6871. return false;
  6872. }
  6873. bool step_push(xpath_node_set_raw& ns, xml_node_struct* n, xpath_allocator* alloc)
  6874. {
  6875. assert(n);
  6876. xml_node_type type = PUGI__NODETYPE(n);
  6877. switch (_test)
  6878. {
  6879. case nodetest_name:
  6880. if (type == node_element && n->name && strequal(n->name, _data.nodetest))
  6881. {
  6882. ns.push_back(xml_node(n), alloc);
  6883. return true;
  6884. }
  6885. break;
  6886. case nodetest_type_node:
  6887. ns.push_back(xml_node(n), alloc);
  6888. return true;
  6889. case nodetest_type_comment:
  6890. if (type == node_comment)
  6891. {
  6892. ns.push_back(xml_node(n), alloc);
  6893. return true;
  6894. }
  6895. break;
  6896. case nodetest_type_text:
  6897. if (type == node_pcdata || type == node_cdata)
  6898. {
  6899. ns.push_back(xml_node(n), alloc);
  6900. return true;
  6901. }
  6902. break;
  6903. case nodetest_type_pi:
  6904. if (type == node_pi)
  6905. {
  6906. ns.push_back(xml_node(n), alloc);
  6907. return true;
  6908. }
  6909. break;
  6910. case nodetest_pi:
  6911. if (type == node_pi && n->name && strequal(n->name, _data.nodetest))
  6912. {
  6913. ns.push_back(xml_node(n), alloc);
  6914. return true;
  6915. }
  6916. break;
  6917. case nodetest_all:
  6918. if (type == node_element)
  6919. {
  6920. ns.push_back(xml_node(n), alloc);
  6921. return true;
  6922. }
  6923. break;
  6924. case nodetest_all_in_namespace:
  6925. if (type == node_element && n->name && starts_with(n->name, _data.nodetest))
  6926. {
  6927. ns.push_back(xml_node(n), alloc);
  6928. return true;
  6929. }
  6930. break;
  6931. default:
  6932. assert(!"Unknown axis");
  6933. }
  6934. return false;
  6935. }
  6936. template <class T> void step_fill(xpath_node_set_raw& ns, xml_node_struct* n, xpath_allocator* alloc, bool once, T)
  6937. {
  6938. const axis_t axis = T::axis;
  6939. switch (axis)
  6940. {
  6941. case axis_attribute:
  6942. {
  6943. for (xml_attribute_struct* a = n->first_attribute; a; a = a->next_attribute)
  6944. if (step_push(ns, a, n, alloc) & once)
  6945. return;
  6946. break;
  6947. }
  6948. case axis_child:
  6949. {
  6950. for (xml_node_struct* c = n->first_child; c; c = c->next_sibling)
  6951. if (step_push(ns, c, alloc) & once)
  6952. return;
  6953. break;
  6954. }
  6955. case axis_descendant:
  6956. case axis_descendant_or_self:
  6957. {
  6958. if (axis == axis_descendant_or_self)
  6959. if (step_push(ns, n, alloc) & once)
  6960. return;
  6961. xml_node_struct* cur = n->first_child;
  6962. while (cur)
  6963. {
  6964. if (step_push(ns, cur, alloc) & once)
  6965. return;
  6966. if (cur->first_child)
  6967. cur = cur->first_child;
  6968. else
  6969. {
  6970. while (!cur->next_sibling)
  6971. {
  6972. cur = cur->parent;
  6973. if (cur == n) return;
  6974. }
  6975. cur = cur->next_sibling;
  6976. }
  6977. }
  6978. break;
  6979. }
  6980. case axis_following_sibling:
  6981. {
  6982. for (xml_node_struct* c = n->next_sibling; c; c = c->next_sibling)
  6983. if (step_push(ns, c, alloc) & once)
  6984. return;
  6985. break;
  6986. }
  6987. case axis_preceding_sibling:
  6988. {
  6989. for (xml_node_struct* c = n->prev_sibling_c; c->next_sibling; c = c->prev_sibling_c)
  6990. if (step_push(ns, c, alloc) & once)
  6991. return;
  6992. break;
  6993. }
  6994. case axis_following:
  6995. {
  6996. xml_node_struct* cur = n;
  6997. // exit from this node so that we don't include descendants
  6998. while (!cur->next_sibling)
  6999. {
  7000. cur = cur->parent;
  7001. if (!cur) return;
  7002. }
  7003. cur = cur->next_sibling;
  7004. while (cur)
  7005. {
  7006. if (step_push(ns, cur, alloc) & once)
  7007. return;
  7008. if (cur->first_child)
  7009. cur = cur->first_child;
  7010. else
  7011. {
  7012. while (!cur->next_sibling)
  7013. {
  7014. cur = cur->parent;
  7015. if (!cur) return;
  7016. }
  7017. cur = cur->next_sibling;
  7018. }
  7019. }
  7020. break;
  7021. }
  7022. case axis_preceding:
  7023. {
  7024. xml_node_struct* cur = n;
  7025. // exit from this node so that we don't include descendants
  7026. while (!cur->prev_sibling_c->next_sibling)
  7027. {
  7028. cur = cur->parent;
  7029. if (!cur) return;
  7030. }
  7031. cur = cur->prev_sibling_c;
  7032. while (cur)
  7033. {
  7034. if (cur->first_child)
  7035. cur = cur->first_child->prev_sibling_c;
  7036. else
  7037. {
  7038. // leaf node, can't be ancestor
  7039. if (step_push(ns, cur, alloc) & once)
  7040. return;
  7041. while (!cur->prev_sibling_c->next_sibling)
  7042. {
  7043. cur = cur->parent;
  7044. if (!cur) return;
  7045. if (!node_is_ancestor(cur, n))
  7046. if (step_push(ns, cur, alloc) & once)
  7047. return;
  7048. }
  7049. cur = cur->prev_sibling_c;
  7050. }
  7051. }
  7052. break;
  7053. }
  7054. case axis_ancestor:
  7055. case axis_ancestor_or_self:
  7056. {
  7057. if (axis == axis_ancestor_or_self)
  7058. if (step_push(ns, n, alloc) & once)
  7059. return;
  7060. xml_node_struct* cur = n->parent;
  7061. while (cur)
  7062. {
  7063. if (step_push(ns, cur, alloc) & once)
  7064. return;
  7065. cur = cur->parent;
  7066. }
  7067. break;
  7068. }
  7069. case axis_self:
  7070. {
  7071. step_push(ns, n, alloc);
  7072. break;
  7073. }
  7074. case axis_parent:
  7075. {
  7076. if (n->parent)
  7077. step_push(ns, n->parent, alloc);
  7078. break;
  7079. }
  7080. default:
  7081. assert(!"Unimplemented axis");
  7082. }
  7083. }
  7084. template <class T> void step_fill(xpath_node_set_raw& ns, xml_attribute_struct* a, xml_node_struct* p, xpath_allocator* alloc, bool once, T v)
  7085. {
  7086. const axis_t axis = T::axis;
  7087. switch (axis)
  7088. {
  7089. case axis_ancestor:
  7090. case axis_ancestor_or_self:
  7091. {
  7092. if (axis == axis_ancestor_or_self && _test == nodetest_type_node) // reject attributes based on principal node type test
  7093. if (step_push(ns, a, p, alloc) & once)
  7094. return;
  7095. xml_node_struct* cur = p;
  7096. while (cur)
  7097. {
  7098. if (step_push(ns, cur, alloc) & once)
  7099. return;
  7100. cur = cur->parent;
  7101. }
  7102. break;
  7103. }
  7104. case axis_descendant_or_self:
  7105. case axis_self:
  7106. {
  7107. if (_test == nodetest_type_node) // reject attributes based on principal node type test
  7108. step_push(ns, a, p, alloc);
  7109. break;
  7110. }
  7111. case axis_following:
  7112. {
  7113. xml_node_struct* cur = p;
  7114. while (cur)
  7115. {
  7116. if (cur->first_child)
  7117. cur = cur->first_child;
  7118. else
  7119. {
  7120. while (!cur->next_sibling)
  7121. {
  7122. cur = cur->parent;
  7123. if (!cur) return;
  7124. }
  7125. cur = cur->next_sibling;
  7126. }
  7127. if (step_push(ns, cur, alloc) & once)
  7128. return;
  7129. }
  7130. break;
  7131. }
  7132. case axis_parent:
  7133. {
  7134. step_push(ns, p, alloc);
  7135. break;
  7136. }
  7137. case axis_preceding:
  7138. {
  7139. // preceding:: axis does not include attribute nodes and attribute ancestors (they are the same as parent's ancestors), so we can reuse node preceding
  7140. step_fill(ns, p, alloc, once, v);
  7141. break;
  7142. }
  7143. default:
  7144. assert(!"Unimplemented axis");
  7145. }
  7146. }
  7147. template <class T> void step_fill(xpath_node_set_raw& ns, const xpath_node& xn, xpath_allocator* alloc, bool once, T v)
  7148. {
  7149. const axis_t axis = T::axis;
  7150. const bool axis_has_attributes = (axis == axis_ancestor || axis == axis_ancestor_or_self || axis == axis_descendant_or_self || axis == axis_following || axis == axis_parent || axis == axis_preceding || axis == axis_self);
  7151. if (xn.node())
  7152. step_fill(ns, xn.node().internal_object(), alloc, once, v);
  7153. else if (axis_has_attributes && xn.attribute() && xn.parent())
  7154. step_fill(ns, xn.attribute().internal_object(), xn.parent().internal_object(), alloc, once, v);
  7155. }
  7156. template <class T> xpath_node_set_raw step_do(const xpath_context& c, const xpath_stack& stack, nodeset_eval_t eval, T v)
  7157. {
  7158. const axis_t axis = T::axis;
  7159. const bool axis_reverse = (axis == axis_ancestor || axis == axis_ancestor_or_self || axis == axis_preceding || axis == axis_preceding_sibling);
  7160. const xpath_node_set::type_t axis_type = axis_reverse ? xpath_node_set::type_sorted_reverse : xpath_node_set::type_sorted;
  7161. bool once =
  7162. (axis == axis_attribute && _test == nodetest_name) ||
  7163. (!_right && eval_once(axis_type, eval)) ||
  7164. (_right && !_right->_next && _right->_test == predicate_constant_one);
  7165. xpath_node_set_raw ns;
  7166. ns.set_type(axis_type);
  7167. if (_left)
  7168. {
  7169. xpath_node_set_raw s = _left->eval_node_set(c, stack, nodeset_eval_all);
  7170. // self axis preserves the original order
  7171. if (axis == axis_self) ns.set_type(s.type());
  7172. for (const xpath_node* it = s.begin(); it != s.end(); ++it)
  7173. {
  7174. size_t size = ns.size();
  7175. // in general, all axes generate elements in a particular order, but there is no order guarantee if axis is applied to two nodes
  7176. if (axis != axis_self && size != 0) ns.set_type(xpath_node_set::type_unsorted);
  7177. step_fill(ns, *it, stack.result, once, v);
  7178. if (_right) apply_predicates(ns, size, stack, eval);
  7179. }
  7180. }
  7181. else
  7182. {
  7183. step_fill(ns, c.n, stack.result, once, v);
  7184. if (_right) apply_predicates(ns, 0, stack, eval);
  7185. }
  7186. // child, attribute and self axes always generate unique set of nodes
  7187. // for other axis, if the set stayed sorted, it stayed unique because the traversal algorithms do not visit the same node twice
  7188. if (axis != axis_child && axis != axis_attribute && axis != axis_self && ns.type() == xpath_node_set::type_unsorted)
  7189. ns.remove_duplicates();
  7190. return ns;
  7191. }
  7192. public:
  7193. xpath_ast_node(ast_type_t type, xpath_value_type rettype_, const char_t* value):
  7194. _type(static_cast<char>(type)), _rettype(static_cast<char>(rettype_)), _axis(0), _test(0), _left(0), _right(0), _next(0)
  7195. {
  7196. assert(type == ast_string_constant);
  7197. _data.string = value;
  7198. }
  7199. xpath_ast_node(ast_type_t type, xpath_value_type rettype_, double value):
  7200. _type(static_cast<char>(type)), _rettype(static_cast<char>(rettype_)), _axis(0), _test(0), _left(0), _right(0), _next(0)
  7201. {
  7202. assert(type == ast_number_constant);
  7203. _data.number = value;
  7204. }
  7205. xpath_ast_node(ast_type_t type, xpath_value_type rettype_, xpath_variable* value):
  7206. _type(static_cast<char>(type)), _rettype(static_cast<char>(rettype_)), _axis(0), _test(0), _left(0), _right(0), _next(0)
  7207. {
  7208. assert(type == ast_variable);
  7209. _data.variable = value;
  7210. }
  7211. xpath_ast_node(ast_type_t type, xpath_value_type rettype_, xpath_ast_node* left = 0, xpath_ast_node* right = 0):
  7212. _type(static_cast<char>(type)), _rettype(static_cast<char>(rettype_)), _axis(0), _test(0), _left(left), _right(right), _next(0)
  7213. {
  7214. }
  7215. xpath_ast_node(ast_type_t type, xpath_ast_node* left, axis_t axis, nodetest_t test, const char_t* contents):
  7216. _type(static_cast<char>(type)), _rettype(xpath_type_node_set), _axis(static_cast<char>(axis)), _test(static_cast<char>(test)), _left(left), _right(0), _next(0)
  7217. {
  7218. assert(type == ast_step);
  7219. _data.nodetest = contents;
  7220. }
  7221. xpath_ast_node(ast_type_t type, xpath_ast_node* left, xpath_ast_node* right, predicate_t test):
  7222. _type(static_cast<char>(type)), _rettype(xpath_type_node_set), _axis(0), _test(static_cast<char>(test)), _left(left), _right(right), _next(0)
  7223. {
  7224. assert(type == ast_filter || type == ast_predicate);
  7225. }
  7226. void set_next(xpath_ast_node* value)
  7227. {
  7228. _next = value;
  7229. }
  7230. void set_right(xpath_ast_node* value)
  7231. {
  7232. _right = value;
  7233. }
  7234. bool eval_boolean(const xpath_context& c, const xpath_stack& stack)
  7235. {
  7236. switch (_type)
  7237. {
  7238. case ast_op_or:
  7239. return _left->eval_boolean(c, stack) || _right->eval_boolean(c, stack);
  7240. case ast_op_and:
  7241. return _left->eval_boolean(c, stack) && _right->eval_boolean(c, stack);
  7242. case ast_op_equal:
  7243. return compare_eq(_left, _right, c, stack, equal_to());
  7244. case ast_op_not_equal:
  7245. return compare_eq(_left, _right, c, stack, not_equal_to());
  7246. case ast_op_less:
  7247. return compare_rel(_left, _right, c, stack, less());
  7248. case ast_op_greater:
  7249. return compare_rel(_right, _left, c, stack, less());
  7250. case ast_op_less_or_equal:
  7251. return compare_rel(_left, _right, c, stack, less_equal());
  7252. case ast_op_greater_or_equal:
  7253. return compare_rel(_right, _left, c, stack, less_equal());
  7254. case ast_func_starts_with:
  7255. {
  7256. xpath_allocator_capture cr(stack.result);
  7257. xpath_string lr = _left->eval_string(c, stack);
  7258. xpath_string rr = _right->eval_string(c, stack);
  7259. return starts_with(lr.c_str(), rr.c_str());
  7260. }
  7261. case ast_func_contains:
  7262. {
  7263. xpath_allocator_capture cr(stack.result);
  7264. xpath_string lr = _left->eval_string(c, stack);
  7265. xpath_string rr = _right->eval_string(c, stack);
  7266. return find_substring(lr.c_str(), rr.c_str()) != 0;
  7267. }
  7268. case ast_func_boolean:
  7269. return _left->eval_boolean(c, stack);
  7270. case ast_func_not:
  7271. return !_left->eval_boolean(c, stack);
  7272. case ast_func_true:
  7273. return true;
  7274. case ast_func_false:
  7275. return false;
  7276. case ast_func_lang:
  7277. {
  7278. if (c.n.attribute()) return false;
  7279. xpath_allocator_capture cr(stack.result);
  7280. xpath_string lang = _left->eval_string(c, stack);
  7281. for (xml_node n = c.n.node(); n; n = n.parent())
  7282. {
  7283. xml_attribute a = n.attribute(PUGIXML_TEXT("xml:lang"));
  7284. if (a)
  7285. {
  7286. const char_t* value = a.value();
  7287. // strnicmp / strncasecmp is not portable
  7288. for (const char_t* lit = lang.c_str(); *lit; ++lit)
  7289. {
  7290. if (tolower_ascii(*lit) != tolower_ascii(*value)) return false;
  7291. ++value;
  7292. }
  7293. return *value == 0 || *value == '-';
  7294. }
  7295. }
  7296. return false;
  7297. }
  7298. case ast_opt_compare_attribute:
  7299. {
  7300. const char_t* value = (_right->_type == ast_string_constant) ? _right->_data.string : _right->_data.variable->get_string();
  7301. xml_attribute attr = c.n.node().attribute(_left->_data.nodetest);
  7302. return attr && strequal(attr.value(), value) && is_xpath_attribute(attr.name());
  7303. }
  7304. case ast_variable:
  7305. {
  7306. assert(_rettype == _data.variable->type());
  7307. if (_rettype == xpath_type_boolean)
  7308. return _data.variable->get_boolean();
  7309. // fallthrough to type conversion
  7310. }
  7311. default:
  7312. {
  7313. switch (_rettype)
  7314. {
  7315. case xpath_type_number:
  7316. return convert_number_to_boolean(eval_number(c, stack));
  7317. case xpath_type_string:
  7318. {
  7319. xpath_allocator_capture cr(stack.result);
  7320. return !eval_string(c, stack).empty();
  7321. }
  7322. case xpath_type_node_set:
  7323. {
  7324. xpath_allocator_capture cr(stack.result);
  7325. return !eval_node_set(c, stack, nodeset_eval_any).empty();
  7326. }
  7327. default:
  7328. assert(!"Wrong expression for return type boolean");
  7329. return false;
  7330. }
  7331. }
  7332. }
  7333. }
  7334. double eval_number(const xpath_context& c, const xpath_stack& stack)
  7335. {
  7336. switch (_type)
  7337. {
  7338. case ast_op_add:
  7339. return _left->eval_number(c, stack) + _right->eval_number(c, stack);
  7340. case ast_op_subtract:
  7341. return _left->eval_number(c, stack) - _right->eval_number(c, stack);
  7342. case ast_op_multiply:
  7343. return _left->eval_number(c, stack) * _right->eval_number(c, stack);
  7344. case ast_op_divide:
  7345. return _left->eval_number(c, stack) / _right->eval_number(c, stack);
  7346. case ast_op_mod:
  7347. return fmod(_left->eval_number(c, stack), _right->eval_number(c, stack));
  7348. case ast_op_negate:
  7349. return -_left->eval_number(c, stack);
  7350. case ast_number_constant:
  7351. return _data.number;
  7352. case ast_func_last:
  7353. return static_cast<double>(c.size);
  7354. case ast_func_position:
  7355. return static_cast<double>(c.position);
  7356. case ast_func_count:
  7357. {
  7358. xpath_allocator_capture cr(stack.result);
  7359. return static_cast<double>(_left->eval_node_set(c, stack, nodeset_eval_all).size());
  7360. }
  7361. case ast_func_string_length_0:
  7362. {
  7363. xpath_allocator_capture cr(stack.result);
  7364. return static_cast<double>(string_value(c.n, stack.result).length());
  7365. }
  7366. case ast_func_string_length_1:
  7367. {
  7368. xpath_allocator_capture cr(stack.result);
  7369. return static_cast<double>(_left->eval_string(c, stack).length());
  7370. }
  7371. case ast_func_number_0:
  7372. {
  7373. xpath_allocator_capture cr(stack.result);
  7374. return convert_string_to_number(string_value(c.n, stack.result).c_str());
  7375. }
  7376. case ast_func_number_1:
  7377. return _left->eval_number(c, stack);
  7378. case ast_func_sum:
  7379. {
  7380. xpath_allocator_capture cr(stack.result);
  7381. double r = 0;
  7382. xpath_node_set_raw ns = _left->eval_node_set(c, stack, nodeset_eval_all);
  7383. for (const xpath_node* it = ns.begin(); it != ns.end(); ++it)
  7384. {
  7385. xpath_allocator_capture cri(stack.result);
  7386. r += convert_string_to_number(string_value(*it, stack.result).c_str());
  7387. }
  7388. return r;
  7389. }
  7390. case ast_func_floor:
  7391. {
  7392. double r = _left->eval_number(c, stack);
  7393. return r == r ? floor(r) : r;
  7394. }
  7395. case ast_func_ceiling:
  7396. {
  7397. double r = _left->eval_number(c, stack);
  7398. return r == r ? ceil(r) : r;
  7399. }
  7400. case ast_func_round:
  7401. return round_nearest_nzero(_left->eval_number(c, stack));
  7402. case ast_variable:
  7403. {
  7404. assert(_rettype == _data.variable->type());
  7405. if (_rettype == xpath_type_number)
  7406. return _data.variable->get_number();
  7407. // fallthrough to type conversion
  7408. }
  7409. default:
  7410. {
  7411. switch (_rettype)
  7412. {
  7413. case xpath_type_boolean:
  7414. return eval_boolean(c, stack) ? 1 : 0;
  7415. case xpath_type_string:
  7416. {
  7417. xpath_allocator_capture cr(stack.result);
  7418. return convert_string_to_number(eval_string(c, stack).c_str());
  7419. }
  7420. case xpath_type_node_set:
  7421. {
  7422. xpath_allocator_capture cr(stack.result);
  7423. return convert_string_to_number(eval_string(c, stack).c_str());
  7424. }
  7425. default:
  7426. assert(!"Wrong expression for return type number");
  7427. return 0;
  7428. }
  7429. }
  7430. }
  7431. }
  7432. xpath_string eval_string_concat(const xpath_context& c, const xpath_stack& stack)
  7433. {
  7434. assert(_type == ast_func_concat);
  7435. xpath_allocator_capture ct(stack.temp);
  7436. // count the string number
  7437. size_t count = 1;
  7438. for (xpath_ast_node* nc = _right; nc; nc = nc->_next) count++;
  7439. // gather all strings
  7440. xpath_string static_buffer[4];
  7441. xpath_string* buffer = static_buffer;
  7442. // allocate on-heap for large concats
  7443. if (count > sizeof(static_buffer) / sizeof(static_buffer[0]))
  7444. {
  7445. buffer = static_cast<xpath_string*>(stack.temp->allocate(count * sizeof(xpath_string)));
  7446. assert(buffer);
  7447. }
  7448. // evaluate all strings to temporary stack
  7449. xpath_stack swapped_stack = {stack.temp, stack.result};
  7450. buffer[0] = _left->eval_string(c, swapped_stack);
  7451. size_t pos = 1;
  7452. for (xpath_ast_node* n = _right; n; n = n->_next, ++pos) buffer[pos] = n->eval_string(c, swapped_stack);
  7453. assert(pos == count);
  7454. // get total length
  7455. size_t length = 0;
  7456. for (size_t i = 0; i < count; ++i) length += buffer[i].length();
  7457. // create final string
  7458. char_t* result = static_cast<char_t*>(stack.result->allocate((length + 1) * sizeof(char_t)));
  7459. assert(result);
  7460. char_t* ri = result;
  7461. for (size_t j = 0; j < count; ++j)
  7462. for (const char_t* bi = buffer[j].c_str(); *bi; ++bi)
  7463. *ri++ = *bi;
  7464. *ri = 0;
  7465. return xpath_string::from_heap_preallocated(result, ri);
  7466. }
  7467. xpath_string eval_string(const xpath_context& c, const xpath_stack& stack)
  7468. {
  7469. switch (_type)
  7470. {
  7471. case ast_string_constant:
  7472. return xpath_string::from_const(_data.string);
  7473. case ast_func_local_name_0:
  7474. {
  7475. xpath_node na = c.n;
  7476. return xpath_string::from_const(local_name(na));
  7477. }
  7478. case ast_func_local_name_1:
  7479. {
  7480. xpath_allocator_capture cr(stack.result);
  7481. xpath_node_set_raw ns = _left->eval_node_set(c, stack, nodeset_eval_first);
  7482. xpath_node na = ns.first();
  7483. return xpath_string::from_const(local_name(na));
  7484. }
  7485. case ast_func_name_0:
  7486. {
  7487. xpath_node na = c.n;
  7488. return xpath_string::from_const(qualified_name(na));
  7489. }
  7490. case ast_func_name_1:
  7491. {
  7492. xpath_allocator_capture cr(stack.result);
  7493. xpath_node_set_raw ns = _left->eval_node_set(c, stack, nodeset_eval_first);
  7494. xpath_node na = ns.first();
  7495. return xpath_string::from_const(qualified_name(na));
  7496. }
  7497. case ast_func_namespace_uri_0:
  7498. {
  7499. xpath_node na = c.n;
  7500. return xpath_string::from_const(namespace_uri(na));
  7501. }
  7502. case ast_func_namespace_uri_1:
  7503. {
  7504. xpath_allocator_capture cr(stack.result);
  7505. xpath_node_set_raw ns = _left->eval_node_set(c, stack, nodeset_eval_first);
  7506. xpath_node na = ns.first();
  7507. return xpath_string::from_const(namespace_uri(na));
  7508. }
  7509. case ast_func_string_0:
  7510. return string_value(c.n, stack.result);
  7511. case ast_func_string_1:
  7512. return _left->eval_string(c, stack);
  7513. case ast_func_concat:
  7514. return eval_string_concat(c, stack);
  7515. case ast_func_substring_before:
  7516. {
  7517. xpath_allocator_capture cr(stack.temp);
  7518. xpath_stack swapped_stack = {stack.temp, stack.result};
  7519. xpath_string s = _left->eval_string(c, swapped_stack);
  7520. xpath_string p = _right->eval_string(c, swapped_stack);
  7521. const char_t* pos = find_substring(s.c_str(), p.c_str());
  7522. return pos ? xpath_string::from_heap(s.c_str(), pos, stack.result) : xpath_string();
  7523. }
  7524. case ast_func_substring_after:
  7525. {
  7526. xpath_allocator_capture cr(stack.temp);
  7527. xpath_stack swapped_stack = {stack.temp, stack.result};
  7528. xpath_string s = _left->eval_string(c, swapped_stack);
  7529. xpath_string p = _right->eval_string(c, swapped_stack);
  7530. const char_t* pos = find_substring(s.c_str(), p.c_str());
  7531. if (!pos) return xpath_string();
  7532. const char_t* rbegin = pos + p.length();
  7533. const char_t* rend = s.c_str() + s.length();
  7534. return s.uses_heap() ? xpath_string::from_heap(rbegin, rend, stack.result) : xpath_string::from_const(rbegin);
  7535. }
  7536. case ast_func_substring_2:
  7537. {
  7538. xpath_allocator_capture cr(stack.temp);
  7539. xpath_stack swapped_stack = {stack.temp, stack.result};
  7540. xpath_string s = _left->eval_string(c, swapped_stack);
  7541. size_t s_length = s.length();
  7542. double first = round_nearest(_right->eval_number(c, stack));
  7543. if (is_nan(first)) return xpath_string(); // NaN
  7544. else if (first >= s_length + 1) return xpath_string();
  7545. size_t pos = first < 1 ? 1 : static_cast<size_t>(first);
  7546. assert(1 <= pos && pos <= s_length + 1);
  7547. const char_t* rbegin = s.c_str() + (pos - 1);
  7548. const char_t* rend = s.c_str() + s.length();
  7549. return s.uses_heap() ? xpath_string::from_heap(rbegin, rend, stack.result) : xpath_string::from_const(rbegin);
  7550. }
  7551. case ast_func_substring_3:
  7552. {
  7553. xpath_allocator_capture cr(stack.temp);
  7554. xpath_stack swapped_stack = {stack.temp, stack.result};
  7555. xpath_string s = _left->eval_string(c, swapped_stack);
  7556. size_t s_length = s.length();
  7557. double first = round_nearest(_right->eval_number(c, stack));
  7558. double last = first + round_nearest(_right->_next->eval_number(c, stack));
  7559. if (is_nan(first) || is_nan(last)) return xpath_string();
  7560. else if (first >= s_length + 1) return xpath_string();
  7561. else if (first >= last) return xpath_string();
  7562. else if (last < 1) return xpath_string();
  7563. size_t pos = first < 1 ? 1 : static_cast<size_t>(first);
  7564. size_t end = last >= s_length + 1 ? s_length + 1 : static_cast<size_t>(last);
  7565. assert(1 <= pos && pos <= end && end <= s_length + 1);
  7566. const char_t* rbegin = s.c_str() + (pos - 1);
  7567. const char_t* rend = s.c_str() + (end - 1);
  7568. return (end == s_length + 1 && !s.uses_heap()) ? xpath_string::from_const(rbegin) : xpath_string::from_heap(rbegin, rend, stack.result);
  7569. }
  7570. case ast_func_normalize_space_0:
  7571. {
  7572. xpath_string s = string_value(c.n, stack.result);
  7573. normalize_space(s.data(stack.result));
  7574. return s;
  7575. }
  7576. case ast_func_normalize_space_1:
  7577. {
  7578. xpath_string s = _left->eval_string(c, stack);
  7579. normalize_space(s.data(stack.result));
  7580. return s;
  7581. }
  7582. case ast_func_translate:
  7583. {
  7584. xpath_allocator_capture cr(stack.temp);
  7585. xpath_stack swapped_stack = {stack.temp, stack.result};
  7586. xpath_string s = _left->eval_string(c, stack);
  7587. xpath_string from = _right->eval_string(c, swapped_stack);
  7588. xpath_string to = _right->_next->eval_string(c, swapped_stack);
  7589. translate(s.data(stack.result), from.c_str(), to.c_str(), to.length());
  7590. return s;
  7591. }
  7592. case ast_opt_translate_table:
  7593. {
  7594. xpath_string s = _left->eval_string(c, stack);
  7595. translate_table(s.data(stack.result), _data.table);
  7596. return s;
  7597. }
  7598. case ast_variable:
  7599. {
  7600. assert(_rettype == _data.variable->type());
  7601. if (_rettype == xpath_type_string)
  7602. return xpath_string::from_const(_data.variable->get_string());
  7603. // fallthrough to type conversion
  7604. }
  7605. default:
  7606. {
  7607. switch (_rettype)
  7608. {
  7609. case xpath_type_boolean:
  7610. return xpath_string::from_const(eval_boolean(c, stack) ? PUGIXML_TEXT("true") : PUGIXML_TEXT("false"));
  7611. case xpath_type_number:
  7612. return convert_number_to_string(eval_number(c, stack), stack.result);
  7613. case xpath_type_node_set:
  7614. {
  7615. xpath_allocator_capture cr(stack.temp);
  7616. xpath_stack swapped_stack = {stack.temp, stack.result};
  7617. xpath_node_set_raw ns = eval_node_set(c, swapped_stack, nodeset_eval_first);
  7618. return ns.empty() ? xpath_string() : string_value(ns.first(), stack.result);
  7619. }
  7620. default:
  7621. assert(!"Wrong expression for return type string");
  7622. return xpath_string();
  7623. }
  7624. }
  7625. }
  7626. }
  7627. xpath_node_set_raw eval_node_set(const xpath_context& c, const xpath_stack& stack, nodeset_eval_t eval)
  7628. {
  7629. switch (_type)
  7630. {
  7631. case ast_op_union:
  7632. {
  7633. xpath_allocator_capture cr(stack.temp);
  7634. xpath_stack swapped_stack = {stack.temp, stack.result};
  7635. xpath_node_set_raw ls = _left->eval_node_set(c, swapped_stack, eval);
  7636. xpath_node_set_raw rs = _right->eval_node_set(c, stack, eval);
  7637. // we can optimize merging two sorted sets, but this is a very rare operation, so don't bother
  7638. rs.set_type(xpath_node_set::type_unsorted);
  7639. rs.append(ls.begin(), ls.end(), stack.result);
  7640. rs.remove_duplicates();
  7641. return rs;
  7642. }
  7643. case ast_filter:
  7644. {
  7645. xpath_node_set_raw set = _left->eval_node_set(c, stack, _test == predicate_constant_one ? nodeset_eval_first : nodeset_eval_all);
  7646. // either expression is a number or it contains position() call; sort by document order
  7647. if (_test != predicate_posinv) set.sort_do();
  7648. bool once = eval_once(set.type(), eval);
  7649. apply_predicate(set, 0, stack, once);
  7650. return set;
  7651. }
  7652. case ast_func_id:
  7653. return xpath_node_set_raw();
  7654. case ast_step:
  7655. {
  7656. switch (_axis)
  7657. {
  7658. case axis_ancestor:
  7659. return step_do(c, stack, eval, axis_to_type<axis_ancestor>());
  7660. case axis_ancestor_or_self:
  7661. return step_do(c, stack, eval, axis_to_type<axis_ancestor_or_self>());
  7662. case axis_attribute:
  7663. return step_do(c, stack, eval, axis_to_type<axis_attribute>());
  7664. case axis_child:
  7665. return step_do(c, stack, eval, axis_to_type<axis_child>());
  7666. case axis_descendant:
  7667. return step_do(c, stack, eval, axis_to_type<axis_descendant>());
  7668. case axis_descendant_or_self:
  7669. return step_do(c, stack, eval, axis_to_type<axis_descendant_or_self>());
  7670. case axis_following:
  7671. return step_do(c, stack, eval, axis_to_type<axis_following>());
  7672. case axis_following_sibling:
  7673. return step_do(c, stack, eval, axis_to_type<axis_following_sibling>());
  7674. case axis_namespace:
  7675. // namespaced axis is not supported
  7676. return xpath_node_set_raw();
  7677. case axis_parent:
  7678. return step_do(c, stack, eval, axis_to_type<axis_parent>());
  7679. case axis_preceding:
  7680. return step_do(c, stack, eval, axis_to_type<axis_preceding>());
  7681. case axis_preceding_sibling:
  7682. return step_do(c, stack, eval, axis_to_type<axis_preceding_sibling>());
  7683. case axis_self:
  7684. return step_do(c, stack, eval, axis_to_type<axis_self>());
  7685. default:
  7686. assert(!"Unknown axis");
  7687. return xpath_node_set_raw();
  7688. }
  7689. }
  7690. case ast_step_root:
  7691. {
  7692. assert(!_right); // root step can't have any predicates
  7693. xpath_node_set_raw ns;
  7694. ns.set_type(xpath_node_set::type_sorted);
  7695. if (c.n.node()) ns.push_back(c.n.node().root(), stack.result);
  7696. else if (c.n.attribute()) ns.push_back(c.n.parent().root(), stack.result);
  7697. return ns;
  7698. }
  7699. case ast_variable:
  7700. {
  7701. assert(_rettype == _data.variable->type());
  7702. if (_rettype == xpath_type_node_set)
  7703. {
  7704. const xpath_node_set& s = _data.variable->get_node_set();
  7705. xpath_node_set_raw ns;
  7706. ns.set_type(s.type());
  7707. ns.append(s.begin(), s.end(), stack.result);
  7708. return ns;
  7709. }
  7710. // fallthrough to type conversion
  7711. }
  7712. default:
  7713. assert(!"Wrong expression for return type node set");
  7714. return xpath_node_set_raw();
  7715. }
  7716. }
  7717. void optimize(xpath_allocator* alloc)
  7718. {
  7719. if (_left) _left->optimize(alloc);
  7720. if (_right) _right->optimize(alloc);
  7721. if (_next) _next->optimize(alloc);
  7722. // Rewrite [position()=expr] with [expr]
  7723. // Note that this step has to go before classification to recognize [position()=1]
  7724. if ((_type == ast_filter || _type == ast_predicate) &&
  7725. _right->_type == ast_op_equal && _right->_left->_type == ast_func_position && _right->_right->_rettype == xpath_type_number)
  7726. {
  7727. _right = _right->_right;
  7728. }
  7729. // Classify filter/predicate ops to perform various optimizations during evaluation
  7730. if (_type == ast_filter || _type == ast_predicate)
  7731. {
  7732. assert(_test == predicate_default);
  7733. if (_right->_type == ast_number_constant && _right->_data.number == 1.0)
  7734. _test = predicate_constant_one;
  7735. else if (_right->_rettype == xpath_type_number && (_right->_type == ast_number_constant || _right->_type == ast_variable || _right->_type == ast_func_last))
  7736. _test = predicate_constant;
  7737. else if (_right->_rettype != xpath_type_number && _right->is_posinv_expr())
  7738. _test = predicate_posinv;
  7739. }
  7740. // Rewrite descendant-or-self::node()/child::foo with descendant::foo
  7741. // The former is a full form of //foo, the latter is much faster since it executes the node test immediately
  7742. // Do a similar kind of rewrite for self/descendant/descendant-or-self axes
  7743. // Note that we only rewrite positionally invariant steps (//foo[1] != /descendant::foo[1])
  7744. if (_type == ast_step && (_axis == axis_child || _axis == axis_self || _axis == axis_descendant || _axis == axis_descendant_or_self) && _left &&
  7745. _left->_type == ast_step && _left->_axis == axis_descendant_or_self && _left->_test == nodetest_type_node && !_left->_right &&
  7746. is_posinv_step())
  7747. {
  7748. if (_axis == axis_child || _axis == axis_descendant)
  7749. _axis = axis_descendant;
  7750. else
  7751. _axis = axis_descendant_or_self;
  7752. _left = _left->_left;
  7753. }
  7754. // Use optimized lookup table implementation for translate() with constant arguments
  7755. if (_type == ast_func_translate && _right->_type == ast_string_constant && _right->_next->_type == ast_string_constant)
  7756. {
  7757. unsigned char* table = translate_table_generate(alloc, _right->_data.string, _right->_next->_data.string);
  7758. if (table)
  7759. {
  7760. _type = ast_opt_translate_table;
  7761. _data.table = table;
  7762. }
  7763. }
  7764. // Use optimized path for @attr = 'value' or @attr = $value
  7765. if (_type == ast_op_equal &&
  7766. _left->_type == ast_step && _left->_axis == axis_attribute && _left->_test == nodetest_name && !_left->_left && !_left->_right &&
  7767. (_right->_type == ast_string_constant || (_right->_type == ast_variable && _right->_rettype == xpath_type_string)))
  7768. {
  7769. _type = ast_opt_compare_attribute;
  7770. }
  7771. }
  7772. bool is_posinv_expr() const
  7773. {
  7774. switch (_type)
  7775. {
  7776. case ast_func_position:
  7777. case ast_func_last:
  7778. return false;
  7779. case ast_string_constant:
  7780. case ast_number_constant:
  7781. case ast_variable:
  7782. return true;
  7783. case ast_step:
  7784. case ast_step_root:
  7785. return true;
  7786. case ast_predicate:
  7787. case ast_filter:
  7788. return true;
  7789. default:
  7790. if (_left && !_left->is_posinv_expr()) return false;
  7791. for (xpath_ast_node* n = _right; n; n = n->_next)
  7792. if (!n->is_posinv_expr()) return false;
  7793. return true;
  7794. }
  7795. }
  7796. bool is_posinv_step() const
  7797. {
  7798. assert(_type == ast_step);
  7799. for (xpath_ast_node* n = _right; n; n = n->_next)
  7800. {
  7801. assert(n->_type == ast_predicate);
  7802. if (n->_test != predicate_posinv)
  7803. return false;
  7804. }
  7805. return true;
  7806. }
  7807. xpath_value_type rettype() const
  7808. {
  7809. return static_cast<xpath_value_type>(_rettype);
  7810. }
  7811. };
  7812. struct xpath_parser
  7813. {
  7814. xpath_allocator* _alloc;
  7815. xpath_lexer _lexer;
  7816. const char_t* _query;
  7817. xpath_variable_set* _variables;
  7818. xpath_parse_result* _result;
  7819. char_t _scratch[32];
  7820. #ifdef PUGIXML_NO_EXCEPTIONS
  7821. jmp_buf _error_handler;
  7822. #endif
  7823. void throw_error(const char* message)
  7824. {
  7825. _result->error = message;
  7826. _result->offset = _lexer.current_pos() - _query;
  7827. #ifdef PUGIXML_NO_EXCEPTIONS
  7828. longjmp(_error_handler, 1);
  7829. #else
  7830. throw xpath_exception(*_result);
  7831. #endif
  7832. }
  7833. void throw_error_oom()
  7834. {
  7835. #ifdef PUGIXML_NO_EXCEPTIONS
  7836. throw_error("Out of memory");
  7837. #else
  7838. throw std::bad_alloc();
  7839. #endif
  7840. }
  7841. void* alloc_node()
  7842. {
  7843. void* result = _alloc->allocate_nothrow(sizeof(xpath_ast_node));
  7844. if (!result) throw_error_oom();
  7845. return result;
  7846. }
  7847. const char_t* alloc_string(const xpath_lexer_string& value)
  7848. {
  7849. if (value.begin)
  7850. {
  7851. size_t length = static_cast<size_t>(value.end - value.begin);
  7852. char_t* c = static_cast<char_t*>(_alloc->allocate_nothrow((length + 1) * sizeof(char_t)));
  7853. if (!c) throw_error_oom();
  7854. assert(c); // workaround for clang static analysis
  7855. memcpy(c, value.begin, length * sizeof(char_t));
  7856. c[length] = 0;
  7857. return c;
  7858. }
  7859. else return 0;
  7860. }
  7861. xpath_ast_node* parse_function_helper(ast_type_t type0, ast_type_t type1, size_t argc, xpath_ast_node* args[2])
  7862. {
  7863. assert(argc <= 1);
  7864. if (argc == 1 && args[0]->rettype() != xpath_type_node_set) throw_error("Function has to be applied to node set");
  7865. return new (alloc_node()) xpath_ast_node(argc == 0 ? type0 : type1, xpath_type_string, args[0]);
  7866. }
  7867. xpath_ast_node* parse_function(const xpath_lexer_string& name, size_t argc, xpath_ast_node* args[2])
  7868. {
  7869. switch (name.begin[0])
  7870. {
  7871. case 'b':
  7872. if (name == PUGIXML_TEXT("boolean") && argc == 1)
  7873. return new (alloc_node()) xpath_ast_node(ast_func_boolean, xpath_type_boolean, args[0]);
  7874. break;
  7875. case 'c':
  7876. if (name == PUGIXML_TEXT("count") && argc == 1)
  7877. {
  7878. if (args[0]->rettype() != xpath_type_node_set) throw_error("Function has to be applied to node set");
  7879. return new (alloc_node()) xpath_ast_node(ast_func_count, xpath_type_number, args[0]);
  7880. }
  7881. else if (name == PUGIXML_TEXT("contains") && argc == 2)
  7882. return new (alloc_node()) xpath_ast_node(ast_func_contains, xpath_type_boolean, args[0], args[1]);
  7883. else if (name == PUGIXML_TEXT("concat") && argc >= 2)
  7884. return new (alloc_node()) xpath_ast_node(ast_func_concat, xpath_type_string, args[0], args[1]);
  7885. else if (name == PUGIXML_TEXT("ceiling") && argc == 1)
  7886. return new (alloc_node()) xpath_ast_node(ast_func_ceiling, xpath_type_number, args[0]);
  7887. break;
  7888. case 'f':
  7889. if (name == PUGIXML_TEXT("false") && argc == 0)
  7890. return new (alloc_node()) xpath_ast_node(ast_func_false, xpath_type_boolean);
  7891. else if (name == PUGIXML_TEXT("floor") && argc == 1)
  7892. return new (alloc_node()) xpath_ast_node(ast_func_floor, xpath_type_number, args[0]);
  7893. break;
  7894. case 'i':
  7895. if (name == PUGIXML_TEXT("id") && argc == 1)
  7896. return new (alloc_node()) xpath_ast_node(ast_func_id, xpath_type_node_set, args[0]);
  7897. break;
  7898. case 'l':
  7899. if (name == PUGIXML_TEXT("last") && argc == 0)
  7900. return new (alloc_node()) xpath_ast_node(ast_func_last, xpath_type_number);
  7901. else if (name == PUGIXML_TEXT("lang") && argc == 1)
  7902. return new (alloc_node()) xpath_ast_node(ast_func_lang, xpath_type_boolean, args[0]);
  7903. else if (name == PUGIXML_TEXT("local-name") && argc <= 1)
  7904. return parse_function_helper(ast_func_local_name_0, ast_func_local_name_1, argc, args);
  7905. break;
  7906. case 'n':
  7907. if (name == PUGIXML_TEXT("name") && argc <= 1)
  7908. return parse_function_helper(ast_func_name_0, ast_func_name_1, argc, args);
  7909. else if (name == PUGIXML_TEXT("namespace-uri") && argc <= 1)
  7910. return parse_function_helper(ast_func_namespace_uri_0, ast_func_namespace_uri_1, argc, args);
  7911. else if (name == PUGIXML_TEXT("normalize-space") && argc <= 1)
  7912. return new (alloc_node()) xpath_ast_node(argc == 0 ? ast_func_normalize_space_0 : ast_func_normalize_space_1, xpath_type_string, args[0], args[1]);
  7913. else if (name == PUGIXML_TEXT("not") && argc == 1)
  7914. return new (alloc_node()) xpath_ast_node(ast_func_not, xpath_type_boolean, args[0]);
  7915. else if (name == PUGIXML_TEXT("number") && argc <= 1)
  7916. return new (alloc_node()) xpath_ast_node(argc == 0 ? ast_func_number_0 : ast_func_number_1, xpath_type_number, args[0]);
  7917. break;
  7918. case 'p':
  7919. if (name == PUGIXML_TEXT("position") && argc == 0)
  7920. return new (alloc_node()) xpath_ast_node(ast_func_position, xpath_type_number);
  7921. break;
  7922. case 'r':
  7923. if (name == PUGIXML_TEXT("round") && argc == 1)
  7924. return new (alloc_node()) xpath_ast_node(ast_func_round, xpath_type_number, args[0]);
  7925. break;
  7926. case 's':
  7927. if (name == PUGIXML_TEXT("string") && argc <= 1)
  7928. return new (alloc_node()) xpath_ast_node(argc == 0 ? ast_func_string_0 : ast_func_string_1, xpath_type_string, args[0]);
  7929. else if (name == PUGIXML_TEXT("string-length") && argc <= 1)
  7930. return new (alloc_node()) xpath_ast_node(argc == 0 ? ast_func_string_length_0 : ast_func_string_length_1, xpath_type_number, args[0]);
  7931. else if (name == PUGIXML_TEXT("starts-with") && argc == 2)
  7932. return new (alloc_node()) xpath_ast_node(ast_func_starts_with, xpath_type_boolean, args[0], args[1]);
  7933. else if (name == PUGIXML_TEXT("substring-before") && argc == 2)
  7934. return new (alloc_node()) xpath_ast_node(ast_func_substring_before, xpath_type_string, args[0], args[1]);
  7935. else if (name == PUGIXML_TEXT("substring-after") && argc == 2)
  7936. return new (alloc_node()) xpath_ast_node(ast_func_substring_after, xpath_type_string, args[0], args[1]);
  7937. else if (name == PUGIXML_TEXT("substring") && (argc == 2 || argc == 3))
  7938. return new (alloc_node()) xpath_ast_node(argc == 2 ? ast_func_substring_2 : ast_func_substring_3, xpath_type_string, args[0], args[1]);
  7939. else if (name == PUGIXML_TEXT("sum") && argc == 1)
  7940. {
  7941. if (args[0]->rettype() != xpath_type_node_set) throw_error("Function has to be applied to node set");
  7942. return new (alloc_node()) xpath_ast_node(ast_func_sum, xpath_type_number, args[0]);
  7943. }
  7944. break;
  7945. case 't':
  7946. if (name == PUGIXML_TEXT("translate") && argc == 3)
  7947. return new (alloc_node()) xpath_ast_node(ast_func_translate, xpath_type_string, args[0], args[1]);
  7948. else if (name == PUGIXML_TEXT("true") && argc == 0)
  7949. return new (alloc_node()) xpath_ast_node(ast_func_true, xpath_type_boolean);
  7950. break;
  7951. default:
  7952. break;
  7953. }
  7954. throw_error("Unrecognized function or wrong parameter count");
  7955. return 0;
  7956. }
  7957. axis_t parse_axis_name(const xpath_lexer_string& name, bool& specified)
  7958. {
  7959. specified = true;
  7960. switch (name.begin[0])
  7961. {
  7962. case 'a':
  7963. if (name == PUGIXML_TEXT("ancestor"))
  7964. return axis_ancestor;
  7965. else if (name == PUGIXML_TEXT("ancestor-or-self"))
  7966. return axis_ancestor_or_self;
  7967. else if (name == PUGIXML_TEXT("attribute"))
  7968. return axis_attribute;
  7969. break;
  7970. case 'c':
  7971. if (name == PUGIXML_TEXT("child"))
  7972. return axis_child;
  7973. break;
  7974. case 'd':
  7975. if (name == PUGIXML_TEXT("descendant"))
  7976. return axis_descendant;
  7977. else if (name == PUGIXML_TEXT("descendant-or-self"))
  7978. return axis_descendant_or_self;
  7979. break;
  7980. case 'f':
  7981. if (name == PUGIXML_TEXT("following"))
  7982. return axis_following;
  7983. else if (name == PUGIXML_TEXT("following-sibling"))
  7984. return axis_following_sibling;
  7985. break;
  7986. case 'n':
  7987. if (name == PUGIXML_TEXT("namespace"))
  7988. return axis_namespace;
  7989. break;
  7990. case 'p':
  7991. if (name == PUGIXML_TEXT("parent"))
  7992. return axis_parent;
  7993. else if (name == PUGIXML_TEXT("preceding"))
  7994. return axis_preceding;
  7995. else if (name == PUGIXML_TEXT("preceding-sibling"))
  7996. return axis_preceding_sibling;
  7997. break;
  7998. case 's':
  7999. if (name == PUGIXML_TEXT("self"))
  8000. return axis_self;
  8001. break;
  8002. default:
  8003. break;
  8004. }
  8005. specified = false;
  8006. return axis_child;
  8007. }
  8008. nodetest_t parse_node_test_type(const xpath_lexer_string& name)
  8009. {
  8010. switch (name.begin[0])
  8011. {
  8012. case 'c':
  8013. if (name == PUGIXML_TEXT("comment"))
  8014. return nodetest_type_comment;
  8015. break;
  8016. case 'n':
  8017. if (name == PUGIXML_TEXT("node"))
  8018. return nodetest_type_node;
  8019. break;
  8020. case 'p':
  8021. if (name == PUGIXML_TEXT("processing-instruction"))
  8022. return nodetest_type_pi;
  8023. break;
  8024. case 't':
  8025. if (name == PUGIXML_TEXT("text"))
  8026. return nodetest_type_text;
  8027. break;
  8028. default:
  8029. break;
  8030. }
  8031. return nodetest_none;
  8032. }
  8033. // PrimaryExpr ::= VariableReference | '(' Expr ')' | Literal | Number | FunctionCall
  8034. xpath_ast_node* parse_primary_expression()
  8035. {
  8036. switch (_lexer.current())
  8037. {
  8038. case lex_var_ref:
  8039. {
  8040. xpath_lexer_string name = _lexer.contents();
  8041. if (!_variables)
  8042. throw_error("Unknown variable: variable set is not provided");
  8043. xpath_variable* var = get_variable_scratch(_scratch, _variables, name.begin, name.end);
  8044. if (!var)
  8045. throw_error("Unknown variable: variable set does not contain the given name");
  8046. _lexer.next();
  8047. return new (alloc_node()) xpath_ast_node(ast_variable, var->type(), var);
  8048. }
  8049. case lex_open_brace:
  8050. {
  8051. _lexer.next();
  8052. xpath_ast_node* n = parse_expression();
  8053. if (_lexer.current() != lex_close_brace)
  8054. throw_error("Unmatched braces");
  8055. _lexer.next();
  8056. return n;
  8057. }
  8058. case lex_quoted_string:
  8059. {
  8060. const char_t* value = alloc_string(_lexer.contents());
  8061. xpath_ast_node* n = new (alloc_node()) xpath_ast_node(ast_string_constant, xpath_type_string, value);
  8062. _lexer.next();
  8063. return n;
  8064. }
  8065. case lex_number:
  8066. {
  8067. double value = 0;
  8068. if (!convert_string_to_number_scratch(_scratch, _lexer.contents().begin, _lexer.contents().end, &value))
  8069. throw_error_oom();
  8070. xpath_ast_node* n = new (alloc_node()) xpath_ast_node(ast_number_constant, xpath_type_number, value);
  8071. _lexer.next();
  8072. return n;
  8073. }
  8074. case lex_string:
  8075. {
  8076. xpath_ast_node* args[2] = {0};
  8077. size_t argc = 0;
  8078. xpath_lexer_string function = _lexer.contents();
  8079. _lexer.next();
  8080. xpath_ast_node* last_arg = 0;
  8081. if (_lexer.current() != lex_open_brace)
  8082. throw_error("Unrecognized function call");
  8083. _lexer.next();
  8084. if (_lexer.current() != lex_close_brace)
  8085. args[argc++] = parse_expression();
  8086. while (_lexer.current() != lex_close_brace)
  8087. {
  8088. if (_lexer.current() != lex_comma)
  8089. throw_error("No comma between function arguments");
  8090. _lexer.next();
  8091. xpath_ast_node* n = parse_expression();
  8092. if (argc < 2) args[argc] = n;
  8093. else last_arg->set_next(n);
  8094. argc++;
  8095. last_arg = n;
  8096. }
  8097. _lexer.next();
  8098. return parse_function(function, argc, args);
  8099. }
  8100. default:
  8101. throw_error("Unrecognizable primary expression");
  8102. return 0;
  8103. }
  8104. }
  8105. // FilterExpr ::= PrimaryExpr | FilterExpr Predicate
  8106. // Predicate ::= '[' PredicateExpr ']'
  8107. // PredicateExpr ::= Expr
  8108. xpath_ast_node* parse_filter_expression()
  8109. {
  8110. xpath_ast_node* n = parse_primary_expression();
  8111. while (_lexer.current() == lex_open_square_brace)
  8112. {
  8113. _lexer.next();
  8114. xpath_ast_node* expr = parse_expression();
  8115. if (n->rettype() != xpath_type_node_set) throw_error("Predicate has to be applied to node set");
  8116. n = new (alloc_node()) xpath_ast_node(ast_filter, n, expr, predicate_default);
  8117. if (_lexer.current() != lex_close_square_brace)
  8118. throw_error("Unmatched square brace");
  8119. _lexer.next();
  8120. }
  8121. return n;
  8122. }
  8123. // Step ::= AxisSpecifier NodeTest Predicate* | AbbreviatedStep
  8124. // AxisSpecifier ::= AxisName '::' | '@'?
  8125. // NodeTest ::= NameTest | NodeType '(' ')' | 'processing-instruction' '(' Literal ')'
  8126. // NameTest ::= '*' | NCName ':' '*' | QName
  8127. // AbbreviatedStep ::= '.' | '..'
  8128. xpath_ast_node* parse_step(xpath_ast_node* set)
  8129. {
  8130. if (set && set->rettype() != xpath_type_node_set)
  8131. throw_error("Step has to be applied to node set");
  8132. bool axis_specified = false;
  8133. axis_t axis = axis_child; // implied child axis
  8134. if (_lexer.current() == lex_axis_attribute)
  8135. {
  8136. axis = axis_attribute;
  8137. axis_specified = true;
  8138. _lexer.next();
  8139. }
  8140. else if (_lexer.current() == lex_dot)
  8141. {
  8142. _lexer.next();
  8143. return new (alloc_node()) xpath_ast_node(ast_step, set, axis_self, nodetest_type_node, 0);
  8144. }
  8145. else if (_lexer.current() == lex_double_dot)
  8146. {
  8147. _lexer.next();
  8148. return new (alloc_node()) xpath_ast_node(ast_step, set, axis_parent, nodetest_type_node, 0);
  8149. }
  8150. nodetest_t nt_type = nodetest_none;
  8151. xpath_lexer_string nt_name;
  8152. if (_lexer.current() == lex_string)
  8153. {
  8154. // node name test
  8155. nt_name = _lexer.contents();
  8156. _lexer.next();
  8157. // was it an axis name?
  8158. if (_lexer.current() == lex_double_colon)
  8159. {
  8160. // parse axis name
  8161. if (axis_specified) throw_error("Two axis specifiers in one step");
  8162. axis = parse_axis_name(nt_name, axis_specified);
  8163. if (!axis_specified) throw_error("Unknown axis");
  8164. // read actual node test
  8165. _lexer.next();
  8166. if (_lexer.current() == lex_multiply)
  8167. {
  8168. nt_type = nodetest_all;
  8169. nt_name = xpath_lexer_string();
  8170. _lexer.next();
  8171. }
  8172. else if (_lexer.current() == lex_string)
  8173. {
  8174. nt_name = _lexer.contents();
  8175. _lexer.next();
  8176. }
  8177. else throw_error("Unrecognized node test");
  8178. }
  8179. if (nt_type == nodetest_none)
  8180. {
  8181. // node type test or processing-instruction
  8182. if (_lexer.current() == lex_open_brace)
  8183. {
  8184. _lexer.next();
  8185. if (_lexer.current() == lex_close_brace)
  8186. {
  8187. _lexer.next();
  8188. nt_type = parse_node_test_type(nt_name);
  8189. if (nt_type == nodetest_none) throw_error("Unrecognized node type");
  8190. nt_name = xpath_lexer_string();
  8191. }
  8192. else if (nt_name == PUGIXML_TEXT("processing-instruction"))
  8193. {
  8194. if (_lexer.current() != lex_quoted_string)
  8195. throw_error("Only literals are allowed as arguments to processing-instruction()");
  8196. nt_type = nodetest_pi;
  8197. nt_name = _lexer.contents();
  8198. _lexer.next();
  8199. if (_lexer.current() != lex_close_brace)
  8200. throw_error("Unmatched brace near processing-instruction()");
  8201. _lexer.next();
  8202. }
  8203. else
  8204. throw_error("Unmatched brace near node type test");
  8205. }
  8206. // QName or NCName:*
  8207. else
  8208. {
  8209. if (nt_name.end - nt_name.begin > 2 && nt_name.end[-2] == ':' && nt_name.end[-1] == '*') // NCName:*
  8210. {
  8211. nt_name.end--; // erase *
  8212. nt_type = nodetest_all_in_namespace;
  8213. }
  8214. else nt_type = nodetest_name;
  8215. }
  8216. }
  8217. }
  8218. else if (_lexer.current() == lex_multiply)
  8219. {
  8220. nt_type = nodetest_all;
  8221. _lexer.next();
  8222. }
  8223. else throw_error("Unrecognized node test");
  8224. xpath_ast_node* n = new (alloc_node()) xpath_ast_node(ast_step, set, axis, nt_type, alloc_string(nt_name));
  8225. xpath_ast_node* last = 0;
  8226. while (_lexer.current() == lex_open_square_brace)
  8227. {
  8228. _lexer.next();
  8229. xpath_ast_node* expr = parse_expression();
  8230. xpath_ast_node* pred = new (alloc_node()) xpath_ast_node(ast_predicate, 0, expr, predicate_default);
  8231. if (_lexer.current() != lex_close_square_brace)
  8232. throw_error("Unmatched square brace");
  8233. _lexer.next();
  8234. if (last) last->set_next(pred);
  8235. else n->set_right(pred);
  8236. last = pred;
  8237. }
  8238. return n;
  8239. }
  8240. // RelativeLocationPath ::= Step | RelativeLocationPath '/' Step | RelativeLocationPath '//' Step
  8241. xpath_ast_node* parse_relative_location_path(xpath_ast_node* set)
  8242. {
  8243. xpath_ast_node* n = parse_step(set);
  8244. while (_lexer.current() == lex_slash || _lexer.current() == lex_double_slash)
  8245. {
  8246. lexeme_t l = _lexer.current();
  8247. _lexer.next();
  8248. if (l == lex_double_slash)
  8249. n = new (alloc_node()) xpath_ast_node(ast_step, n, axis_descendant_or_self, nodetest_type_node, 0);
  8250. n = parse_step(n);
  8251. }
  8252. return n;
  8253. }
  8254. // LocationPath ::= RelativeLocationPath | AbsoluteLocationPath
  8255. // AbsoluteLocationPath ::= '/' RelativeLocationPath? | '//' RelativeLocationPath
  8256. xpath_ast_node* parse_location_path()
  8257. {
  8258. if (_lexer.current() == lex_slash)
  8259. {
  8260. _lexer.next();
  8261. xpath_ast_node* n = new (alloc_node()) xpath_ast_node(ast_step_root, xpath_type_node_set);
  8262. // relative location path can start from axis_attribute, dot, double_dot, multiply and string lexemes; any other lexeme means standalone root path
  8263. lexeme_t l = _lexer.current();
  8264. if (l == lex_string || l == lex_axis_attribute || l == lex_dot || l == lex_double_dot || l == lex_multiply)
  8265. return parse_relative_location_path(n);
  8266. else
  8267. return n;
  8268. }
  8269. else if (_lexer.current() == lex_double_slash)
  8270. {
  8271. _lexer.next();
  8272. xpath_ast_node* n = new (alloc_node()) xpath_ast_node(ast_step_root, xpath_type_node_set);
  8273. n = new (alloc_node()) xpath_ast_node(ast_step, n, axis_descendant_or_self, nodetest_type_node, 0);
  8274. return parse_relative_location_path(n);
  8275. }
  8276. // else clause moved outside of if because of bogus warning 'control may reach end of non-void function being inlined' in gcc 4.0.1
  8277. return parse_relative_location_path(0);
  8278. }
  8279. // PathExpr ::= LocationPath
  8280. // | FilterExpr
  8281. // | FilterExpr '/' RelativeLocationPath
  8282. // | FilterExpr '//' RelativeLocationPath
  8283. // UnionExpr ::= PathExpr | UnionExpr '|' PathExpr
  8284. // UnaryExpr ::= UnionExpr | '-' UnaryExpr
  8285. xpath_ast_node* parse_path_or_unary_expression()
  8286. {
  8287. // Clarification.
  8288. // PathExpr begins with either LocationPath or FilterExpr.
  8289. // FilterExpr begins with PrimaryExpr
  8290. // PrimaryExpr begins with '$' in case of it being a variable reference,
  8291. // '(' in case of it being an expression, string literal, number constant or
  8292. // function call.
  8293. if (_lexer.current() == lex_var_ref || _lexer.current() == lex_open_brace ||
  8294. _lexer.current() == lex_quoted_string || _lexer.current() == lex_number ||
  8295. _lexer.current() == lex_string)
  8296. {
  8297. if (_lexer.current() == lex_string)
  8298. {
  8299. // This is either a function call, or not - if not, we shall proceed with location path
  8300. const char_t* state = _lexer.state();
  8301. while (PUGI__IS_CHARTYPE(*state, ct_space)) ++state;
  8302. if (*state != '(') return parse_location_path();
  8303. // This looks like a function call; however this still can be a node-test. Check it.
  8304. if (parse_node_test_type(_lexer.contents()) != nodetest_none) return parse_location_path();
  8305. }
  8306. xpath_ast_node* n = parse_filter_expression();
  8307. if (_lexer.current() == lex_slash || _lexer.current() == lex_double_slash)
  8308. {
  8309. lexeme_t l = _lexer.current();
  8310. _lexer.next();
  8311. if (l == lex_double_slash)
  8312. {
  8313. if (n->rettype() != xpath_type_node_set) throw_error("Step has to be applied to node set");
  8314. n = new (alloc_node()) xpath_ast_node(ast_step, n, axis_descendant_or_self, nodetest_type_node, 0);
  8315. }
  8316. // select from location path
  8317. return parse_relative_location_path(n);
  8318. }
  8319. return n;
  8320. }
  8321. else if (_lexer.current() == lex_minus)
  8322. {
  8323. _lexer.next();
  8324. // precedence 7+ - only parses union expressions
  8325. xpath_ast_node* expr = parse_expression_rec(parse_path_or_unary_expression(), 7);
  8326. return new (alloc_node()) xpath_ast_node(ast_op_negate, xpath_type_number, expr);
  8327. }
  8328. else
  8329. return parse_location_path();
  8330. }
  8331. struct binary_op_t
  8332. {
  8333. ast_type_t asttype;
  8334. xpath_value_type rettype;
  8335. int precedence;
  8336. binary_op_t(): asttype(ast_unknown), rettype(xpath_type_none), precedence(0)
  8337. {
  8338. }
  8339. binary_op_t(ast_type_t asttype_, xpath_value_type rettype_, int precedence_): asttype(asttype_), rettype(rettype_), precedence(precedence_)
  8340. {
  8341. }
  8342. static binary_op_t parse(xpath_lexer& lexer)
  8343. {
  8344. switch (lexer.current())
  8345. {
  8346. case lex_string:
  8347. if (lexer.contents() == PUGIXML_TEXT("or"))
  8348. return binary_op_t(ast_op_or, xpath_type_boolean, 1);
  8349. else if (lexer.contents() == PUGIXML_TEXT("and"))
  8350. return binary_op_t(ast_op_and, xpath_type_boolean, 2);
  8351. else if (lexer.contents() == PUGIXML_TEXT("div"))
  8352. return binary_op_t(ast_op_divide, xpath_type_number, 6);
  8353. else if (lexer.contents() == PUGIXML_TEXT("mod"))
  8354. return binary_op_t(ast_op_mod, xpath_type_number, 6);
  8355. else
  8356. return binary_op_t();
  8357. case lex_equal:
  8358. return binary_op_t(ast_op_equal, xpath_type_boolean, 3);
  8359. case lex_not_equal:
  8360. return binary_op_t(ast_op_not_equal, xpath_type_boolean, 3);
  8361. case lex_less:
  8362. return binary_op_t(ast_op_less, xpath_type_boolean, 4);
  8363. case lex_greater:
  8364. return binary_op_t(ast_op_greater, xpath_type_boolean, 4);
  8365. case lex_less_or_equal:
  8366. return binary_op_t(ast_op_less_or_equal, xpath_type_boolean, 4);
  8367. case lex_greater_or_equal:
  8368. return binary_op_t(ast_op_greater_or_equal, xpath_type_boolean, 4);
  8369. case lex_plus:
  8370. return binary_op_t(ast_op_add, xpath_type_number, 5);
  8371. case lex_minus:
  8372. return binary_op_t(ast_op_subtract, xpath_type_number, 5);
  8373. case lex_multiply:
  8374. return binary_op_t(ast_op_multiply, xpath_type_number, 6);
  8375. case lex_union:
  8376. return binary_op_t(ast_op_union, xpath_type_node_set, 7);
  8377. default:
  8378. return binary_op_t();
  8379. }
  8380. }
  8381. };
  8382. xpath_ast_node* parse_expression_rec(xpath_ast_node* lhs, int limit)
  8383. {
  8384. binary_op_t op = binary_op_t::parse(_lexer);
  8385. while (op.asttype != ast_unknown && op.precedence >= limit)
  8386. {
  8387. _lexer.next();
  8388. xpath_ast_node* rhs = parse_path_or_unary_expression();
  8389. binary_op_t nextop = binary_op_t::parse(_lexer);
  8390. while (nextop.asttype != ast_unknown && nextop.precedence > op.precedence)
  8391. {
  8392. rhs = parse_expression_rec(rhs, nextop.precedence);
  8393. nextop = binary_op_t::parse(_lexer);
  8394. }
  8395. if (op.asttype == ast_op_union && (lhs->rettype() != xpath_type_node_set || rhs->rettype() != xpath_type_node_set))
  8396. throw_error("Union operator has to be applied to node sets");
  8397. lhs = new (alloc_node()) xpath_ast_node(op.asttype, op.rettype, lhs, rhs);
  8398. op = binary_op_t::parse(_lexer);
  8399. }
  8400. return lhs;
  8401. }
  8402. // Expr ::= OrExpr
  8403. // OrExpr ::= AndExpr | OrExpr 'or' AndExpr
  8404. // AndExpr ::= EqualityExpr | AndExpr 'and' EqualityExpr
  8405. // EqualityExpr ::= RelationalExpr
  8406. // | EqualityExpr '=' RelationalExpr
  8407. // | EqualityExpr '!=' RelationalExpr
  8408. // RelationalExpr ::= AdditiveExpr
  8409. // | RelationalExpr '<' AdditiveExpr
  8410. // | RelationalExpr '>' AdditiveExpr
  8411. // | RelationalExpr '<=' AdditiveExpr
  8412. // | RelationalExpr '>=' AdditiveExpr
  8413. // AdditiveExpr ::= MultiplicativeExpr
  8414. // | AdditiveExpr '+' MultiplicativeExpr
  8415. // | AdditiveExpr '-' MultiplicativeExpr
  8416. // MultiplicativeExpr ::= UnaryExpr
  8417. // | MultiplicativeExpr '*' UnaryExpr
  8418. // | MultiplicativeExpr 'div' UnaryExpr
  8419. // | MultiplicativeExpr 'mod' UnaryExpr
  8420. xpath_ast_node* parse_expression()
  8421. {
  8422. return parse_expression_rec(parse_path_or_unary_expression(), 0);
  8423. }
  8424. xpath_parser(const char_t* query, xpath_variable_set* variables, xpath_allocator* alloc, xpath_parse_result* result): _alloc(alloc), _lexer(query), _query(query), _variables(variables), _result(result)
  8425. {
  8426. }
  8427. xpath_ast_node* parse()
  8428. {
  8429. xpath_ast_node* result = parse_expression();
  8430. if (_lexer.current() != lex_eof)
  8431. {
  8432. // there are still unparsed tokens left, error
  8433. throw_error("Incorrect query");
  8434. }
  8435. return result;
  8436. }
  8437. static xpath_ast_node* parse(const char_t* query, xpath_variable_set* variables, xpath_allocator* alloc, xpath_parse_result* result)
  8438. {
  8439. xpath_parser parser(query, variables, alloc, result);
  8440. #ifdef PUGIXML_NO_EXCEPTIONS
  8441. int error = setjmp(parser._error_handler);
  8442. return (error == 0) ? parser.parse() : 0;
  8443. #else
  8444. return parser.parse();
  8445. #endif
  8446. }
  8447. };
  8448. struct xpath_query_impl
  8449. {
  8450. static xpath_query_impl* create()
  8451. {
  8452. void* memory = xml_memory::allocate(sizeof(xpath_query_impl));
  8453. return new (memory) xpath_query_impl();
  8454. }
  8455. static void destroy(void* ptr)
  8456. {
  8457. if (!ptr) return;
  8458. // free all allocated pages
  8459. static_cast<xpath_query_impl*>(ptr)->alloc.release();
  8460. // free allocator memory (with the first page)
  8461. xml_memory::deallocate(ptr);
  8462. }
  8463. xpath_query_impl(): root(0), alloc(&block)
  8464. {
  8465. block.next = 0;
  8466. block.capacity = sizeof(block.data);
  8467. }
  8468. xpath_ast_node* root;
  8469. xpath_allocator alloc;
  8470. xpath_memory_block block;
  8471. };
  8472. PUGI__FN xpath_string evaluate_string_impl(xpath_query_impl* impl, const xpath_node& n, xpath_stack_data& sd)
  8473. {
  8474. if (!impl) return xpath_string();
  8475. #ifdef PUGIXML_NO_EXCEPTIONS
  8476. if (setjmp(sd.error_handler)) return xpath_string();
  8477. #endif
  8478. xpath_context c(n, 1, 1);
  8479. return impl->root->eval_string(c, sd.stack);
  8480. }
  8481. PUGI__FN impl::xpath_ast_node* evaluate_node_set_prepare(xpath_query_impl* impl)
  8482. {
  8483. if (!impl) return 0;
  8484. if (impl->root->rettype() != xpath_type_node_set)
  8485. {
  8486. #ifdef PUGIXML_NO_EXCEPTIONS
  8487. return 0;
  8488. #else
  8489. xpath_parse_result res;
  8490. res.error = "Expression does not evaluate to node set";
  8491. throw xpath_exception(res);
  8492. #endif
  8493. }
  8494. return impl->root;
  8495. }
  8496. PUGI__NS_END
  8497. namespace pugi
  8498. {
  8499. #ifndef PUGIXML_NO_EXCEPTIONS
  8500. PUGI__FN xpath_exception::xpath_exception(const xpath_parse_result& result_): _result(result_)
  8501. {
  8502. assert(_result.error);
  8503. }
  8504. PUGI__FN const char* xpath_exception::what() const throw()
  8505. {
  8506. return _result.error;
  8507. }
  8508. PUGI__FN const xpath_parse_result& xpath_exception::result() const
  8509. {
  8510. return _result;
  8511. }
  8512. #endif
  8513. PUGI__FN xpath_node::xpath_node()
  8514. {
  8515. }
  8516. // Modified by YaoWT for Urho3D
  8517. PUGI__FN xpath_node::xpath_node(const xpath_node& rhs): _node(rhs._node), _attribute(rhs._attribute)
  8518. {
  8519. }
  8520. PUGI__FN xpath_node::xpath_node(const xml_node& node_): _node(node_)
  8521. {
  8522. }
  8523. PUGI__FN xpath_node::xpath_node(const xml_attribute& attribute_, const xml_node& parent_): _node(attribute_ ? parent_ : xml_node()), _attribute(attribute_)
  8524. {
  8525. }
  8526. PUGI__FN xml_node xpath_node::node() const
  8527. {
  8528. return _attribute ? xml_node() : _node;
  8529. }
  8530. PUGI__FN xml_attribute xpath_node::attribute() const
  8531. {
  8532. return _attribute;
  8533. }
  8534. PUGI__FN xml_node xpath_node::parent() const
  8535. {
  8536. return _attribute ? _node : _node.parent();
  8537. }
  8538. PUGI__FN static void unspecified_bool_xpath_node(xpath_node***)
  8539. {
  8540. }
  8541. PUGI__FN xpath_node::operator xpath_node::unspecified_bool_type() const
  8542. {
  8543. return (_node || _attribute) ? unspecified_bool_xpath_node : 0;
  8544. }
  8545. PUGI__FN bool xpath_node::operator!() const
  8546. {
  8547. return !(_node || _attribute);
  8548. }
  8549. PUGI__FN bool xpath_node::operator==(const xpath_node& n) const
  8550. {
  8551. return _node == n._node && _attribute == n._attribute;
  8552. }
  8553. PUGI__FN bool xpath_node::operator!=(const xpath_node& n) const
  8554. {
  8555. return _node != n._node || _attribute != n._attribute;
  8556. }
  8557. #ifdef __BORLANDC__
  8558. PUGI__FN bool operator&&(const xpath_node& lhs, bool rhs)
  8559. {
  8560. return (bool)lhs && rhs;
  8561. }
  8562. PUGI__FN bool operator||(const xpath_node& lhs, bool rhs)
  8563. {
  8564. return (bool)lhs || rhs;
  8565. }
  8566. #endif
  8567. PUGI__FN void xpath_node_set::_assign(const_iterator begin_, const_iterator end_)
  8568. {
  8569. assert(begin_ <= end_);
  8570. size_t size_ = static_cast<size_t>(end_ - begin_);
  8571. if (size_ <= 1)
  8572. {
  8573. // deallocate old buffer
  8574. if (_begin != &_storage) impl::xml_memory::deallocate(_begin);
  8575. // use internal buffer
  8576. if (begin_ != end_) _storage = *begin_;
  8577. _begin = &_storage;
  8578. _end = &_storage + size_;
  8579. }
  8580. else
  8581. {
  8582. // make heap copy
  8583. xpath_node* storage = static_cast<xpath_node*>(impl::xml_memory::allocate(size_ * sizeof(xpath_node)));
  8584. if (!storage)
  8585. {
  8586. #ifdef PUGIXML_NO_EXCEPTIONS
  8587. return;
  8588. #else
  8589. throw std::bad_alloc();
  8590. #endif
  8591. }
  8592. memcpy(storage, begin_, size_ * sizeof(xpath_node));
  8593. // deallocate old buffer
  8594. if (_begin != &_storage) impl::xml_memory::deallocate(_begin);
  8595. // finalize
  8596. _begin = storage;
  8597. _end = storage + size_;
  8598. }
  8599. }
  8600. PUGI__FN xpath_node_set::xpath_node_set(): _type(type_unsorted), _begin(&_storage), _end(&_storage)
  8601. {
  8602. }
  8603. PUGI__FN xpath_node_set::xpath_node_set(const_iterator begin_, const_iterator end_, type_t type_): _type(type_), _begin(&_storage), _end(&_storage)
  8604. {
  8605. _assign(begin_, end_);
  8606. }
  8607. PUGI__FN xpath_node_set::~xpath_node_set()
  8608. {
  8609. if (_begin != &_storage) impl::xml_memory::deallocate(_begin);
  8610. }
  8611. PUGI__FN xpath_node_set::xpath_node_set(const xpath_node_set& ns): _type(ns._type), _begin(&_storage), _end(&_storage)
  8612. {
  8613. _assign(ns._begin, ns._end);
  8614. }
  8615. PUGI__FN xpath_node_set& xpath_node_set::operator=(const xpath_node_set& ns)
  8616. {
  8617. if (this == &ns) return *this;
  8618. _type = ns._type;
  8619. _assign(ns._begin, ns._end);
  8620. return *this;
  8621. }
  8622. PUGI__FN xpath_node_set::type_t xpath_node_set::type() const
  8623. {
  8624. return _type;
  8625. }
  8626. PUGI__FN size_t xpath_node_set::size() const
  8627. {
  8628. return _end - _begin;
  8629. }
  8630. PUGI__FN bool xpath_node_set::empty() const
  8631. {
  8632. return _begin == _end;
  8633. }
  8634. PUGI__FN const xpath_node& xpath_node_set::operator[](size_t index) const
  8635. {
  8636. assert(index < size());
  8637. return _begin[index];
  8638. }
  8639. PUGI__FN xpath_node_set::const_iterator xpath_node_set::begin() const
  8640. {
  8641. return _begin;
  8642. }
  8643. PUGI__FN xpath_node_set::const_iterator xpath_node_set::end() const
  8644. {
  8645. return _end;
  8646. }
  8647. PUGI__FN void xpath_node_set::sort(bool reverse)
  8648. {
  8649. _type = impl::xpath_sort(_begin, _end, _type, reverse);
  8650. }
  8651. PUGI__FN xpath_node xpath_node_set::first() const
  8652. {
  8653. return impl::xpath_first(_begin, _end, _type);
  8654. }
  8655. PUGI__FN xpath_parse_result::xpath_parse_result(): error("Internal error"), offset(0)
  8656. {
  8657. }
  8658. PUGI__FN xpath_parse_result::operator bool() const
  8659. {
  8660. return error == 0;
  8661. }
  8662. PUGI__FN const char* xpath_parse_result::description() const
  8663. {
  8664. return error ? error : "No error";
  8665. }
  8666. PUGI__FN xpath_variable::xpath_variable(): _type(xpath_type_none), _next(0)
  8667. {
  8668. }
  8669. PUGI__FN const char_t* xpath_variable::name() const
  8670. {
  8671. switch (_type)
  8672. {
  8673. case xpath_type_node_set:
  8674. return static_cast<const impl::xpath_variable_node_set*>(this)->name;
  8675. case xpath_type_number:
  8676. return static_cast<const impl::xpath_variable_number*>(this)->name;
  8677. case xpath_type_string:
  8678. return static_cast<const impl::xpath_variable_string*>(this)->name;
  8679. case xpath_type_boolean:
  8680. return static_cast<const impl::xpath_variable_boolean*>(this)->name;
  8681. default:
  8682. assert(!"Invalid variable type");
  8683. return 0;
  8684. }
  8685. }
  8686. PUGI__FN xpath_value_type xpath_variable::type() const
  8687. {
  8688. return _type;
  8689. }
  8690. PUGI__FN bool xpath_variable::get_boolean() const
  8691. {
  8692. return (_type == xpath_type_boolean) ? static_cast<const impl::xpath_variable_boolean*>(this)->value : false;
  8693. }
  8694. PUGI__FN double xpath_variable::get_number() const
  8695. {
  8696. return (_type == xpath_type_number) ? static_cast<const impl::xpath_variable_number*>(this)->value : impl::gen_nan();
  8697. }
  8698. PUGI__FN const char_t* xpath_variable::get_string() const
  8699. {
  8700. const char_t* value = (_type == xpath_type_string) ? static_cast<const impl::xpath_variable_string*>(this)->value : 0;
  8701. return value ? value : PUGIXML_TEXT("");
  8702. }
  8703. PUGI__FN const xpath_node_set& xpath_variable::get_node_set() const
  8704. {
  8705. return (_type == xpath_type_node_set) ? static_cast<const impl::xpath_variable_node_set*>(this)->value : impl::dummy_node_set;
  8706. }
  8707. PUGI__FN bool xpath_variable::set(bool value)
  8708. {
  8709. if (_type != xpath_type_boolean) return false;
  8710. static_cast<impl::xpath_variable_boolean*>(this)->value = value;
  8711. return true;
  8712. }
  8713. PUGI__FN bool xpath_variable::set(double value)
  8714. {
  8715. if (_type != xpath_type_number) return false;
  8716. static_cast<impl::xpath_variable_number*>(this)->value = value;
  8717. return true;
  8718. }
  8719. PUGI__FN bool xpath_variable::set(const char_t* value)
  8720. {
  8721. if (_type != xpath_type_string) return false;
  8722. impl::xpath_variable_string* var = static_cast<impl::xpath_variable_string*>(this);
  8723. // duplicate string
  8724. size_t size = (impl::strlength(value) + 1) * sizeof(char_t);
  8725. char_t* copy = static_cast<char_t*>(impl::xml_memory::allocate(size));
  8726. if (!copy) return false;
  8727. memcpy(copy, value, size);
  8728. // replace old string
  8729. if (var->value) impl::xml_memory::deallocate(var->value);
  8730. var->value = copy;
  8731. return true;
  8732. }
  8733. PUGI__FN bool xpath_variable::set(const xpath_node_set& value)
  8734. {
  8735. if (_type != xpath_type_node_set) return false;
  8736. static_cast<impl::xpath_variable_node_set*>(this)->value = value;
  8737. return true;
  8738. }
  8739. PUGI__FN xpath_variable_set::xpath_variable_set()
  8740. {
  8741. for (size_t i = 0; i < sizeof(_data) / sizeof(_data[0]); ++i) _data[i] = 0;
  8742. }
  8743. PUGI__FN xpath_variable_set::~xpath_variable_set()
  8744. {
  8745. for (size_t i = 0; i < sizeof(_data) / sizeof(_data[0]); ++i)
  8746. {
  8747. xpath_variable* var = _data[i];
  8748. while (var)
  8749. {
  8750. xpath_variable* next = var->_next;
  8751. impl::delete_xpath_variable(var->_type, var);
  8752. var = next;
  8753. }
  8754. }
  8755. }
  8756. PUGI__FN xpath_variable* xpath_variable_set::find(const char_t* name) const
  8757. {
  8758. const size_t hash_size = sizeof(_data) / sizeof(_data[0]);
  8759. size_t hash = impl::hash_string(name) % hash_size;
  8760. // look for existing variable
  8761. for (xpath_variable* var = _data[hash]; var; var = var->_next)
  8762. if (impl::strequal(var->name(), name))
  8763. return var;
  8764. return 0;
  8765. }
  8766. PUGI__FN xpath_variable* xpath_variable_set::add(const char_t* name, xpath_value_type type)
  8767. {
  8768. const size_t hash_size = sizeof(_data) / sizeof(_data[0]);
  8769. size_t hash = impl::hash_string(name) % hash_size;
  8770. // look for existing variable
  8771. for (xpath_variable* var = _data[hash]; var; var = var->_next)
  8772. if (impl::strequal(var->name(), name))
  8773. return var->type() == type ? var : 0;
  8774. // add new variable
  8775. xpath_variable* result = impl::new_xpath_variable(type, name);
  8776. if (result)
  8777. {
  8778. result->_type = type;
  8779. result->_next = _data[hash];
  8780. _data[hash] = result;
  8781. }
  8782. return result;
  8783. }
  8784. PUGI__FN bool xpath_variable_set::set(const char_t* name, bool value)
  8785. {
  8786. xpath_variable* var = add(name, xpath_type_boolean);
  8787. return var ? var->set(value) : false;
  8788. }
  8789. PUGI__FN bool xpath_variable_set::set(const char_t* name, double value)
  8790. {
  8791. xpath_variable* var = add(name, xpath_type_number);
  8792. return var ? var->set(value) : false;
  8793. }
  8794. PUGI__FN bool xpath_variable_set::set(const char_t* name, const char_t* value)
  8795. {
  8796. xpath_variable* var = add(name, xpath_type_string);
  8797. return var ? var->set(value) : false;
  8798. }
  8799. PUGI__FN bool xpath_variable_set::set(const char_t* name, const xpath_node_set& value)
  8800. {
  8801. xpath_variable* var = add(name, xpath_type_node_set);
  8802. return var ? var->set(value) : false;
  8803. }
  8804. PUGI__FN xpath_variable* xpath_variable_set::get(const char_t* name)
  8805. {
  8806. return find(name);
  8807. }
  8808. PUGI__FN const xpath_variable* xpath_variable_set::get(const char_t* name) const
  8809. {
  8810. return find(name);
  8811. }
  8812. PUGI__FN xpath_query::xpath_query(const char_t* query, xpath_variable_set* variables): _impl(0)
  8813. {
  8814. impl::xpath_query_impl* qimpl = impl::xpath_query_impl::create();
  8815. if (!qimpl)
  8816. {
  8817. #ifdef PUGIXML_NO_EXCEPTIONS
  8818. _result.error = "Out of memory";
  8819. #else
  8820. throw std::bad_alloc();
  8821. #endif
  8822. }
  8823. else
  8824. {
  8825. impl::buffer_holder impl_holder(qimpl, impl::xpath_query_impl::destroy);
  8826. qimpl->root = impl::xpath_parser::parse(query, variables, &qimpl->alloc, &_result);
  8827. if (qimpl->root)
  8828. {
  8829. qimpl->root->optimize(&qimpl->alloc);
  8830. _impl = static_cast<impl::xpath_query_impl*>(impl_holder.release());
  8831. _result.error = 0;
  8832. }
  8833. }
  8834. }
  8835. PUGI__FN xpath_query::~xpath_query()
  8836. {
  8837. impl::xpath_query_impl::destroy(_impl);
  8838. }
  8839. PUGI__FN xpath_value_type xpath_query::return_type() const
  8840. {
  8841. if (!_impl) return xpath_type_none;
  8842. return static_cast<impl::xpath_query_impl*>(_impl)->root->rettype();
  8843. }
  8844. PUGI__FN bool xpath_query::evaluate_boolean(const xpath_node& n) const
  8845. {
  8846. if (!_impl) return false;
  8847. impl::xpath_context c(n, 1, 1);
  8848. impl::xpath_stack_data sd;
  8849. #ifdef PUGIXML_NO_EXCEPTIONS
  8850. if (setjmp(sd.error_handler)) return false;
  8851. #endif
  8852. return static_cast<impl::xpath_query_impl*>(_impl)->root->eval_boolean(c, sd.stack);
  8853. }
  8854. PUGI__FN double xpath_query::evaluate_number(const xpath_node& n) const
  8855. {
  8856. if (!_impl) return impl::gen_nan();
  8857. impl::xpath_context c(n, 1, 1);
  8858. impl::xpath_stack_data sd;
  8859. #ifdef PUGIXML_NO_EXCEPTIONS
  8860. if (setjmp(sd.error_handler)) return impl::gen_nan();
  8861. #endif
  8862. return static_cast<impl::xpath_query_impl*>(_impl)->root->eval_number(c, sd.stack);
  8863. }
  8864. #ifndef PUGIXML_NO_STL
  8865. PUGI__FN string_t xpath_query::evaluate_string(const xpath_node& n) const
  8866. {
  8867. impl::xpath_stack_data sd;
  8868. impl::xpath_string r = impl::evaluate_string_impl(static_cast<impl::xpath_query_impl*>(_impl), n, sd);
  8869. return string_t(r.c_str(), r.length());
  8870. }
  8871. #endif
  8872. PUGI__FN size_t xpath_query::evaluate_string(char_t* buffer, size_t capacity, const xpath_node& n) const
  8873. {
  8874. impl::xpath_stack_data sd;
  8875. impl::xpath_string r = impl::evaluate_string_impl(static_cast<impl::xpath_query_impl*>(_impl), n, sd);
  8876. size_t full_size = r.length() + 1;
  8877. if (capacity > 0)
  8878. {
  8879. size_t size = (full_size < capacity) ? full_size : capacity;
  8880. assert(size > 0);
  8881. memcpy(buffer, r.c_str(), (size - 1) * sizeof(char_t));
  8882. buffer[size - 1] = 0;
  8883. }
  8884. return full_size;
  8885. }
  8886. PUGI__FN xpath_node_set xpath_query::evaluate_node_set(const xpath_node& n) const
  8887. {
  8888. impl::xpath_ast_node* root = impl::evaluate_node_set_prepare(static_cast<impl::xpath_query_impl*>(_impl));
  8889. if (!root) return xpath_node_set();
  8890. impl::xpath_context c(n, 1, 1);
  8891. impl::xpath_stack_data sd;
  8892. #ifdef PUGIXML_NO_EXCEPTIONS
  8893. if (setjmp(sd.error_handler)) return xpath_node_set();
  8894. #endif
  8895. impl::xpath_node_set_raw r = root->eval_node_set(c, sd.stack, impl::nodeset_eval_all);
  8896. return xpath_node_set(r.begin(), r.end(), r.type());
  8897. }
  8898. PUGI__FN xpath_node xpath_query::evaluate_node(const xpath_node& n) const
  8899. {
  8900. impl::xpath_ast_node* root = impl::evaluate_node_set_prepare(static_cast<impl::xpath_query_impl*>(_impl));
  8901. if (!root) return xpath_node();
  8902. impl::xpath_context c(n, 1, 1);
  8903. impl::xpath_stack_data sd;
  8904. #ifdef PUGIXML_NO_EXCEPTIONS
  8905. if (setjmp(sd.error_handler)) return xpath_node();
  8906. #endif
  8907. impl::xpath_node_set_raw r = root->eval_node_set(c, sd.stack, impl::nodeset_eval_first);
  8908. return r.first();
  8909. }
  8910. PUGI__FN const xpath_parse_result& xpath_query::result() const
  8911. {
  8912. return _result;
  8913. }
  8914. PUGI__FN static void unspecified_bool_xpath_query(xpath_query***)
  8915. {
  8916. }
  8917. PUGI__FN xpath_query::operator xpath_query::unspecified_bool_type() const
  8918. {
  8919. return _impl ? unspecified_bool_xpath_query : 0;
  8920. }
  8921. PUGI__FN bool xpath_query::operator!() const
  8922. {
  8923. return !_impl;
  8924. }
  8925. PUGI__FN xpath_node xml_node::select_node(const char_t* query, xpath_variable_set* variables) const
  8926. {
  8927. xpath_query q(query, variables);
  8928. return select_node(q);
  8929. }
  8930. PUGI__FN xpath_node xml_node::select_node(const xpath_query& query) const
  8931. {
  8932. return query.evaluate_node(*this);
  8933. }
  8934. PUGI__FN xpath_node_set xml_node::select_nodes(const char_t* query, xpath_variable_set* variables) const
  8935. {
  8936. xpath_query q(query, variables);
  8937. return select_nodes(q);
  8938. }
  8939. PUGI__FN xpath_node_set xml_node::select_nodes(const xpath_query& query) const
  8940. {
  8941. return query.evaluate_node_set(*this);
  8942. }
  8943. PUGI__FN xpath_node xml_node::select_single_node(const char_t* query, xpath_variable_set* variables) const
  8944. {
  8945. xpath_query q(query, variables);
  8946. return select_single_node(q);
  8947. }
  8948. PUGI__FN xpath_node xml_node::select_single_node(const xpath_query& query) const
  8949. {
  8950. return query.evaluate_node(*this);
  8951. }
  8952. }
  8953. #endif
  8954. #ifdef __BORLANDC__
  8955. # pragma option pop
  8956. #endif
  8957. // Intel C++ does not properly keep warning state for function templates,
  8958. // so popping warning state at the end of translation unit leads to warnings in the middle.
  8959. #if defined(_MSC_VER) && !defined(__INTEL_COMPILER)
  8960. # pragma warning(pop)
  8961. #endif
  8962. // Undefine all local macros (makes sure we're not leaking macros in header-only mode)
  8963. #undef PUGI__NO_INLINE
  8964. #undef PUGI__UNLIKELY
  8965. #undef PUGI__STATIC_ASSERT
  8966. #undef PUGI__DMC_VOLATILE
  8967. #undef PUGI__MSVC_CRT_VERSION
  8968. #undef PUGI__NS_BEGIN
  8969. #undef PUGI__NS_END
  8970. #undef PUGI__FN
  8971. #undef PUGI__FN_NO_INLINE
  8972. #undef PUGI__NODETYPE
  8973. #undef PUGI__IS_CHARTYPE_IMPL
  8974. #undef PUGI__IS_CHARTYPE
  8975. #undef PUGI__IS_CHARTYPEX
  8976. #undef PUGI__ENDSWITH
  8977. #undef PUGI__SKIPWS
  8978. #undef PUGI__OPTSET
  8979. #undef PUGI__PUSHNODE
  8980. #undef PUGI__POPNODE
  8981. #undef PUGI__SCANFOR
  8982. #undef PUGI__SCANWHILE
  8983. #undef PUGI__SCANWHILE_UNROLL
  8984. #undef PUGI__ENDSEG
  8985. #undef PUGI__THROW_ERROR
  8986. #undef PUGI__CHECK_ERROR
  8987. #endif
  8988. /**
  8989. * Copyright (c) 2006-2014 Arseny Kapoulkine
  8990. *
  8991. * Permission is hereby granted, free of charge, to any person
  8992. * obtaining a copy of this software and associated documentation
  8993. * files (the "Software"), to deal in the Software without
  8994. * restriction, including without limitation the rights to use,
  8995. * copy, modify, merge, publish, distribute, sublicense, and/or sell
  8996. * copies of the Software, and to permit persons to whom the
  8997. * Software is furnished to do so, subject to the following
  8998. * conditions:
  8999. *
  9000. * The above copyright notice and this permission notice shall be
  9001. * included in all copies or substantial portions of the Software.
  9002. *
  9003. * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
  9004. * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
  9005. * OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
  9006. * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
  9007. * HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
  9008. * WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
  9009. * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
  9010. * OTHER DEALINGS IN THE SOFTWARE.
  9011. */