ustring.cpp 120 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420
  1. /**************************************************************************/
  2. /* ustring.cpp */
  3. /**************************************************************************/
  4. /* This file is part of: */
  5. /* GODOT ENGINE */
  6. /* https://godotengine.org */
  7. /**************************************************************************/
  8. /* Copyright (c) 2014-present Godot Engine contributors (see AUTHORS.md). */
  9. /* Copyright (c) 2007-2014 Juan Linietsky, Ariel Manzur. */
  10. /* */
  11. /* Permission is hereby granted, free of charge, to any person obtaining */
  12. /* a copy of this software and associated documentation files (the */
  13. /* "Software"), to deal in the Software without restriction, including */
  14. /* without limitation the rights to use, copy, modify, merge, publish, */
  15. /* distribute, sublicense, and/or sell copies of the Software, and to */
  16. /* permit persons to whom the Software is furnished to do so, subject to */
  17. /* the following conditions: */
  18. /* */
  19. /* The above copyright notice and this permission notice shall be */
  20. /* included in all copies or substantial portions of the Software. */
  21. /* */
  22. /* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, */
  23. /* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF */
  24. /* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. */
  25. /* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY */
  26. /* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, */
  27. /* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE */
  28. /* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */
  29. /**************************************************************************/
  30. #include "ustring.h"
  31. #include "core/crypto/crypto_core.h"
  32. #include "core/math/color.h"
  33. #include "core/math/math_funcs.h"
  34. #include "core/os/memory.h"
  35. #include "core/string/print_string.h"
  36. #include "core/string/string_name.h"
  37. #include "core/string/translation.h"
  38. #include "core/string/ucaps.h"
  39. #include "core/variant/variant.h"
  40. #include "core/version_generated.gen.h"
  41. #include <stdio.h>
  42. #include <stdlib.h>
  43. #include <cstdint>
  44. #ifdef _MSC_VER
  45. #define _CRT_SECURE_NO_WARNINGS // to disable build-time warning which suggested to use strcpy_s instead strcpy
  46. #endif
  47. #if defined(MINGW_ENABLED) || defined(_MSC_VER)
  48. #define snprintf _snprintf_s
  49. #endif
  50. static const int MAX_DECIMALS = 32;
  51. static _FORCE_INLINE_ char32_t lower_case(char32_t c) {
  52. return (is_ascii_upper_case(c) ? (c + ('a' - 'A')) : c);
  53. }
  54. const char CharString::_null = 0;
  55. const char16_t Char16String::_null = 0;
  56. const char32_t String::_null = 0;
  57. const char32_t String::_replacement_char = 0xfffd;
  58. bool select_word(const String &p_s, int p_col, int &r_beg, int &r_end) {
  59. const String &s = p_s;
  60. int beg = CLAMP(p_col, 0, s.length());
  61. int end = beg;
  62. if (s[beg] > 32 || beg == s.length()) {
  63. bool symbol = beg < s.length() && is_symbol(s[beg]);
  64. while (beg > 0 && s[beg - 1] > 32 && (symbol == is_symbol(s[beg - 1]))) {
  65. beg--;
  66. }
  67. while (end < s.length() && s[end + 1] > 32 && (symbol == is_symbol(s[end + 1]))) {
  68. end++;
  69. }
  70. if (end < s.length()) {
  71. end += 1;
  72. }
  73. r_beg = beg;
  74. r_end = end;
  75. return true;
  76. } else {
  77. return false;
  78. }
  79. }
  80. /*************************************************************************/
  81. /* Char16String */
  82. /*************************************************************************/
  83. bool Char16String::operator<(const Char16String &p_right) const {
  84. if (length() == 0) {
  85. return p_right.length() != 0;
  86. }
  87. return is_str_less(get_data(), p_right.get_data());
  88. }
  89. Char16String &Char16String::operator+=(char16_t p_char) {
  90. const int lhs_len = length();
  91. resize(lhs_len + 2);
  92. char16_t *dst = ptrw();
  93. dst[lhs_len] = p_char;
  94. dst[lhs_len + 1] = 0;
  95. return *this;
  96. }
  97. void Char16String::operator=(const char16_t *p_cstr) {
  98. copy_from(p_cstr);
  99. }
  100. const char16_t *Char16String::get_data() const {
  101. if (size()) {
  102. return &operator[](0);
  103. } else {
  104. return u"";
  105. }
  106. }
  107. void Char16String::copy_from(const char16_t *p_cstr) {
  108. if (!p_cstr) {
  109. resize(0);
  110. return;
  111. }
  112. const char16_t *s = p_cstr;
  113. for (; *s; s++) {
  114. }
  115. size_t len = s - p_cstr;
  116. if (len == 0) {
  117. resize(0);
  118. return;
  119. }
  120. Error err = resize(++len); // include terminating null char
  121. ERR_FAIL_COND_MSG(err != OK, "Failed to copy char16_t string.");
  122. memcpy(ptrw(), p_cstr, len * sizeof(char16_t));
  123. }
  124. /*************************************************************************/
  125. /* CharString */
  126. /*************************************************************************/
  127. bool CharString::operator<(const CharString &p_right) const {
  128. if (length() == 0) {
  129. return p_right.length() != 0;
  130. }
  131. return is_str_less(get_data(), p_right.get_data());
  132. }
  133. bool CharString::operator==(const CharString &p_right) const {
  134. if (length() == 0) {
  135. // True if both have length 0, false if only p_right has a length
  136. return p_right.length() == 0;
  137. } else if (p_right.length() == 0) {
  138. // False due to unequal length
  139. return false;
  140. }
  141. return strcmp(ptr(), p_right.ptr()) == 0;
  142. }
  143. CharString &CharString::operator+=(char p_char) {
  144. const int lhs_len = length();
  145. resize(lhs_len + 2);
  146. char *dst = ptrw();
  147. dst[lhs_len] = p_char;
  148. dst[lhs_len + 1] = 0;
  149. return *this;
  150. }
  151. void CharString::operator=(const char *p_cstr) {
  152. copy_from(p_cstr);
  153. }
  154. const char *CharString::get_data() const {
  155. if (size()) {
  156. return &operator[](0);
  157. } else {
  158. return "";
  159. }
  160. }
  161. void CharString::copy_from(const char *p_cstr) {
  162. if (!p_cstr) {
  163. resize(0);
  164. return;
  165. }
  166. size_t len = strlen(p_cstr);
  167. if (len == 0) {
  168. resize(0);
  169. return;
  170. }
  171. Error err = resize(++len); // include terminating null char
  172. ERR_FAIL_COND_MSG(err != OK, "Failed to copy C-string.");
  173. memcpy(ptrw(), p_cstr, len);
  174. }
  175. /*************************************************************************/
  176. /* String */
  177. /*************************************************************************/
  178. Error String::parse_url(String &r_scheme, String &r_host, int &r_port, String &r_path) const {
  179. // Splits the URL into scheme, host, port, path. Strip credentials when present.
  180. String base = *this;
  181. r_scheme = "";
  182. r_host = "";
  183. r_port = 0;
  184. r_path = "";
  185. int pos = base.find("://");
  186. // Scheme
  187. if (pos != -1) {
  188. r_scheme = base.substr(0, pos + 3).to_lower();
  189. base = base.substr(pos + 3, base.length() - pos - 3);
  190. }
  191. pos = base.find("/");
  192. // Path
  193. if (pos != -1) {
  194. r_path = base.substr(pos, base.length() - pos);
  195. base = base.substr(0, pos);
  196. }
  197. // Host
  198. pos = base.find("@");
  199. if (pos != -1) {
  200. // Strip credentials
  201. base = base.substr(pos + 1, base.length() - pos - 1);
  202. }
  203. if (base.begins_with("[")) {
  204. // Literal IPv6
  205. pos = base.rfind("]");
  206. if (pos == -1) {
  207. return ERR_INVALID_PARAMETER;
  208. }
  209. r_host = base.substr(1, pos - 1);
  210. base = base.substr(pos + 1, base.length() - pos - 1);
  211. } else {
  212. // Anything else
  213. if (base.get_slice_count(":") > 2) {
  214. return ERR_INVALID_PARAMETER;
  215. }
  216. pos = base.rfind(":");
  217. if (pos == -1) {
  218. r_host = base;
  219. base = "";
  220. } else {
  221. r_host = base.substr(0, pos);
  222. base = base.substr(pos, base.length() - pos);
  223. }
  224. }
  225. if (r_host.is_empty()) {
  226. return ERR_INVALID_PARAMETER;
  227. }
  228. r_host = r_host.to_lower();
  229. // Port
  230. if (base.begins_with(":")) {
  231. base = base.substr(1, base.length() - 1);
  232. if (!base.is_valid_int()) {
  233. return ERR_INVALID_PARAMETER;
  234. }
  235. r_port = base.to_int();
  236. if (r_port < 1 || r_port > 65535) {
  237. return ERR_INVALID_PARAMETER;
  238. }
  239. }
  240. return OK;
  241. }
  242. void String::copy_from(const char *p_cstr) {
  243. // copy Latin-1 encoded c-string directly
  244. if (!p_cstr) {
  245. resize(0);
  246. return;
  247. }
  248. const size_t len = strlen(p_cstr);
  249. if (len == 0) {
  250. resize(0);
  251. return;
  252. }
  253. resize(len + 1); // include 0
  254. char32_t *dst = this->ptrw();
  255. for (size_t i = 0; i <= len; i++) {
  256. #if CHAR_MIN == 0
  257. uint8_t c = p_cstr[i];
  258. #else
  259. uint8_t c = p_cstr[i] >= 0 ? p_cstr[i] : uint8_t(256 + p_cstr[i]);
  260. #endif
  261. if (c == 0 && i < len) {
  262. print_unicode_error("NUL character", true);
  263. dst[i] = _replacement_char;
  264. } else {
  265. dst[i] = c;
  266. }
  267. }
  268. }
  269. void String::copy_from(const char *p_cstr, const int p_clip_to) {
  270. // copy Latin-1 encoded c-string directly
  271. if (!p_cstr) {
  272. resize(0);
  273. return;
  274. }
  275. int len = 0;
  276. const char *ptr = p_cstr;
  277. while ((p_clip_to < 0 || len < p_clip_to) && *(ptr++) != 0) {
  278. len++;
  279. }
  280. if (len == 0) {
  281. resize(0);
  282. return;
  283. }
  284. resize(len + 1); // include 0
  285. char32_t *dst = this->ptrw();
  286. for (int i = 0; i < len; i++) {
  287. #if CHAR_MIN == 0
  288. uint8_t c = p_cstr[i];
  289. #else
  290. uint8_t c = p_cstr[i] >= 0 ? p_cstr[i] : uint8_t(256 + p_cstr[i]);
  291. #endif
  292. if (c == 0) {
  293. print_unicode_error("NUL character", true);
  294. dst[i] = _replacement_char;
  295. } else {
  296. dst[i] = c;
  297. }
  298. }
  299. dst[len] = 0;
  300. }
  301. void String::copy_from(const wchar_t *p_cstr) {
  302. #ifdef WINDOWS_ENABLED
  303. // wchar_t is 16-bit, parse as UTF-16
  304. parse_utf16((const char16_t *)p_cstr);
  305. #else
  306. // wchar_t is 32-bit, copy directly
  307. copy_from((const char32_t *)p_cstr);
  308. #endif
  309. }
  310. void String::copy_from(const wchar_t *p_cstr, const int p_clip_to) {
  311. #ifdef WINDOWS_ENABLED
  312. // wchar_t is 16-bit, parse as UTF-16
  313. parse_utf16((const char16_t *)p_cstr, p_clip_to);
  314. #else
  315. // wchar_t is 32-bit, copy directly
  316. copy_from((const char32_t *)p_cstr, p_clip_to);
  317. #endif
  318. }
  319. void String::copy_from(const char32_t &p_char) {
  320. if (p_char == 0) {
  321. print_unicode_error("NUL character", true);
  322. return;
  323. }
  324. resize(2);
  325. char32_t *dst = ptrw();
  326. if ((p_char & 0xfffff800) == 0xd800) {
  327. print_unicode_error(vformat("Unpaired surrogate (%x)", (uint32_t)p_char));
  328. dst[0] = _replacement_char;
  329. } else if (p_char > 0x10ffff) {
  330. print_unicode_error(vformat("Invalid unicode codepoint (%x)", (uint32_t)p_char));
  331. dst[0] = _replacement_char;
  332. } else {
  333. dst[0] = p_char;
  334. }
  335. dst[1] = 0;
  336. }
  337. void String::copy_from(const char32_t *p_cstr) {
  338. if (!p_cstr) {
  339. resize(0);
  340. return;
  341. }
  342. int len = 0;
  343. const char32_t *ptr = p_cstr;
  344. while (*(ptr++) != 0) {
  345. len++;
  346. }
  347. if (len == 0) {
  348. resize(0);
  349. return;
  350. }
  351. copy_from_unchecked(p_cstr, len);
  352. }
  353. void String::copy_from(const char32_t *p_cstr, const int p_clip_to) {
  354. if (!p_cstr) {
  355. resize(0);
  356. return;
  357. }
  358. int len = 0;
  359. const char32_t *ptr = p_cstr;
  360. while ((p_clip_to < 0 || len < p_clip_to) && *(ptr++) != 0) {
  361. len++;
  362. }
  363. if (len == 0) {
  364. resize(0);
  365. return;
  366. }
  367. copy_from_unchecked(p_cstr, len);
  368. }
  369. // assumes the following have already been validated:
  370. // p_char != nullptr
  371. // p_length > 0
  372. // p_length <= p_char strlen
  373. void String::copy_from_unchecked(const char32_t *p_char, const int p_length) {
  374. resize(p_length + 1);
  375. char32_t *dst = ptrw();
  376. dst[p_length] = 0;
  377. for (int i = 0; i < p_length; i++) {
  378. if (p_char[i] == 0) {
  379. print_unicode_error("NUL character", true);
  380. dst[i] = _replacement_char;
  381. continue;
  382. }
  383. if ((p_char[i] & 0xfffff800) == 0xd800) {
  384. print_unicode_error(vformat("Unpaired surrogate (%x)", (uint32_t)p_char[i]));
  385. dst[i] = _replacement_char;
  386. continue;
  387. }
  388. if (p_char[i] > 0x10ffff) {
  389. print_unicode_error(vformat("Invalid unicode codepoint (%x)", (uint32_t)p_char[i]));
  390. dst[i] = _replacement_char;
  391. continue;
  392. }
  393. dst[i] = p_char[i];
  394. }
  395. }
  396. void String::operator=(const char *p_str) {
  397. copy_from(p_str);
  398. }
  399. void String::operator=(const char32_t *p_str) {
  400. copy_from(p_str);
  401. }
  402. void String::operator=(const wchar_t *p_str) {
  403. copy_from(p_str);
  404. }
  405. String String::operator+(const String &p_str) const {
  406. String res = *this;
  407. res += p_str;
  408. return res;
  409. }
  410. String String::operator+(char32_t p_char) const {
  411. String res = *this;
  412. res += p_char;
  413. return res;
  414. }
  415. String operator+(const char *p_chr, const String &p_str) {
  416. String tmp = p_chr;
  417. tmp += p_str;
  418. return tmp;
  419. }
  420. String operator+(const wchar_t *p_chr, const String &p_str) {
  421. #ifdef WINDOWS_ENABLED
  422. // wchar_t is 16-bit
  423. String tmp = String::utf16((const char16_t *)p_chr);
  424. #else
  425. // wchar_t is 32-bit
  426. String tmp = (const char32_t *)p_chr;
  427. #endif
  428. tmp += p_str;
  429. return tmp;
  430. }
  431. String operator+(char32_t p_chr, const String &p_str) {
  432. return (String::chr(p_chr) + p_str);
  433. }
  434. String &String::operator+=(const String &p_str) {
  435. const int lhs_len = length();
  436. if (lhs_len == 0) {
  437. *this = p_str;
  438. return *this;
  439. }
  440. const int rhs_len = p_str.length();
  441. if (rhs_len == 0) {
  442. return *this;
  443. }
  444. resize(lhs_len + rhs_len + 1);
  445. const char32_t *src = p_str.ptr();
  446. char32_t *dst = ptrw() + lhs_len;
  447. // Don't copy the terminating null with `memcpy` to avoid undefined behavior when string is being added to itself (it would overlap the destination).
  448. memcpy(dst, src, rhs_len * sizeof(char32_t));
  449. *(dst + rhs_len) = _null;
  450. return *this;
  451. }
  452. String &String::operator+=(const char *p_str) {
  453. if (!p_str || p_str[0] == 0) {
  454. return *this;
  455. }
  456. const int lhs_len = length();
  457. const size_t rhs_len = strlen(p_str);
  458. resize(lhs_len + rhs_len + 1);
  459. char32_t *dst = ptrw() + lhs_len;
  460. for (size_t i = 0; i <= rhs_len; i++) {
  461. #if CHAR_MIN == 0
  462. uint8_t c = p_str[i];
  463. #else
  464. uint8_t c = p_str[i] >= 0 ? p_str[i] : uint8_t(256 + p_str[i]);
  465. #endif
  466. if (c == 0 && i < rhs_len) {
  467. print_unicode_error("NUL character", true);
  468. dst[i] = _replacement_char;
  469. } else {
  470. dst[i] = c;
  471. }
  472. }
  473. return *this;
  474. }
  475. String &String::operator+=(const wchar_t *p_str) {
  476. #ifdef WINDOWS_ENABLED
  477. // wchar_t is 16-bit
  478. *this += String::utf16((const char16_t *)p_str);
  479. #else
  480. // wchar_t is 32-bit
  481. *this += String((const char32_t *)p_str);
  482. #endif
  483. return *this;
  484. }
  485. String &String::operator+=(const char32_t *p_str) {
  486. *this += String(p_str);
  487. return *this;
  488. }
  489. String &String::operator+=(char32_t p_char) {
  490. if (p_char == 0) {
  491. print_unicode_error("NUL character", true);
  492. return *this;
  493. }
  494. const int lhs_len = length();
  495. resize(lhs_len + 2);
  496. char32_t *dst = ptrw();
  497. if ((p_char & 0xfffff800) == 0xd800) {
  498. print_unicode_error(vformat("Unpaired surrogate (%x)", (uint32_t)p_char));
  499. dst[lhs_len] = _replacement_char;
  500. } else if (p_char > 0x10ffff) {
  501. print_unicode_error(vformat("Invalid unicode codepoint (%x)", (uint32_t)p_char));
  502. dst[lhs_len] = _replacement_char;
  503. } else {
  504. dst[lhs_len] = p_char;
  505. }
  506. dst[lhs_len + 1] = 0;
  507. return *this;
  508. }
  509. bool String::operator==(const char *p_str) const {
  510. // compare Latin-1 encoded c-string
  511. int len = 0;
  512. const char *aux = p_str;
  513. while (*(aux++) != 0) {
  514. len++;
  515. }
  516. if (length() != len) {
  517. return false;
  518. }
  519. if (is_empty()) {
  520. return true;
  521. }
  522. int l = length();
  523. const char32_t *dst = get_data();
  524. // Compare char by char
  525. for (int i = 0; i < l; i++) {
  526. if ((char32_t)p_str[i] != dst[i]) {
  527. return false;
  528. }
  529. }
  530. return true;
  531. }
  532. bool String::operator==(const wchar_t *p_str) const {
  533. #ifdef WINDOWS_ENABLED
  534. // wchar_t is 16-bit, parse as UTF-16
  535. return *this == String::utf16((const char16_t *)p_str);
  536. #else
  537. // wchar_t is 32-bit, compare char by char
  538. return *this == (const char32_t *)p_str;
  539. #endif
  540. }
  541. bool String::operator==(const char32_t *p_str) const {
  542. int len = 0;
  543. const char32_t *aux = p_str;
  544. while (*(aux++) != 0) {
  545. len++;
  546. }
  547. if (length() != len) {
  548. return false;
  549. }
  550. if (is_empty()) {
  551. return true;
  552. }
  553. int l = length();
  554. const char32_t *dst = get_data();
  555. /* Compare char by char */
  556. for (int i = 0; i < l; i++) {
  557. if (p_str[i] != dst[i]) {
  558. return false;
  559. }
  560. }
  561. return true;
  562. }
  563. bool String::operator==(const String &p_str) const {
  564. if (length() != p_str.length()) {
  565. return false;
  566. }
  567. if (is_empty()) {
  568. return true;
  569. }
  570. int l = length();
  571. const char32_t *src = get_data();
  572. const char32_t *dst = p_str.get_data();
  573. /* Compare char by char */
  574. for (int i = 0; i < l; i++) {
  575. if (src[i] != dst[i]) {
  576. return false;
  577. }
  578. }
  579. return true;
  580. }
  581. bool String::operator==(const StrRange &p_str_range) const {
  582. int len = p_str_range.len;
  583. if (length() != len) {
  584. return false;
  585. }
  586. if (is_empty()) {
  587. return true;
  588. }
  589. const char32_t *c_str = p_str_range.c_str;
  590. const char32_t *dst = &operator[](0);
  591. /* Compare char by char */
  592. for (int i = 0; i < len; i++) {
  593. if (c_str[i] != dst[i]) {
  594. return false;
  595. }
  596. }
  597. return true;
  598. }
  599. bool operator==(const char *p_chr, const String &p_str) {
  600. return p_str == p_chr;
  601. }
  602. bool operator==(const wchar_t *p_chr, const String &p_str) {
  603. #ifdef WINDOWS_ENABLED
  604. // wchar_t is 16-bit
  605. return p_str == String::utf16((const char16_t *)p_chr);
  606. #else
  607. // wchar_t is 32-bi
  608. return p_str == String((const char32_t *)p_chr);
  609. #endif
  610. }
  611. bool operator!=(const char *p_chr, const String &p_str) {
  612. return !(p_str == p_chr);
  613. }
  614. bool operator!=(const wchar_t *p_chr, const String &p_str) {
  615. #ifdef WINDOWS_ENABLED
  616. // wchar_t is 16-bit
  617. return !(p_str == String::utf16((const char16_t *)p_chr));
  618. #else
  619. // wchar_t is 32-bi
  620. return !(p_str == String((const char32_t *)p_chr));
  621. #endif
  622. }
  623. bool String::operator!=(const char *p_str) const {
  624. return (!(*this == p_str));
  625. }
  626. bool String::operator!=(const wchar_t *p_str) const {
  627. return (!(*this == p_str));
  628. }
  629. bool String::operator!=(const char32_t *p_str) const {
  630. return (!(*this == p_str));
  631. }
  632. bool String::operator!=(const String &p_str) const {
  633. return !((*this == p_str));
  634. }
  635. bool String::operator<=(const String &p_str) const {
  636. return !(p_str < *this);
  637. }
  638. bool String::operator>(const String &p_str) const {
  639. return p_str < *this;
  640. }
  641. bool String::operator>=(const String &p_str) const {
  642. return !(*this < p_str);
  643. }
  644. bool String::operator<(const char *p_str) const {
  645. if (is_empty() && p_str[0] == 0) {
  646. return false;
  647. }
  648. if (is_empty()) {
  649. return true;
  650. }
  651. return is_str_less(get_data(), p_str);
  652. }
  653. bool String::operator<(const wchar_t *p_str) const {
  654. if (is_empty() && p_str[0] == 0) {
  655. return false;
  656. }
  657. if (is_empty()) {
  658. return true;
  659. }
  660. #ifdef WINDOWS_ENABLED
  661. // wchar_t is 16-bit
  662. return is_str_less(get_data(), String::utf16((const char16_t *)p_str).get_data());
  663. #else
  664. // wchar_t is 32-bit
  665. return is_str_less(get_data(), (const char32_t *)p_str);
  666. #endif
  667. }
  668. bool String::operator<(const char32_t *p_str) const {
  669. if (is_empty() && p_str[0] == 0) {
  670. return false;
  671. }
  672. if (is_empty()) {
  673. return true;
  674. }
  675. return is_str_less(get_data(), p_str);
  676. }
  677. bool String::operator<(const String &p_str) const {
  678. return operator<(p_str.get_data());
  679. }
  680. signed char String::nocasecmp_to(const String &p_str) const {
  681. if (is_empty() && p_str.is_empty()) {
  682. return 0;
  683. }
  684. if (is_empty()) {
  685. return -1;
  686. }
  687. if (p_str.is_empty()) {
  688. return 1;
  689. }
  690. const char32_t *that_str = p_str.get_data();
  691. const char32_t *this_str = get_data();
  692. while (true) {
  693. if (*that_str == 0 && *this_str == 0) { // If both strings are at the end, they are equal.
  694. return 0;
  695. } else if (*this_str == 0) { // If at the end of this, and not of other, we are less.
  696. return -1;
  697. } else if (*that_str == 0) { // If at end of other, and not of this, we are greater.
  698. return 1;
  699. } else if (_find_upper(*this_str) < _find_upper(*that_str)) { // If current character in this is less, we are less.
  700. return -1;
  701. } else if (_find_upper(*this_str) > _find_upper(*that_str)) { // If current character in this is greater, we are greater.
  702. return 1;
  703. }
  704. this_str++;
  705. that_str++;
  706. }
  707. }
  708. signed char String::casecmp_to(const String &p_str) const {
  709. if (is_empty() && p_str.is_empty()) {
  710. return 0;
  711. }
  712. if (is_empty()) {
  713. return -1;
  714. }
  715. if (p_str.is_empty()) {
  716. return 1;
  717. }
  718. const char32_t *that_str = p_str.get_data();
  719. const char32_t *this_str = get_data();
  720. while (true) {
  721. if (*that_str == 0 && *this_str == 0) { // If both strings are at the end, they are equal.
  722. return 0;
  723. } else if (*this_str == 0) { // If at the end of this, and not of other, we are less.
  724. return -1;
  725. } else if (*that_str == 0) { // If at end of other, and not of this, we are greater.
  726. return 1;
  727. } else if (*this_str < *that_str) { // If current character in this is less, we are less.
  728. return -1;
  729. } else if (*this_str > *that_str) { // If current character in this is greater, we are greater.
  730. return 1;
  731. }
  732. this_str++;
  733. that_str++;
  734. }
  735. }
  736. static _FORCE_INLINE_ signed char natural_cmp_common(const char32_t *&r_this_str, const char32_t *&r_that_str) {
  737. // Keep ptrs to start of numerical sequences.
  738. const char32_t *this_substr = r_this_str;
  739. const char32_t *that_substr = r_that_str;
  740. // Compare lengths of both numerical sequences, ignoring leading zeros.
  741. while (is_digit(*r_this_str)) {
  742. r_this_str++;
  743. }
  744. while (is_digit(*r_that_str)) {
  745. r_that_str++;
  746. }
  747. while (*this_substr == '0') {
  748. this_substr++;
  749. }
  750. while (*that_substr == '0') {
  751. that_substr++;
  752. }
  753. int this_len = r_this_str - this_substr;
  754. int that_len = r_that_str - that_substr;
  755. if (this_len < that_len) {
  756. return -1;
  757. } else if (this_len > that_len) {
  758. return 1;
  759. }
  760. // If lengths equal, compare lexicographically.
  761. while (this_substr != r_this_str && that_substr != r_that_str) {
  762. if (*this_substr < *that_substr) {
  763. return -1;
  764. } else if (*this_substr > *that_substr) {
  765. return 1;
  766. }
  767. this_substr++;
  768. that_substr++;
  769. }
  770. return 0;
  771. }
  772. signed char String::naturalcasecmp_to(const String &p_str) const {
  773. const char32_t *this_str = get_data();
  774. const char32_t *that_str = p_str.get_data();
  775. if (this_str && that_str) {
  776. while (*this_str == '.' || *that_str == '.') {
  777. if (*this_str++ != '.') {
  778. return 1;
  779. }
  780. if (*that_str++ != '.') {
  781. return -1;
  782. }
  783. if (!*that_str) {
  784. return 1;
  785. }
  786. if (!*this_str) {
  787. return -1;
  788. }
  789. }
  790. while (*this_str) {
  791. if (!*that_str) {
  792. return 1;
  793. } else if (is_digit(*this_str)) {
  794. if (!is_digit(*that_str)) {
  795. return -1;
  796. }
  797. signed char ret = natural_cmp_common(this_str, that_str);
  798. if (ret) {
  799. return ret;
  800. }
  801. } else if (is_digit(*that_str)) {
  802. return 1;
  803. } else {
  804. if (*this_str < *that_str) { // If current character in this is less, we are less.
  805. return -1;
  806. } else if (*this_str > *that_str) { // If current character in this is greater, we are greater.
  807. return 1;
  808. }
  809. this_str++;
  810. that_str++;
  811. }
  812. }
  813. if (*that_str) {
  814. return -1;
  815. }
  816. }
  817. return 0;
  818. }
  819. signed char String::naturalnocasecmp_to(const String &p_str) const {
  820. const char32_t *this_str = get_data();
  821. const char32_t *that_str = p_str.get_data();
  822. if (this_str && that_str) {
  823. while (*this_str == '.' || *that_str == '.') {
  824. if (*this_str++ != '.') {
  825. return 1;
  826. }
  827. if (*that_str++ != '.') {
  828. return -1;
  829. }
  830. if (!*that_str) {
  831. return 1;
  832. }
  833. if (!*this_str) {
  834. return -1;
  835. }
  836. }
  837. while (*this_str) {
  838. if (!*that_str) {
  839. return 1;
  840. } else if (is_digit(*this_str)) {
  841. if (!is_digit(*that_str)) {
  842. return -1;
  843. }
  844. signed char ret = natural_cmp_common(this_str, that_str);
  845. if (ret) {
  846. return ret;
  847. }
  848. } else if (is_digit(*that_str)) {
  849. return 1;
  850. } else {
  851. if (_find_upper(*this_str) < _find_upper(*that_str)) { // If current character in this is less, we are less.
  852. return -1;
  853. } else if (_find_upper(*this_str) > _find_upper(*that_str)) { // If current character in this is greater, we are greater.
  854. return 1;
  855. }
  856. this_str++;
  857. that_str++;
  858. }
  859. }
  860. if (*that_str) {
  861. return -1;
  862. }
  863. }
  864. return 0;
  865. }
  866. const char32_t *String::get_data() const {
  867. static const char32_t zero = 0;
  868. return size() ? &operator[](0) : &zero;
  869. }
  870. String String::_camelcase_to_underscore() const {
  871. const char32_t *cstr = get_data();
  872. String new_string;
  873. int start_index = 0;
  874. for (int i = 1; i < this->size(); i++) {
  875. bool is_prev_upper = is_ascii_upper_case(cstr[i - 1]);
  876. bool is_prev_lower = is_ascii_lower_case(cstr[i - 1]);
  877. bool is_prev_digit = is_digit(cstr[i - 1]);
  878. bool is_curr_upper = is_ascii_upper_case(cstr[i]);
  879. bool is_curr_lower = is_ascii_lower_case(cstr[i]);
  880. bool is_curr_digit = is_digit(cstr[i]);
  881. bool is_next_lower = false;
  882. if (i + 1 < this->size()) {
  883. is_next_lower = is_ascii_lower_case(cstr[i + 1]);
  884. }
  885. const bool cond_a = is_prev_lower && is_curr_upper; // aA
  886. const bool cond_b = (is_prev_upper || is_prev_digit) && is_curr_upper && is_next_lower; // AAa, 2Aa
  887. const bool cond_c = is_prev_digit && is_curr_lower && is_next_lower; // 2aa
  888. const bool cond_d = (is_prev_upper || is_prev_lower) && is_curr_digit; // A2, a2
  889. if (cond_a || cond_b || cond_c || cond_d) {
  890. new_string += this->substr(start_index, i - start_index) + "_";
  891. start_index = i;
  892. }
  893. }
  894. new_string += this->substr(start_index, this->size() - start_index);
  895. return new_string.to_lower();
  896. }
  897. String String::capitalize() const {
  898. String aux = this->_camelcase_to_underscore().replace("_", " ").strip_edges();
  899. String cap;
  900. for (int i = 0; i < aux.get_slice_count(" "); i++) {
  901. String slice = aux.get_slicec(' ', i);
  902. if (slice.length() > 0) {
  903. slice[0] = _find_upper(slice[0]);
  904. if (i > 0) {
  905. cap += " ";
  906. }
  907. cap += slice;
  908. }
  909. }
  910. return cap;
  911. }
  912. String String::to_camel_case() const {
  913. String s = this->to_pascal_case();
  914. if (!s.is_empty()) {
  915. s[0] = _find_lower(s[0]);
  916. }
  917. return s;
  918. }
  919. String String::to_pascal_case() const {
  920. return this->capitalize().replace(" ", "");
  921. }
  922. String String::to_snake_case() const {
  923. return this->_camelcase_to_underscore().replace(" ", "_").strip_edges();
  924. }
  925. String String::get_with_code_lines() const {
  926. const Vector<String> lines = split("\n");
  927. String ret;
  928. for (int i = 0; i < lines.size(); i++) {
  929. if (i > 0) {
  930. ret += "\n";
  931. }
  932. ret += vformat("%4d | %s", i + 1, lines[i]);
  933. }
  934. return ret;
  935. }
  936. int String::get_slice_count(String p_splitter) const {
  937. if (is_empty()) {
  938. return 0;
  939. }
  940. if (p_splitter.is_empty()) {
  941. return 0;
  942. }
  943. int pos = 0;
  944. int slices = 1;
  945. while ((pos = find(p_splitter, pos)) >= 0) {
  946. slices++;
  947. pos += p_splitter.length();
  948. }
  949. return slices;
  950. }
  951. String String::get_slice(String p_splitter, int p_slice) const {
  952. if (is_empty() || p_splitter.is_empty()) {
  953. return "";
  954. }
  955. int pos = 0;
  956. int prev_pos = 0;
  957. //int slices=1;
  958. if (p_slice < 0) {
  959. return "";
  960. }
  961. if (find(p_splitter) == -1) {
  962. return *this;
  963. }
  964. int i = 0;
  965. while (true) {
  966. pos = find(p_splitter, pos);
  967. if (pos == -1) {
  968. pos = length(); //reached end
  969. }
  970. int from = prev_pos;
  971. //int to=pos;
  972. if (p_slice == i) {
  973. return substr(from, pos - from);
  974. }
  975. if (pos == length()) { //reached end and no find
  976. break;
  977. }
  978. pos += p_splitter.length();
  979. prev_pos = pos;
  980. i++;
  981. }
  982. return ""; //no find!
  983. }
  984. String String::get_slicec(char32_t p_splitter, int p_slice) const {
  985. if (is_empty()) {
  986. return String();
  987. }
  988. if (p_slice < 0) {
  989. return String();
  990. }
  991. const char32_t *c = this->ptr();
  992. int i = 0;
  993. int prev = 0;
  994. int count = 0;
  995. while (true) {
  996. if (c[i] == 0 || c[i] == p_splitter) {
  997. if (p_slice == count) {
  998. return substr(prev, i - prev);
  999. } else if (c[i] == 0) {
  1000. return String();
  1001. } else {
  1002. count++;
  1003. prev = i + 1;
  1004. }
  1005. }
  1006. i++;
  1007. }
  1008. }
  1009. Vector<String> String::split_spaces() const {
  1010. Vector<String> ret;
  1011. int from = 0;
  1012. int i = 0;
  1013. int len = length();
  1014. if (len == 0) {
  1015. return ret;
  1016. }
  1017. bool inside = false;
  1018. while (true) {
  1019. bool empty = operator[](i) < 33;
  1020. if (i == 0) {
  1021. inside = !empty;
  1022. }
  1023. if (!empty && !inside) {
  1024. inside = true;
  1025. from = i;
  1026. }
  1027. if (empty && inside) {
  1028. ret.push_back(substr(from, i - from));
  1029. inside = false;
  1030. }
  1031. if (i == len) {
  1032. break;
  1033. }
  1034. i++;
  1035. }
  1036. return ret;
  1037. }
  1038. Vector<String> String::split(const String &p_splitter, bool p_allow_empty, int p_maxsplit) const {
  1039. Vector<String> ret;
  1040. if (is_empty()) {
  1041. if (p_allow_empty) {
  1042. ret.push_back("");
  1043. }
  1044. return ret;
  1045. }
  1046. int from = 0;
  1047. int len = length();
  1048. while (true) {
  1049. int end;
  1050. if (p_splitter.is_empty()) {
  1051. end = from + 1;
  1052. } else {
  1053. end = find(p_splitter, from);
  1054. if (end < 0) {
  1055. end = len;
  1056. }
  1057. }
  1058. if (p_allow_empty || (end > from)) {
  1059. if (p_maxsplit <= 0) {
  1060. ret.push_back(substr(from, end - from));
  1061. } else {
  1062. // Put rest of the string and leave cycle.
  1063. if (p_maxsplit == ret.size()) {
  1064. ret.push_back(substr(from, len));
  1065. break;
  1066. }
  1067. // Otherwise, push items until positive limit is reached.
  1068. ret.push_back(substr(from, end - from));
  1069. }
  1070. }
  1071. if (end == len) {
  1072. break;
  1073. }
  1074. from = end + p_splitter.length();
  1075. }
  1076. return ret;
  1077. }
  1078. Vector<String> String::rsplit(const String &p_splitter, bool p_allow_empty, int p_maxsplit) const {
  1079. Vector<String> ret;
  1080. const int len = length();
  1081. int remaining_len = len;
  1082. while (true) {
  1083. if (remaining_len < p_splitter.length() || (p_maxsplit > 0 && p_maxsplit == ret.size())) {
  1084. // no room for another splitter or hit max splits, push what's left and we're done
  1085. if (p_allow_empty || remaining_len > 0) {
  1086. ret.push_back(substr(0, remaining_len));
  1087. }
  1088. break;
  1089. }
  1090. int left_edge;
  1091. if (p_splitter.is_empty()) {
  1092. left_edge = remaining_len - 1;
  1093. if (left_edge == 0) {
  1094. left_edge--; // Skip to the < 0 condition.
  1095. }
  1096. } else {
  1097. left_edge = rfind(p_splitter, remaining_len - p_splitter.length());
  1098. }
  1099. if (left_edge < 0) {
  1100. // no more splitters, we're done
  1101. ret.push_back(substr(0, remaining_len));
  1102. break;
  1103. }
  1104. int substr_start = left_edge + p_splitter.length();
  1105. if (p_allow_empty || substr_start < remaining_len) {
  1106. ret.push_back(substr(substr_start, remaining_len - substr_start));
  1107. }
  1108. remaining_len = left_edge;
  1109. }
  1110. ret.reverse();
  1111. return ret;
  1112. }
  1113. Vector<double> String::split_floats(const String &p_splitter, bool p_allow_empty) const {
  1114. Vector<double> ret;
  1115. int from = 0;
  1116. int len = length();
  1117. while (true) {
  1118. int end = find(p_splitter, from);
  1119. if (end < 0) {
  1120. end = len;
  1121. }
  1122. if (p_allow_empty || (end > from)) {
  1123. ret.push_back(String::to_float(&get_data()[from]));
  1124. }
  1125. if (end == len) {
  1126. break;
  1127. }
  1128. from = end + p_splitter.length();
  1129. }
  1130. return ret;
  1131. }
  1132. Vector<float> String::split_floats_mk(const Vector<String> &p_splitters, bool p_allow_empty) const {
  1133. Vector<float> ret;
  1134. int from = 0;
  1135. int len = length();
  1136. while (true) {
  1137. int idx;
  1138. int end = findmk(p_splitters, from, &idx);
  1139. int spl_len = 1;
  1140. if (end < 0) {
  1141. end = len;
  1142. } else {
  1143. spl_len = p_splitters[idx].length();
  1144. }
  1145. if (p_allow_empty || (end > from)) {
  1146. ret.push_back(String::to_float(&get_data()[from]));
  1147. }
  1148. if (end == len) {
  1149. break;
  1150. }
  1151. from = end + spl_len;
  1152. }
  1153. return ret;
  1154. }
  1155. Vector<int> String::split_ints(const String &p_splitter, bool p_allow_empty) const {
  1156. Vector<int> ret;
  1157. int from = 0;
  1158. int len = length();
  1159. while (true) {
  1160. int end = find(p_splitter, from);
  1161. if (end < 0) {
  1162. end = len;
  1163. }
  1164. if (p_allow_empty || (end > from)) {
  1165. ret.push_back(String::to_int(&get_data()[from], end - from));
  1166. }
  1167. if (end == len) {
  1168. break;
  1169. }
  1170. from = end + p_splitter.length();
  1171. }
  1172. return ret;
  1173. }
  1174. Vector<int> String::split_ints_mk(const Vector<String> &p_splitters, bool p_allow_empty) const {
  1175. Vector<int> ret;
  1176. int from = 0;
  1177. int len = length();
  1178. while (true) {
  1179. int idx;
  1180. int end = findmk(p_splitters, from, &idx);
  1181. int spl_len = 1;
  1182. if (end < 0) {
  1183. end = len;
  1184. } else {
  1185. spl_len = p_splitters[idx].length();
  1186. }
  1187. if (p_allow_empty || (end > from)) {
  1188. ret.push_back(String::to_int(&get_data()[from], end - from));
  1189. }
  1190. if (end == len) {
  1191. break;
  1192. }
  1193. from = end + spl_len;
  1194. }
  1195. return ret;
  1196. }
  1197. String String::join(Vector<String> parts) const {
  1198. String ret;
  1199. for (int i = 0; i < parts.size(); ++i) {
  1200. if (i > 0) {
  1201. ret += *this;
  1202. }
  1203. ret += parts[i];
  1204. }
  1205. return ret;
  1206. }
  1207. char32_t String::char_uppercase(char32_t p_char) {
  1208. return _find_upper(p_char);
  1209. }
  1210. char32_t String::char_lowercase(char32_t p_char) {
  1211. return _find_lower(p_char);
  1212. }
  1213. String String::to_upper() const {
  1214. String upper = *this;
  1215. for (int i = 0; i < upper.size(); i++) {
  1216. const char32_t s = upper[i];
  1217. const char32_t t = _find_upper(s);
  1218. if (s != t) { // avoid copy on write
  1219. upper[i] = t;
  1220. }
  1221. }
  1222. return upper;
  1223. }
  1224. String String::to_lower() const {
  1225. String lower = *this;
  1226. for (int i = 0; i < lower.size(); i++) {
  1227. const char32_t s = lower[i];
  1228. const char32_t t = _find_lower(s);
  1229. if (s != t) { // avoid copy on write
  1230. lower[i] = t;
  1231. }
  1232. }
  1233. return lower;
  1234. }
  1235. String String::chr(char32_t p_char) {
  1236. char32_t c[2] = { p_char, 0 };
  1237. return String(c);
  1238. }
  1239. String String::num(double p_num, int p_decimals) {
  1240. if (Math::is_nan(p_num)) {
  1241. return "nan";
  1242. }
  1243. if (Math::is_inf(p_num)) {
  1244. if (signbit(p_num)) {
  1245. return "-inf";
  1246. } else {
  1247. return "inf";
  1248. }
  1249. }
  1250. if (p_decimals < 0) {
  1251. p_decimals = 14;
  1252. const double abs_num = Math::abs(p_num);
  1253. if (abs_num > 10) {
  1254. // We want to align the digits to the above reasonable default, so we only
  1255. // need to subtract log10 for numbers with a positive power of ten.
  1256. p_decimals -= (int)floor(log10(abs_num));
  1257. }
  1258. }
  1259. if (p_decimals > MAX_DECIMALS) {
  1260. p_decimals = MAX_DECIMALS;
  1261. }
  1262. char fmt[7];
  1263. fmt[0] = '%';
  1264. fmt[1] = '.';
  1265. if (p_decimals < 0) {
  1266. fmt[1] = 'l';
  1267. fmt[2] = 'f';
  1268. fmt[3] = 0;
  1269. } else if (p_decimals < 10) {
  1270. fmt[2] = '0' + p_decimals;
  1271. fmt[3] = 'l';
  1272. fmt[4] = 'f';
  1273. fmt[5] = 0;
  1274. } else {
  1275. fmt[2] = '0' + (p_decimals / 10);
  1276. fmt[3] = '0' + (p_decimals % 10);
  1277. fmt[4] = 'l';
  1278. fmt[5] = 'f';
  1279. fmt[6] = 0;
  1280. }
  1281. // if we want to convert a double with as much decimal places as as
  1282. // DBL_MAX or DBL_MIN then we would theoretically need a buffer of at least
  1283. // DBL_MAX_10_EXP + 2 for DBL_MAX and DBL_MAX_10_EXP + 4 for DBL_MIN.
  1284. // BUT those values where still giving me exceptions, so I tested from
  1285. // DBL_MAX_10_EXP + 10 incrementing one by one and DBL_MAX_10_EXP + 17 (325)
  1286. // was the first buffer size not to throw an exception
  1287. char buf[325];
  1288. #if defined(__GNUC__) || defined(_MSC_VER)
  1289. // PLEASE NOTE that, albeit vcrt online reference states that snprintf
  1290. // should safely truncate the output to the given buffer size, we have
  1291. // found a case where this is not true, so we should create a buffer
  1292. // as big as needed
  1293. snprintf(buf, 325, fmt, p_num);
  1294. #else
  1295. sprintf(buf, fmt, p_num);
  1296. #endif
  1297. buf[324] = 0;
  1298. //destroy trailing zeroes
  1299. {
  1300. bool period = false;
  1301. int z = 0;
  1302. while (buf[z]) {
  1303. if (buf[z] == '.') {
  1304. period = true;
  1305. }
  1306. z++;
  1307. }
  1308. if (period) {
  1309. z--;
  1310. while (z > 0) {
  1311. if (buf[z] == '0') {
  1312. buf[z] = 0;
  1313. } else if (buf[z] == '.') {
  1314. buf[z] = 0;
  1315. break;
  1316. } else {
  1317. break;
  1318. }
  1319. z--;
  1320. }
  1321. }
  1322. }
  1323. return buf;
  1324. }
  1325. String String::num_int64(int64_t p_num, int base, bool capitalize_hex) {
  1326. bool sign = p_num < 0;
  1327. int64_t n = p_num;
  1328. int chars = 0;
  1329. do {
  1330. n /= base;
  1331. chars++;
  1332. } while (n);
  1333. if (sign) {
  1334. chars++;
  1335. }
  1336. String s;
  1337. s.resize(chars + 1);
  1338. char32_t *c = s.ptrw();
  1339. c[chars] = 0;
  1340. n = p_num;
  1341. do {
  1342. int mod = ABS(n % base);
  1343. if (mod >= 10) {
  1344. char a = (capitalize_hex ? 'A' : 'a');
  1345. c[--chars] = a + (mod - 10);
  1346. } else {
  1347. c[--chars] = '0' + mod;
  1348. }
  1349. n /= base;
  1350. } while (n);
  1351. if (sign) {
  1352. c[0] = '-';
  1353. }
  1354. return s;
  1355. }
  1356. String String::num_uint64(uint64_t p_num, int base, bool capitalize_hex) {
  1357. uint64_t n = p_num;
  1358. int chars = 0;
  1359. do {
  1360. n /= base;
  1361. chars++;
  1362. } while (n);
  1363. String s;
  1364. s.resize(chars + 1);
  1365. char32_t *c = s.ptrw();
  1366. c[chars] = 0;
  1367. n = p_num;
  1368. do {
  1369. int mod = n % base;
  1370. if (mod >= 10) {
  1371. char a = (capitalize_hex ? 'A' : 'a');
  1372. c[--chars] = a + (mod - 10);
  1373. } else {
  1374. c[--chars] = '0' + mod;
  1375. }
  1376. n /= base;
  1377. } while (n);
  1378. return s;
  1379. }
  1380. String String::num_real(double p_num, bool p_trailing) {
  1381. if (p_num == (double)(int64_t)p_num) {
  1382. if (p_trailing) {
  1383. return num_int64((int64_t)p_num) + ".0";
  1384. } else {
  1385. return num_int64((int64_t)p_num);
  1386. }
  1387. }
  1388. #ifdef REAL_T_IS_DOUBLE
  1389. int decimals = 14;
  1390. #else
  1391. int decimals = 6;
  1392. #endif
  1393. // We want to align the digits to the above sane default, so we only need
  1394. // to subtract log10 for numbers with a positive power of ten magnitude.
  1395. double abs_num = Math::abs(p_num);
  1396. if (abs_num > 10) {
  1397. decimals -= (int)floor(log10(abs_num));
  1398. }
  1399. return num(p_num, decimals);
  1400. }
  1401. String String::num_scientific(double p_num) {
  1402. if (Math::is_nan(p_num)) {
  1403. return "nan";
  1404. }
  1405. if (Math::is_inf(p_num)) {
  1406. if (signbit(p_num)) {
  1407. return "-inf";
  1408. } else {
  1409. return "inf";
  1410. }
  1411. }
  1412. char buf[256];
  1413. #if defined(__GNUC__) || defined(_MSC_VER)
  1414. #if defined(__MINGW32__) && defined(_TWO_DIGIT_EXPONENT) && !defined(_UCRT)
  1415. // MinGW requires _set_output_format() to conform to C99 output for printf
  1416. unsigned int old_exponent_format = _set_output_format(_TWO_DIGIT_EXPONENT);
  1417. #endif
  1418. snprintf(buf, 256, "%lg", p_num);
  1419. #if defined(__MINGW32__) && defined(_TWO_DIGIT_EXPONENT) && !defined(_UCRT)
  1420. _set_output_format(old_exponent_format);
  1421. #endif
  1422. #else
  1423. sprintf(buf, "%.16lg", p_num);
  1424. #endif
  1425. buf[255] = 0;
  1426. return buf;
  1427. }
  1428. String String::md5(const uint8_t *p_md5) {
  1429. return String::hex_encode_buffer(p_md5, 16);
  1430. }
  1431. String String::hex_encode_buffer(const uint8_t *p_buffer, int p_len) {
  1432. static const char hex[16] = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f' };
  1433. String ret;
  1434. char v[2] = { 0, 0 };
  1435. for (int i = 0; i < p_len; i++) {
  1436. v[0] = hex[p_buffer[i] >> 4];
  1437. ret += v;
  1438. v[0] = hex[p_buffer[i] & 0xF];
  1439. ret += v;
  1440. }
  1441. return ret;
  1442. }
  1443. Vector<uint8_t> String::hex_decode() const {
  1444. ERR_FAIL_COND_V_MSG(length() % 2 != 0, Vector<uint8_t>(), "Hexadecimal string of uneven length.");
  1445. #define HEX_TO_BYTE(m_output, m_index) \
  1446. uint8_t m_output; \
  1447. c = operator[](m_index); \
  1448. if (is_digit(c)) { \
  1449. m_output = c - '0'; \
  1450. } else if (c >= 'a' && c <= 'f') { \
  1451. m_output = c - 'a' + 10; \
  1452. } else if (c >= 'A' && c <= 'F') { \
  1453. m_output = c - 'A' + 10; \
  1454. } else { \
  1455. ERR_FAIL_V_MSG(Vector<uint8_t>(), "Invalid hexadecimal character \"" + chr(c) + "\" at index " + m_index + "."); \
  1456. }
  1457. Vector<uint8_t> out;
  1458. int len = length() / 2;
  1459. out.resize(len);
  1460. for (int i = 0; i < len; i++) {
  1461. char32_t c;
  1462. HEX_TO_BYTE(first, i * 2);
  1463. HEX_TO_BYTE(second, i * 2 + 1);
  1464. out.write[i] = first * 16 + second;
  1465. }
  1466. return out;
  1467. #undef HEX_TO_BYTE
  1468. }
  1469. void String::print_unicode_error(const String &p_message, bool p_critical) const {
  1470. if (p_critical) {
  1471. print_error(vformat(U"Unicode parsing error, some characters were replaced with � (U+FFFD): %s", p_message));
  1472. } else {
  1473. print_error(vformat("Unicode parsing error: %s", p_message));
  1474. }
  1475. }
  1476. CharString String::ascii(bool p_allow_extended) const {
  1477. if (!length()) {
  1478. return CharString();
  1479. }
  1480. CharString cs;
  1481. cs.resize(size());
  1482. for (int i = 0; i < size(); i++) {
  1483. char32_t c = operator[](i);
  1484. if ((c <= 0x7f) || (c <= 0xff && p_allow_extended)) {
  1485. cs[i] = c;
  1486. } else {
  1487. print_unicode_error(vformat("Invalid unicode codepoint (%x), cannot represent as ASCII/Latin-1", (uint32_t)c));
  1488. cs[i] = 0x20; // ascii doesn't have a replacement character like unicode, 0x1a is sometimes used but is kinda arcane
  1489. }
  1490. }
  1491. return cs;
  1492. }
  1493. String String::utf8(const char *p_utf8, int p_len) {
  1494. String ret;
  1495. ret.parse_utf8(p_utf8, p_len);
  1496. return ret;
  1497. }
  1498. Error String::parse_utf8(const char *p_utf8, int p_len, bool p_skip_cr) {
  1499. if (!p_utf8) {
  1500. return ERR_INVALID_DATA;
  1501. }
  1502. String aux;
  1503. int cstr_size = 0;
  1504. int str_size = 0;
  1505. /* HANDLE BOM (Byte Order Mark) */
  1506. if (p_len < 0 || p_len >= 3) {
  1507. bool has_bom = uint8_t(p_utf8[0]) == 0xef && uint8_t(p_utf8[1]) == 0xbb && uint8_t(p_utf8[2]) == 0xbf;
  1508. if (has_bom) {
  1509. //8-bit encoding, byte order has no meaning in UTF-8, just skip it
  1510. if (p_len >= 0) {
  1511. p_len -= 3;
  1512. }
  1513. p_utf8 += 3;
  1514. }
  1515. }
  1516. bool decode_error = false;
  1517. bool decode_failed = false;
  1518. {
  1519. const char *ptrtmp = p_utf8;
  1520. const char *ptrtmp_limit = &p_utf8[p_len];
  1521. int skip = 0;
  1522. uint8_t c_start = 0;
  1523. while (ptrtmp != ptrtmp_limit && *ptrtmp) {
  1524. #if CHAR_MIN == 0
  1525. uint8_t c = *ptrtmp;
  1526. #else
  1527. uint8_t c = *ptrtmp >= 0 ? *ptrtmp : uint8_t(256 + *ptrtmp);
  1528. #endif
  1529. if (skip == 0) {
  1530. if (p_skip_cr && c == '\r') {
  1531. ptrtmp++;
  1532. continue;
  1533. }
  1534. /* Determine the number of characters in sequence */
  1535. if ((c & 0x80) == 0) {
  1536. skip = 0;
  1537. } else if ((c & 0xe0) == 0xc0) {
  1538. skip = 1;
  1539. } else if ((c & 0xf0) == 0xe0) {
  1540. skip = 2;
  1541. } else if ((c & 0xf8) == 0xf0) {
  1542. skip = 3;
  1543. } else if ((c & 0xfc) == 0xf8) {
  1544. skip = 4;
  1545. } else if ((c & 0xfe) == 0xfc) {
  1546. skip = 5;
  1547. } else {
  1548. skip = 0;
  1549. print_unicode_error(vformat("Invalid UTF-8 leading byte (%x)", c), true);
  1550. decode_failed = true;
  1551. }
  1552. c_start = c;
  1553. if (skip == 1 && (c & 0x1e) == 0) {
  1554. print_unicode_error(vformat("Overlong encoding (%x ...)", c));
  1555. decode_error = true;
  1556. }
  1557. str_size++;
  1558. } else {
  1559. if ((c_start == 0xe0 && skip == 2 && c < 0xa0) || (c_start == 0xf0 && skip == 3 && c < 0x90) || (c_start == 0xf8 && skip == 4 && c < 0x88) || (c_start == 0xfc && skip == 5 && c < 0x84)) {
  1560. print_unicode_error(vformat("Overlong encoding (%x %x ...)", c_start, c));
  1561. decode_error = true;
  1562. }
  1563. if (c < 0x80 || c > 0xbf) {
  1564. print_unicode_error(vformat("Invalid UTF-8 continuation byte (%x ... %x ...)", c_start, c), true);
  1565. decode_failed = true;
  1566. skip = 0;
  1567. } else {
  1568. --skip;
  1569. }
  1570. }
  1571. cstr_size++;
  1572. ptrtmp++;
  1573. }
  1574. if (skip) {
  1575. print_unicode_error(vformat("Missing %d UTF-8 continuation byte(s)", skip), true);
  1576. decode_failed = true;
  1577. }
  1578. }
  1579. if (str_size == 0) {
  1580. clear();
  1581. return OK; // empty string
  1582. }
  1583. resize(str_size + 1);
  1584. char32_t *dst = ptrw();
  1585. dst[str_size] = 0;
  1586. int skip = 0;
  1587. uint32_t unichar = 0;
  1588. while (cstr_size) {
  1589. #if CHAR_MIN == 0
  1590. uint8_t c = *p_utf8;
  1591. #else
  1592. uint8_t c = *p_utf8 >= 0 ? *p_utf8 : uint8_t(256 + *p_utf8);
  1593. #endif
  1594. if (skip == 0) {
  1595. if (p_skip_cr && c == '\r') {
  1596. p_utf8++;
  1597. continue;
  1598. }
  1599. /* Determine the number of characters in sequence */
  1600. if ((c & 0x80) == 0) {
  1601. *(dst++) = c;
  1602. unichar = 0;
  1603. skip = 0;
  1604. } else if ((c & 0xe0) == 0xc0) {
  1605. unichar = (0xff >> 3) & c;
  1606. skip = 1;
  1607. } else if ((c & 0xf0) == 0xe0) {
  1608. unichar = (0xff >> 4) & c;
  1609. skip = 2;
  1610. } else if ((c & 0xf8) == 0xf0) {
  1611. unichar = (0xff >> 5) & c;
  1612. skip = 3;
  1613. } else if ((c & 0xfc) == 0xf8) {
  1614. unichar = (0xff >> 6) & c;
  1615. skip = 4;
  1616. } else if ((c & 0xfe) == 0xfc) {
  1617. unichar = (0xff >> 7) & c;
  1618. skip = 5;
  1619. } else {
  1620. *(dst++) = _replacement_char;
  1621. unichar = 0;
  1622. skip = 0;
  1623. }
  1624. } else {
  1625. if (c < 0x80 || c > 0xbf) {
  1626. *(dst++) = _replacement_char;
  1627. skip = 0;
  1628. } else {
  1629. unichar = (unichar << 6) | (c & 0x3f);
  1630. --skip;
  1631. if (skip == 0) {
  1632. if (unichar == 0) {
  1633. print_unicode_error("NUL character", true);
  1634. decode_failed = true;
  1635. unichar = _replacement_char;
  1636. } else if ((unichar & 0xfffff800) == 0xd800) {
  1637. print_unicode_error(vformat("Unpaired surrogate (%x)", unichar), true);
  1638. decode_failed = true;
  1639. unichar = _replacement_char;
  1640. } else if (unichar > 0x10ffff) {
  1641. print_unicode_error(vformat("Invalid unicode codepoint (%x)", unichar), true);
  1642. decode_failed = true;
  1643. unichar = _replacement_char;
  1644. }
  1645. *(dst++) = unichar;
  1646. }
  1647. }
  1648. }
  1649. cstr_size--;
  1650. p_utf8++;
  1651. }
  1652. if (skip) {
  1653. *(dst++) = 0x20;
  1654. }
  1655. if (decode_failed) {
  1656. return ERR_INVALID_DATA;
  1657. } else if (decode_error) {
  1658. return ERR_PARSE_ERROR;
  1659. } else {
  1660. return OK;
  1661. }
  1662. }
  1663. CharString String::utf8() const {
  1664. int l = length();
  1665. if (!l) {
  1666. return CharString();
  1667. }
  1668. const char32_t *d = &operator[](0);
  1669. int fl = 0;
  1670. for (int i = 0; i < l; i++) {
  1671. uint32_t c = d[i];
  1672. if (c <= 0x7f) { // 7 bits.
  1673. fl += 1;
  1674. } else if (c <= 0x7ff) { // 11 bits
  1675. fl += 2;
  1676. } else if (c <= 0xffff) { // 16 bits
  1677. fl += 3;
  1678. } else if (c <= 0x001fffff) { // 21 bits
  1679. fl += 4;
  1680. } else if (c <= 0x03ffffff) { // 26 bits
  1681. fl += 5;
  1682. print_unicode_error(vformat("Invalid unicode codepoint (%x)", c));
  1683. } else if (c <= 0x7fffffff) { // 31 bits
  1684. fl += 6;
  1685. print_unicode_error(vformat("Invalid unicode codepoint (%x)", c));
  1686. } else {
  1687. fl += 1;
  1688. print_unicode_error(vformat("Invalid unicode codepoint (%x), cannot represent as UTF-8", c), true);
  1689. }
  1690. }
  1691. CharString utf8s;
  1692. if (fl == 0) {
  1693. return utf8s;
  1694. }
  1695. utf8s.resize(fl + 1);
  1696. uint8_t *cdst = (uint8_t *)utf8s.get_data();
  1697. #define APPEND_CHAR(m_c) *(cdst++) = m_c
  1698. for (int i = 0; i < l; i++) {
  1699. uint32_t c = d[i];
  1700. if (c <= 0x7f) { // 7 bits.
  1701. APPEND_CHAR(c);
  1702. } else if (c <= 0x7ff) { // 11 bits
  1703. APPEND_CHAR(uint32_t(0xc0 | ((c >> 6) & 0x1f))); // Top 5 bits.
  1704. APPEND_CHAR(uint32_t(0x80 | (c & 0x3f))); // Bottom 6 bits.
  1705. } else if (c <= 0xffff) { // 16 bits
  1706. APPEND_CHAR(uint32_t(0xe0 | ((c >> 12) & 0x0f))); // Top 4 bits.
  1707. APPEND_CHAR(uint32_t(0x80 | ((c >> 6) & 0x3f))); // Middle 6 bits.
  1708. APPEND_CHAR(uint32_t(0x80 | (c & 0x3f))); // Bottom 6 bits.
  1709. } else if (c <= 0x001fffff) { // 21 bits
  1710. APPEND_CHAR(uint32_t(0xf0 | ((c >> 18) & 0x07))); // Top 3 bits.
  1711. APPEND_CHAR(uint32_t(0x80 | ((c >> 12) & 0x3f))); // Upper middle 6 bits.
  1712. APPEND_CHAR(uint32_t(0x80 | ((c >> 6) & 0x3f))); // Lower middle 6 bits.
  1713. APPEND_CHAR(uint32_t(0x80 | (c & 0x3f))); // Bottom 6 bits.
  1714. } else if (c <= 0x03ffffff) { // 26 bits
  1715. APPEND_CHAR(uint32_t(0xf8 | ((c >> 24) & 0x03))); // Top 2 bits.
  1716. APPEND_CHAR(uint32_t(0x80 | ((c >> 18) & 0x3f))); // Upper middle 6 bits.
  1717. APPEND_CHAR(uint32_t(0x80 | ((c >> 12) & 0x3f))); // middle 6 bits.
  1718. APPEND_CHAR(uint32_t(0x80 | ((c >> 6) & 0x3f))); // Lower middle 6 bits.
  1719. APPEND_CHAR(uint32_t(0x80 | (c & 0x3f))); // Bottom 6 bits.
  1720. } else if (c <= 0x7fffffff) { // 31 bits
  1721. APPEND_CHAR(uint32_t(0xfc | ((c >> 30) & 0x01))); // Top 1 bit.
  1722. APPEND_CHAR(uint32_t(0x80 | ((c >> 24) & 0x3f))); // Upper upper middle 6 bits.
  1723. APPEND_CHAR(uint32_t(0x80 | ((c >> 18) & 0x3f))); // Lower upper middle 6 bits.
  1724. APPEND_CHAR(uint32_t(0x80 | ((c >> 12) & 0x3f))); // Upper lower middle 6 bits.
  1725. APPEND_CHAR(uint32_t(0x80 | ((c >> 6) & 0x3f))); // Lower lower middle 6 bits.
  1726. APPEND_CHAR(uint32_t(0x80 | (c & 0x3f))); // Bottom 6 bits.
  1727. } else {
  1728. // the string is a valid UTF32, so it should never happen ...
  1729. print_unicode_error(vformat("Non scalar value (%x)", c), true);
  1730. APPEND_CHAR(uint32_t(0xe0 | ((_replacement_char >> 12) & 0x0f))); // Top 4 bits.
  1731. APPEND_CHAR(uint32_t(0x80 | ((_replacement_char >> 6) & 0x3f))); // Middle 6 bits.
  1732. APPEND_CHAR(uint32_t(0x80 | (_replacement_char & 0x3f))); // Bottom 6 bits.
  1733. }
  1734. }
  1735. #undef APPEND_CHAR
  1736. *cdst = 0; //trailing zero
  1737. return utf8s;
  1738. }
  1739. String String::utf16(const char16_t *p_utf16, int p_len) {
  1740. String ret;
  1741. ret.parse_utf16(p_utf16, p_len);
  1742. return ret;
  1743. }
  1744. Error String::parse_utf16(const char16_t *p_utf16, int p_len) {
  1745. if (!p_utf16) {
  1746. return ERR_INVALID_DATA;
  1747. }
  1748. String aux;
  1749. int cstr_size = 0;
  1750. int str_size = 0;
  1751. /* HANDLE BOM (Byte Order Mark) */
  1752. bool byteswap = false; // assume correct endianness if no BOM found
  1753. if (p_len < 0 || p_len >= 1) {
  1754. bool has_bom = false;
  1755. if (uint16_t(p_utf16[0]) == 0xfeff) { // correct BOM, read as is
  1756. has_bom = true;
  1757. byteswap = false;
  1758. } else if (uint16_t(p_utf16[0]) == 0xfffe) { // backwards BOM, swap bytes
  1759. has_bom = true;
  1760. byteswap = true;
  1761. }
  1762. if (has_bom) {
  1763. if (p_len >= 0) {
  1764. p_len -= 1;
  1765. }
  1766. p_utf16 += 1;
  1767. }
  1768. }
  1769. bool decode_error = false;
  1770. {
  1771. const char16_t *ptrtmp = p_utf16;
  1772. const char16_t *ptrtmp_limit = &p_utf16[p_len];
  1773. uint32_t c_prev = 0;
  1774. bool skip = false;
  1775. while (ptrtmp != ptrtmp_limit && *ptrtmp) {
  1776. uint32_t c = (byteswap) ? BSWAP16(*ptrtmp) : *ptrtmp;
  1777. if ((c & 0xfffffc00) == 0xd800) { // lead surrogate
  1778. if (skip) {
  1779. print_unicode_error(vformat("Unpaired lead surrogate (%x [trail?] %x)", c_prev, c));
  1780. decode_error = true;
  1781. }
  1782. skip = true;
  1783. } else if ((c & 0xfffffc00) == 0xdc00) { // trail surrogate
  1784. if (skip) {
  1785. str_size--;
  1786. } else {
  1787. print_unicode_error(vformat("Unpaired trail surrogate (%x [lead?] %x)", c_prev, c));
  1788. decode_error = true;
  1789. }
  1790. skip = false;
  1791. } else {
  1792. skip = false;
  1793. }
  1794. c_prev = c;
  1795. str_size++;
  1796. cstr_size++;
  1797. ptrtmp++;
  1798. }
  1799. if (skip) {
  1800. print_unicode_error(vformat("Unpaired lead surrogate (%x [eol])", c_prev));
  1801. decode_error = true;
  1802. }
  1803. }
  1804. if (str_size == 0) {
  1805. clear();
  1806. return OK; // empty string
  1807. }
  1808. resize(str_size + 1);
  1809. char32_t *dst = ptrw();
  1810. dst[str_size] = 0;
  1811. bool skip = false;
  1812. uint32_t c_prev = 0;
  1813. while (cstr_size) {
  1814. uint32_t c = (byteswap) ? BSWAP16(*p_utf16) : *p_utf16;
  1815. if ((c & 0xfffffc00) == 0xd800) { // lead surrogate
  1816. if (skip) {
  1817. *(dst++) = c_prev; // unpaired, store as is
  1818. }
  1819. skip = true;
  1820. } else if ((c & 0xfffffc00) == 0xdc00) { // trail surrogate
  1821. if (skip) {
  1822. *(dst++) = (c_prev << 10UL) + c - ((0xd800 << 10UL) + 0xdc00 - 0x10000); // decode pair
  1823. } else {
  1824. *(dst++) = c; // unpaired, store as is
  1825. }
  1826. skip = false;
  1827. } else {
  1828. *(dst++) = c;
  1829. skip = false;
  1830. }
  1831. cstr_size--;
  1832. p_utf16++;
  1833. c_prev = c;
  1834. }
  1835. if (skip) {
  1836. *(dst++) = c_prev;
  1837. }
  1838. if (decode_error) {
  1839. return ERR_PARSE_ERROR;
  1840. } else {
  1841. return OK;
  1842. }
  1843. }
  1844. Char16String String::utf16() const {
  1845. int l = length();
  1846. if (!l) {
  1847. return Char16String();
  1848. }
  1849. const char32_t *d = &operator[](0);
  1850. int fl = 0;
  1851. for (int i = 0; i < l; i++) {
  1852. uint32_t c = d[i];
  1853. if (c <= 0xffff) { // 16 bits.
  1854. fl += 1;
  1855. if ((c & 0xfffff800) == 0xd800) {
  1856. print_unicode_error(vformat("Unpaired surrogate (%x)", c));
  1857. }
  1858. } else if (c <= 0x10ffff) { // 32 bits.
  1859. fl += 2;
  1860. } else {
  1861. print_unicode_error(vformat("Invalid unicode codepoint (%x), cannot represent as UTF-16", c), true);
  1862. fl += 1;
  1863. }
  1864. }
  1865. Char16String utf16s;
  1866. if (fl == 0) {
  1867. return utf16s;
  1868. }
  1869. utf16s.resize(fl + 1);
  1870. uint16_t *cdst = (uint16_t *)utf16s.get_data();
  1871. #define APPEND_CHAR(m_c) *(cdst++) = m_c
  1872. for (int i = 0; i < l; i++) {
  1873. uint32_t c = d[i];
  1874. if (c <= 0xffff) { // 16 bits.
  1875. APPEND_CHAR(c);
  1876. } else if (c <= 0x10ffff) { // 32 bits.
  1877. APPEND_CHAR(uint32_t((c >> 10) + 0xd7c0)); // lead surrogate.
  1878. APPEND_CHAR(uint32_t((c & 0x3ff) | 0xdc00)); // trail surrogate.
  1879. } else {
  1880. // the string is a valid UTF32, so it should never happen ...
  1881. APPEND_CHAR(uint32_t((_replacement_char >> 10) + 0xd7c0));
  1882. APPEND_CHAR(uint32_t((_replacement_char & 0x3ff) | 0xdc00));
  1883. }
  1884. }
  1885. #undef APPEND_CHAR
  1886. *cdst = 0; //trailing zero
  1887. return utf16s;
  1888. }
  1889. String::String(const char *p_str) {
  1890. copy_from(p_str);
  1891. }
  1892. String::String(const wchar_t *p_str) {
  1893. copy_from(p_str);
  1894. }
  1895. String::String(const char32_t *p_str) {
  1896. copy_from(p_str);
  1897. }
  1898. String::String(const char *p_str, int p_clip_to_len) {
  1899. copy_from(p_str, p_clip_to_len);
  1900. }
  1901. String::String(const wchar_t *p_str, int p_clip_to_len) {
  1902. copy_from(p_str, p_clip_to_len);
  1903. }
  1904. String::String(const char32_t *p_str, int p_clip_to_len) {
  1905. copy_from(p_str, p_clip_to_len);
  1906. }
  1907. String::String(const StrRange &p_range) {
  1908. if (!p_range.c_str) {
  1909. return;
  1910. }
  1911. copy_from(p_range.c_str, p_range.len);
  1912. }
  1913. int64_t String::hex_to_int() const {
  1914. int len = length();
  1915. if (len == 0) {
  1916. return 0;
  1917. }
  1918. const char32_t *s = ptr();
  1919. int64_t sign = s[0] == '-' ? -1 : 1;
  1920. if (sign < 0) {
  1921. s++;
  1922. }
  1923. if (len > 2 && s[0] == '0' && lower_case(s[1]) == 'x') {
  1924. s += 2;
  1925. }
  1926. int64_t hex = 0;
  1927. while (*s) {
  1928. char32_t c = lower_case(*s);
  1929. int64_t n;
  1930. if (is_digit(c)) {
  1931. n = c - '0';
  1932. } else if (c >= 'a' && c <= 'f') {
  1933. n = (c - 'a') + 10;
  1934. } else {
  1935. ERR_FAIL_V_MSG(0, vformat(R"(Invalid hexadecimal notation character "%c" (U+%04X) in string "%s".)", *s, static_cast<int32_t>(*s), *this));
  1936. }
  1937. // Check for overflow/underflow, with special case to ensure INT64_MIN does not result in error
  1938. bool overflow = ((hex > INT64_MAX / 16) && (sign == 1 || (sign == -1 && hex != (INT64_MAX >> 4) + 1))) || (sign == -1 && hex == (INT64_MAX >> 4) + 1 && c > '0');
  1939. ERR_FAIL_COND_V_MSG(overflow, sign == 1 ? INT64_MAX : INT64_MIN, "Cannot represent " + *this + " as a 64-bit signed integer, since the value is " + (sign == 1 ? "too large." : "too small."));
  1940. hex *= 16;
  1941. hex += n;
  1942. s++;
  1943. }
  1944. return hex * sign;
  1945. }
  1946. int64_t String::bin_to_int() const {
  1947. int len = length();
  1948. if (len == 0) {
  1949. return 0;
  1950. }
  1951. const char32_t *s = ptr();
  1952. int64_t sign = s[0] == '-' ? -1 : 1;
  1953. if (sign < 0) {
  1954. s++;
  1955. }
  1956. if (len > 2 && s[0] == '0' && lower_case(s[1]) == 'b') {
  1957. s += 2;
  1958. }
  1959. int64_t binary = 0;
  1960. while (*s) {
  1961. char32_t c = lower_case(*s);
  1962. int64_t n;
  1963. if (c == '0' || c == '1') {
  1964. n = c - '0';
  1965. } else {
  1966. return 0;
  1967. }
  1968. // Check for overflow/underflow, with special case to ensure INT64_MIN does not result in error
  1969. bool overflow = ((binary > INT64_MAX / 2) && (sign == 1 || (sign == -1 && binary != (INT64_MAX >> 1) + 1))) || (sign == -1 && binary == (INT64_MAX >> 1) + 1 && c > '0');
  1970. ERR_FAIL_COND_V_MSG(overflow, sign == 1 ? INT64_MAX : INT64_MIN, "Cannot represent " + *this + " as a 64-bit signed integer, since the value is " + (sign == 1 ? "too large." : "too small."));
  1971. binary *= 2;
  1972. binary += n;
  1973. s++;
  1974. }
  1975. return binary * sign;
  1976. }
  1977. int64_t String::to_int() const {
  1978. if (length() == 0) {
  1979. return 0;
  1980. }
  1981. int to = (find(".") >= 0) ? find(".") : length();
  1982. int64_t integer = 0;
  1983. int64_t sign = 1;
  1984. for (int i = 0; i < to; i++) {
  1985. char32_t c = operator[](i);
  1986. if (is_digit(c)) {
  1987. bool overflow = (integer > INT64_MAX / 10) || (integer == INT64_MAX / 10 && ((sign == 1 && c > '7') || (sign == -1 && c > '8')));
  1988. ERR_FAIL_COND_V_MSG(overflow, sign == 1 ? INT64_MAX : INT64_MIN, "Cannot represent " + *this + " as a 64-bit signed integer, since the value is " + (sign == 1 ? "too large." : "too small."));
  1989. integer *= 10;
  1990. integer += c - '0';
  1991. } else if (integer == 0 && c == '-') {
  1992. sign = -sign;
  1993. }
  1994. }
  1995. return integer * sign;
  1996. }
  1997. int64_t String::to_int(const char *p_str, int p_len) {
  1998. int to = 0;
  1999. if (p_len >= 0) {
  2000. to = p_len;
  2001. } else {
  2002. while (p_str[to] != 0 && p_str[to] != '.') {
  2003. to++;
  2004. }
  2005. }
  2006. int64_t integer = 0;
  2007. int64_t sign = 1;
  2008. for (int i = 0; i < to; i++) {
  2009. char c = p_str[i];
  2010. if (is_digit(c)) {
  2011. bool overflow = (integer > INT64_MAX / 10) || (integer == INT64_MAX / 10 && ((sign == 1 && c > '7') || (sign == -1 && c > '8')));
  2012. ERR_FAIL_COND_V_MSG(overflow, sign == 1 ? INT64_MAX : INT64_MIN, "Cannot represent " + String(p_str).substr(0, to) + " as a 64-bit signed integer, since the value is " + (sign == 1 ? "too large." : "too small."));
  2013. integer *= 10;
  2014. integer += c - '0';
  2015. } else if (c == '-' && integer == 0) {
  2016. sign = -sign;
  2017. } else if (c != ' ') {
  2018. break;
  2019. }
  2020. }
  2021. return integer * sign;
  2022. }
  2023. int64_t String::to_int(const wchar_t *p_str, int p_len) {
  2024. int to = 0;
  2025. if (p_len >= 0) {
  2026. to = p_len;
  2027. } else {
  2028. while (p_str[to] != 0 && p_str[to] != '.') {
  2029. to++;
  2030. }
  2031. }
  2032. int64_t integer = 0;
  2033. int64_t sign = 1;
  2034. for (int i = 0; i < to; i++) {
  2035. wchar_t c = p_str[i];
  2036. if (is_digit(c)) {
  2037. bool overflow = (integer > INT64_MAX / 10) || (integer == INT64_MAX / 10 && ((sign == 1 && c > '7') || (sign == -1 && c > '8')));
  2038. ERR_FAIL_COND_V_MSG(overflow, sign == 1 ? INT64_MAX : INT64_MIN, "Cannot represent " + String(p_str).substr(0, to) + " as a 64-bit signed integer, since the value is " + (sign == 1 ? "too large." : "too small."));
  2039. integer *= 10;
  2040. integer += c - '0';
  2041. } else if (c == '-' && integer == 0) {
  2042. sign = -sign;
  2043. } else if (c != ' ') {
  2044. break;
  2045. }
  2046. }
  2047. return integer * sign;
  2048. }
  2049. bool String::is_numeric() const {
  2050. if (length() == 0) {
  2051. return false;
  2052. }
  2053. int s = 0;
  2054. if (operator[](0) == '-') {
  2055. ++s;
  2056. }
  2057. bool dot = false;
  2058. for (int i = s; i < length(); i++) {
  2059. char32_t c = operator[](i);
  2060. if (c == '.') {
  2061. if (dot) {
  2062. return false;
  2063. }
  2064. dot = true;
  2065. } else if (!is_digit(c)) {
  2066. return false;
  2067. }
  2068. }
  2069. return true; // TODO: Use the parser below for this instead
  2070. }
  2071. template <class C>
  2072. static double built_in_strtod(
  2073. /* A decimal ASCII floating-point number,
  2074. * optionally preceded by white space. Must
  2075. * have form "-I.FE-X", where I is the integer
  2076. * part of the mantissa, F is the fractional
  2077. * part of the mantissa, and X is the
  2078. * exponent. Either of the signs may be "+",
  2079. * "-", or omitted. Either I or F may be
  2080. * omitted, or both. The decimal point isn't
  2081. * necessary unless F is present. The "E" may
  2082. * actually be an "e". E and X may both be
  2083. * omitted (but not just one). */
  2084. const C *string,
  2085. /* If non-nullptr, store terminating Cacter's
  2086. * address here. */
  2087. C **endPtr = nullptr) {
  2088. /* Largest possible base 10 exponent. Any
  2089. * exponent larger than this will already
  2090. * produce underflow or overflow, so there's
  2091. * no need to worry about additional digits. */
  2092. static const int maxExponent = 511;
  2093. /* Table giving binary powers of 10. Entry
  2094. * is 10^2^i. Used to convert decimal
  2095. * exponents into floating-point numbers. */
  2096. static const double powersOf10[] = {
  2097. 10.,
  2098. 100.,
  2099. 1.0e4,
  2100. 1.0e8,
  2101. 1.0e16,
  2102. 1.0e32,
  2103. 1.0e64,
  2104. 1.0e128,
  2105. 1.0e256
  2106. };
  2107. bool sign, expSign = false;
  2108. double fraction, dblExp;
  2109. const double *d;
  2110. const C *p;
  2111. int c;
  2112. /* Exponent read from "EX" field. */
  2113. int exp = 0;
  2114. /* Exponent that derives from the fractional
  2115. * part. Under normal circumstances, it is
  2116. * the negative of the number of digits in F.
  2117. * However, if I is very long, the last digits
  2118. * of I get dropped (otherwise a long I with a
  2119. * large negative exponent could cause an
  2120. * unnecessary overflow on I alone). In this
  2121. * case, fracExp is incremented one for each
  2122. * dropped digit. */
  2123. int fracExp = 0;
  2124. /* Number of digits in mantissa. */
  2125. int mantSize;
  2126. /* Number of mantissa digits BEFORE decimal point. */
  2127. int decPt;
  2128. /* Temporarily holds location of exponent in string. */
  2129. const C *pExp;
  2130. /*
  2131. * Strip off leading blanks and check for a sign.
  2132. */
  2133. p = string;
  2134. while (*p == ' ' || *p == '\t' || *p == '\n') {
  2135. p += 1;
  2136. }
  2137. if (*p == '-') {
  2138. sign = true;
  2139. p += 1;
  2140. } else {
  2141. if (*p == '+') {
  2142. p += 1;
  2143. }
  2144. sign = false;
  2145. }
  2146. /*
  2147. * Count the number of digits in the mantissa (including the decimal
  2148. * point), and also locate the decimal point.
  2149. */
  2150. decPt = -1;
  2151. for (mantSize = 0;; mantSize += 1) {
  2152. c = *p;
  2153. if (!is_digit(c)) {
  2154. if ((c != '.') || (decPt >= 0)) {
  2155. break;
  2156. }
  2157. decPt = mantSize;
  2158. }
  2159. p += 1;
  2160. }
  2161. /*
  2162. * Now suck up the digits in the mantissa. Use two integers to collect 9
  2163. * digits each (this is faster than using floating-point). If the mantissa
  2164. * has more than 18 digits, ignore the extras, since they can't affect the
  2165. * value anyway.
  2166. */
  2167. pExp = p;
  2168. p -= mantSize;
  2169. if (decPt < 0) {
  2170. decPt = mantSize;
  2171. } else {
  2172. mantSize -= 1; /* One of the digits was the point. */
  2173. }
  2174. if (mantSize > 18) {
  2175. fracExp = decPt - 18;
  2176. mantSize = 18;
  2177. } else {
  2178. fracExp = decPt - mantSize;
  2179. }
  2180. if (mantSize == 0) {
  2181. fraction = 0.0;
  2182. p = string;
  2183. goto done;
  2184. } else {
  2185. int frac1, frac2;
  2186. frac1 = 0;
  2187. for (; mantSize > 9; mantSize -= 1) {
  2188. c = *p;
  2189. p += 1;
  2190. if (c == '.') {
  2191. c = *p;
  2192. p += 1;
  2193. }
  2194. frac1 = 10 * frac1 + (c - '0');
  2195. }
  2196. frac2 = 0;
  2197. for (; mantSize > 0; mantSize -= 1) {
  2198. c = *p;
  2199. p += 1;
  2200. if (c == '.') {
  2201. c = *p;
  2202. p += 1;
  2203. }
  2204. frac2 = 10 * frac2 + (c - '0');
  2205. }
  2206. fraction = (1.0e9 * frac1) + frac2;
  2207. }
  2208. /*
  2209. * Skim off the exponent.
  2210. */
  2211. p = pExp;
  2212. if ((*p == 'E') || (*p == 'e')) {
  2213. p += 1;
  2214. if (*p == '-') {
  2215. expSign = true;
  2216. p += 1;
  2217. } else {
  2218. if (*p == '+') {
  2219. p += 1;
  2220. }
  2221. expSign = false;
  2222. }
  2223. if (!is_digit(char32_t(*p))) {
  2224. p = pExp;
  2225. goto done;
  2226. }
  2227. while (is_digit(char32_t(*p))) {
  2228. exp = exp * 10 + (*p - '0');
  2229. p += 1;
  2230. }
  2231. }
  2232. if (expSign) {
  2233. exp = fracExp - exp;
  2234. } else {
  2235. exp = fracExp + exp;
  2236. }
  2237. /*
  2238. * Generate a floating-point number that represents the exponent. Do this
  2239. * by processing the exponent one bit at a time to combine many powers of
  2240. * 2 of 10. Then combine the exponent with the fraction.
  2241. */
  2242. if (exp < 0) {
  2243. expSign = true;
  2244. exp = -exp;
  2245. } else {
  2246. expSign = false;
  2247. }
  2248. if (exp > maxExponent) {
  2249. exp = maxExponent;
  2250. WARN_PRINT("Exponent too high");
  2251. }
  2252. dblExp = 1.0;
  2253. for (d = powersOf10; exp != 0; exp >>= 1, ++d) {
  2254. if (exp & 01) {
  2255. dblExp *= *d;
  2256. }
  2257. }
  2258. if (expSign) {
  2259. fraction /= dblExp;
  2260. } else {
  2261. fraction *= dblExp;
  2262. }
  2263. done:
  2264. if (endPtr != nullptr) {
  2265. *endPtr = (C *)p;
  2266. }
  2267. if (sign) {
  2268. return -fraction;
  2269. }
  2270. return fraction;
  2271. }
  2272. #define READING_SIGN 0
  2273. #define READING_INT 1
  2274. #define READING_DEC 2
  2275. #define READING_EXP 3
  2276. #define READING_DONE 4
  2277. double String::to_float(const char *p_str) {
  2278. return built_in_strtod<char>(p_str);
  2279. }
  2280. double String::to_float(const char32_t *p_str, const char32_t **r_end) {
  2281. return built_in_strtod<char32_t>(p_str, (char32_t **)r_end);
  2282. }
  2283. double String::to_float(const wchar_t *p_str, const wchar_t **r_end) {
  2284. return built_in_strtod<wchar_t>(p_str, (wchar_t **)r_end);
  2285. }
  2286. uint32_t String::num_characters(int64_t p_int) {
  2287. int r = 1;
  2288. if (p_int < 0) {
  2289. r += 1;
  2290. if (p_int == INT64_MIN) {
  2291. p_int = INT64_MAX;
  2292. } else {
  2293. p_int = -p_int;
  2294. }
  2295. }
  2296. while (p_int >= 10) {
  2297. p_int /= 10;
  2298. r++;
  2299. }
  2300. return r;
  2301. }
  2302. int64_t String::to_int(const char32_t *p_str, int p_len, bool p_clamp) {
  2303. if (p_len == 0 || !p_str[0]) {
  2304. return 0;
  2305. }
  2306. ///@todo make more exact so saving and loading does not lose precision
  2307. int64_t integer = 0;
  2308. int64_t sign = 1;
  2309. int reading = READING_SIGN;
  2310. const char32_t *str = p_str;
  2311. const char32_t *limit = &p_str[p_len];
  2312. while (*str && reading != READING_DONE && str != limit) {
  2313. char32_t c = *(str++);
  2314. switch (reading) {
  2315. case READING_SIGN: {
  2316. if (is_digit(c)) {
  2317. reading = READING_INT;
  2318. // let it fallthrough
  2319. } else if (c == '-') {
  2320. sign = -1;
  2321. reading = READING_INT;
  2322. break;
  2323. } else if (c == '+') {
  2324. sign = 1;
  2325. reading = READING_INT;
  2326. break;
  2327. } else {
  2328. break;
  2329. }
  2330. [[fallthrough]];
  2331. }
  2332. case READING_INT: {
  2333. if (is_digit(c)) {
  2334. if (integer > INT64_MAX / 10) {
  2335. String number("");
  2336. str = p_str;
  2337. while (*str && str != limit) {
  2338. number += *(str++);
  2339. }
  2340. if (p_clamp) {
  2341. if (sign == 1) {
  2342. return INT64_MAX;
  2343. } else {
  2344. return INT64_MIN;
  2345. }
  2346. } else {
  2347. ERR_FAIL_V_MSG(sign == 1 ? INT64_MAX : INT64_MIN, "Cannot represent " + number + " as a 64-bit signed integer, since the value is " + (sign == 1 ? "too large." : "too small."));
  2348. }
  2349. }
  2350. integer *= 10;
  2351. integer += c - '0';
  2352. } else {
  2353. reading = READING_DONE;
  2354. }
  2355. } break;
  2356. }
  2357. }
  2358. return sign * integer;
  2359. }
  2360. double String::to_float() const {
  2361. if (is_empty()) {
  2362. return 0;
  2363. }
  2364. return built_in_strtod<char32_t>(get_data());
  2365. }
  2366. uint32_t String::hash(const char *p_cstr) {
  2367. // static_cast: avoid negative values on platforms where char is signed.
  2368. uint32_t hashv = 5381;
  2369. uint32_t c = static_cast<uint8_t>(*p_cstr++);
  2370. while (c) {
  2371. hashv = ((hashv << 5) + hashv) + c; /* hash * 33 + c */
  2372. c = static_cast<uint8_t>(*p_cstr++);
  2373. }
  2374. return hashv;
  2375. }
  2376. uint32_t String::hash(const char *p_cstr, int p_len) {
  2377. uint32_t hashv = 5381;
  2378. for (int i = 0; i < p_len; i++) {
  2379. // static_cast: avoid negative values on platforms where char is signed.
  2380. hashv = ((hashv << 5) + hashv) + static_cast<uint8_t>(p_cstr[i]); /* hash * 33 + c */
  2381. }
  2382. return hashv;
  2383. }
  2384. uint32_t String::hash(const wchar_t *p_cstr, int p_len) {
  2385. // Avoid negative values on platforms where wchar_t is signed. Account for different sizes.
  2386. using wide_unsigned = std::conditional<sizeof(wchar_t) == 2, uint16_t, uint32_t>::type;
  2387. uint32_t hashv = 5381;
  2388. for (int i = 0; i < p_len; i++) {
  2389. hashv = ((hashv << 5) + hashv) + static_cast<wide_unsigned>(p_cstr[i]); /* hash * 33 + c */
  2390. }
  2391. return hashv;
  2392. }
  2393. uint32_t String::hash(const wchar_t *p_cstr) {
  2394. // Avoid negative values on platforms where wchar_t is signed. Account for different sizes.
  2395. using wide_unsigned = std::conditional<sizeof(wchar_t) == 2, uint16_t, uint32_t>::type;
  2396. uint32_t hashv = 5381;
  2397. uint32_t c = static_cast<wide_unsigned>(*p_cstr++);
  2398. while (c) {
  2399. hashv = ((hashv << 5) + hashv) + c; /* hash * 33 + c */
  2400. c = static_cast<wide_unsigned>(*p_cstr++);
  2401. }
  2402. return hashv;
  2403. }
  2404. uint32_t String::hash(const char32_t *p_cstr, int p_len) {
  2405. uint32_t hashv = 5381;
  2406. for (int i = 0; i < p_len; i++) {
  2407. hashv = ((hashv << 5) + hashv) + p_cstr[i]; /* hash * 33 + c */
  2408. }
  2409. return hashv;
  2410. }
  2411. uint32_t String::hash(const char32_t *p_cstr) {
  2412. uint32_t hashv = 5381;
  2413. uint32_t c = *p_cstr++;
  2414. while (c) {
  2415. hashv = ((hashv << 5) + hashv) + c; /* hash * 33 + c */
  2416. c = *p_cstr++;
  2417. }
  2418. return hashv;
  2419. }
  2420. uint32_t String::hash() const {
  2421. /* simple djb2 hashing */
  2422. const char32_t *chr = get_data();
  2423. uint32_t hashv = 5381;
  2424. uint32_t c = *chr++;
  2425. while (c) {
  2426. hashv = ((hashv << 5) + hashv) + c; /* hash * 33 + c */
  2427. c = *chr++;
  2428. }
  2429. return hashv;
  2430. }
  2431. uint64_t String::hash64() const {
  2432. /* simple djb2 hashing */
  2433. const char32_t *chr = get_data();
  2434. uint64_t hashv = 5381;
  2435. uint64_t c = *chr++;
  2436. while (c) {
  2437. hashv = ((hashv << 5) + hashv) + c; /* hash * 33 + c */
  2438. c = *chr++;
  2439. }
  2440. return hashv;
  2441. }
  2442. String String::md5_text() const {
  2443. CharString cs = utf8();
  2444. unsigned char hash[16];
  2445. CryptoCore::md5((unsigned char *)cs.ptr(), cs.length(), hash);
  2446. return String::hex_encode_buffer(hash, 16);
  2447. }
  2448. String String::sha1_text() const {
  2449. CharString cs = utf8();
  2450. unsigned char hash[20];
  2451. CryptoCore::sha1((unsigned char *)cs.ptr(), cs.length(), hash);
  2452. return String::hex_encode_buffer(hash, 20);
  2453. }
  2454. String String::sha256_text() const {
  2455. CharString cs = utf8();
  2456. unsigned char hash[32];
  2457. CryptoCore::sha256((unsigned char *)cs.ptr(), cs.length(), hash);
  2458. return String::hex_encode_buffer(hash, 32);
  2459. }
  2460. Vector<uint8_t> String::md5_buffer() const {
  2461. CharString cs = utf8();
  2462. unsigned char hash[16];
  2463. CryptoCore::md5((unsigned char *)cs.ptr(), cs.length(), hash);
  2464. Vector<uint8_t> ret;
  2465. ret.resize(16);
  2466. for (int i = 0; i < 16; i++) {
  2467. ret.write[i] = hash[i];
  2468. }
  2469. return ret;
  2470. }
  2471. Vector<uint8_t> String::sha1_buffer() const {
  2472. CharString cs = utf8();
  2473. unsigned char hash[20];
  2474. CryptoCore::sha1((unsigned char *)cs.ptr(), cs.length(), hash);
  2475. Vector<uint8_t> ret;
  2476. ret.resize(20);
  2477. for (int i = 0; i < 20; i++) {
  2478. ret.write[i] = hash[i];
  2479. }
  2480. return ret;
  2481. }
  2482. Vector<uint8_t> String::sha256_buffer() const {
  2483. CharString cs = utf8();
  2484. unsigned char hash[32];
  2485. CryptoCore::sha256((unsigned char *)cs.ptr(), cs.length(), hash);
  2486. Vector<uint8_t> ret;
  2487. ret.resize(32);
  2488. for (int i = 0; i < 32; i++) {
  2489. ret.write[i] = hash[i];
  2490. }
  2491. return ret;
  2492. }
  2493. String String::insert(int p_at_pos, const String &p_string) const {
  2494. if (p_at_pos < 0) {
  2495. return *this;
  2496. }
  2497. if (p_at_pos > length()) {
  2498. p_at_pos = length();
  2499. }
  2500. String pre;
  2501. if (p_at_pos > 0) {
  2502. pre = substr(0, p_at_pos);
  2503. }
  2504. String post;
  2505. if (p_at_pos < length()) {
  2506. post = substr(p_at_pos, length() - p_at_pos);
  2507. }
  2508. return pre + p_string + post;
  2509. }
  2510. String String::erase(int p_pos, int p_chars) const {
  2511. ERR_FAIL_COND_V_MSG(p_pos < 0, "", vformat("Invalid starting position for `String.erase()`: %d. Starting position must be positive or zero.", p_pos));
  2512. ERR_FAIL_COND_V_MSG(p_chars < 0, "", vformat("Invalid character count for `String.erase()`: %d. Character count must be positive or zero.", p_chars));
  2513. return left(p_pos) + substr(p_pos + p_chars);
  2514. }
  2515. String String::substr(int p_from, int p_chars) const {
  2516. if (p_chars == -1) {
  2517. p_chars = length() - p_from;
  2518. }
  2519. if (is_empty() || p_from < 0 || p_from >= length() || p_chars <= 0) {
  2520. return "";
  2521. }
  2522. if ((p_from + p_chars) > length()) {
  2523. p_chars = length() - p_from;
  2524. }
  2525. if (p_from == 0 && p_chars >= length()) {
  2526. return String(*this);
  2527. }
  2528. String s;
  2529. s.copy_from_unchecked(&get_data()[p_from], p_chars);
  2530. return s;
  2531. }
  2532. int String::find(const String &p_str, int p_from) const {
  2533. if (p_from < 0) {
  2534. return -1;
  2535. }
  2536. const int src_len = p_str.length();
  2537. const int len = length();
  2538. if (src_len == 0 || len == 0) {
  2539. return -1; // won't find anything!
  2540. }
  2541. const char32_t *src = get_data();
  2542. const char32_t *str = p_str.get_data();
  2543. for (int i = p_from; i <= (len - src_len); i++) {
  2544. bool found = true;
  2545. for (int j = 0; j < src_len; j++) {
  2546. int read_pos = i + j;
  2547. if (read_pos >= len) {
  2548. ERR_PRINT("read_pos>=len");
  2549. return -1;
  2550. }
  2551. if (src[read_pos] != str[j]) {
  2552. found = false;
  2553. break;
  2554. }
  2555. }
  2556. if (found) {
  2557. return i;
  2558. }
  2559. }
  2560. return -1;
  2561. }
  2562. int String::find(const char *p_str, int p_from) const {
  2563. if (p_from < 0) {
  2564. return -1;
  2565. }
  2566. const int len = length();
  2567. if (len == 0) {
  2568. return -1; // won't find anything!
  2569. }
  2570. const char32_t *src = get_data();
  2571. int src_len = 0;
  2572. while (p_str[src_len] != '\0') {
  2573. src_len++;
  2574. }
  2575. if (src_len == 1) {
  2576. const char32_t needle = p_str[0];
  2577. for (int i = p_from; i < len; i++) {
  2578. if (src[i] == needle) {
  2579. return i;
  2580. }
  2581. }
  2582. } else {
  2583. for (int i = p_from; i <= (len - src_len); i++) {
  2584. bool found = true;
  2585. for (int j = 0; j < src_len; j++) {
  2586. int read_pos = i + j;
  2587. if (read_pos >= len) {
  2588. ERR_PRINT("read_pos>=len");
  2589. return -1;
  2590. }
  2591. if (src[read_pos] != (char32_t)p_str[j]) {
  2592. found = false;
  2593. break;
  2594. }
  2595. }
  2596. if (found) {
  2597. return i;
  2598. }
  2599. }
  2600. }
  2601. return -1;
  2602. }
  2603. int String::find_char(const char32_t &p_char, int p_from) const {
  2604. return _cowdata.find(p_char, p_from);
  2605. }
  2606. int String::findmk(const Vector<String> &p_keys, int p_from, int *r_key) const {
  2607. if (p_from < 0) {
  2608. return -1;
  2609. }
  2610. if (p_keys.size() == 0) {
  2611. return -1;
  2612. }
  2613. //int src_len=p_str.length();
  2614. const String *keys = &p_keys[0];
  2615. int key_count = p_keys.size();
  2616. int len = length();
  2617. if (len == 0) {
  2618. return -1; // won't find anything!
  2619. }
  2620. const char32_t *src = get_data();
  2621. for (int i = p_from; i < len; i++) {
  2622. bool found = true;
  2623. for (int k = 0; k < key_count; k++) {
  2624. found = true;
  2625. if (r_key) {
  2626. *r_key = k;
  2627. }
  2628. const char32_t *cmp = keys[k].get_data();
  2629. int l = keys[k].length();
  2630. for (int j = 0; j < l; j++) {
  2631. int read_pos = i + j;
  2632. if (read_pos >= len) {
  2633. found = false;
  2634. break;
  2635. }
  2636. if (src[read_pos] != cmp[j]) {
  2637. found = false;
  2638. break;
  2639. }
  2640. }
  2641. if (found) {
  2642. break;
  2643. }
  2644. }
  2645. if (found) {
  2646. return i;
  2647. }
  2648. }
  2649. return -1;
  2650. }
  2651. int String::findn(const String &p_str, int p_from) const {
  2652. if (p_from < 0) {
  2653. return -1;
  2654. }
  2655. int src_len = p_str.length();
  2656. if (src_len == 0 || length() == 0) {
  2657. return -1; // won't find anything!
  2658. }
  2659. const char32_t *srcd = get_data();
  2660. for (int i = p_from; i <= (length() - src_len); i++) {
  2661. bool found = true;
  2662. for (int j = 0; j < src_len; j++) {
  2663. int read_pos = i + j;
  2664. if (read_pos >= length()) {
  2665. ERR_PRINT("read_pos>=length()");
  2666. return -1;
  2667. }
  2668. char32_t src = _find_lower(srcd[read_pos]);
  2669. char32_t dst = _find_lower(p_str[j]);
  2670. if (src != dst) {
  2671. found = false;
  2672. break;
  2673. }
  2674. }
  2675. if (found) {
  2676. return i;
  2677. }
  2678. }
  2679. return -1;
  2680. }
  2681. int String::rfind(const String &p_str, int p_from) const {
  2682. // establish a limit
  2683. int limit = length() - p_str.length();
  2684. if (limit < 0) {
  2685. return -1;
  2686. }
  2687. // establish a starting point
  2688. if (p_from < 0) {
  2689. p_from = limit;
  2690. } else if (p_from > limit) {
  2691. p_from = limit;
  2692. }
  2693. int src_len = p_str.length();
  2694. int len = length();
  2695. if (src_len == 0 || len == 0) {
  2696. return -1; // won't find anything!
  2697. }
  2698. const char32_t *src = get_data();
  2699. for (int i = p_from; i >= 0; i--) {
  2700. bool found = true;
  2701. for (int j = 0; j < src_len; j++) {
  2702. int read_pos = i + j;
  2703. if (read_pos >= len) {
  2704. ERR_PRINT("read_pos>=len");
  2705. return -1;
  2706. }
  2707. if (src[read_pos] != p_str[j]) {
  2708. found = false;
  2709. break;
  2710. }
  2711. }
  2712. if (found) {
  2713. return i;
  2714. }
  2715. }
  2716. return -1;
  2717. }
  2718. int String::rfindn(const String &p_str, int p_from) const {
  2719. // establish a limit
  2720. int limit = length() - p_str.length();
  2721. if (limit < 0) {
  2722. return -1;
  2723. }
  2724. // establish a starting point
  2725. if (p_from < 0) {
  2726. p_from = limit;
  2727. } else if (p_from > limit) {
  2728. p_from = limit;
  2729. }
  2730. int src_len = p_str.length();
  2731. int len = length();
  2732. if (src_len == 0 || len == 0) {
  2733. return -1; // won't find anything!
  2734. }
  2735. const char32_t *src = get_data();
  2736. for (int i = p_from; i >= 0; i--) {
  2737. bool found = true;
  2738. for (int j = 0; j < src_len; j++) {
  2739. int read_pos = i + j;
  2740. if (read_pos >= len) {
  2741. ERR_PRINT("read_pos>=len");
  2742. return -1;
  2743. }
  2744. char32_t srcc = _find_lower(src[read_pos]);
  2745. char32_t dstc = _find_lower(p_str[j]);
  2746. if (srcc != dstc) {
  2747. found = false;
  2748. break;
  2749. }
  2750. }
  2751. if (found) {
  2752. return i;
  2753. }
  2754. }
  2755. return -1;
  2756. }
  2757. bool String::ends_with(const String &p_string) const {
  2758. int l = p_string.length();
  2759. if (l > length()) {
  2760. return false;
  2761. }
  2762. if (l == 0) {
  2763. return true;
  2764. }
  2765. const char32_t *p = &p_string[0];
  2766. const char32_t *s = &operator[](length() - l);
  2767. for (int i = 0; i < l; i++) {
  2768. if (p[i] != s[i]) {
  2769. return false;
  2770. }
  2771. }
  2772. return true;
  2773. }
  2774. bool String::begins_with(const String &p_string) const {
  2775. int l = p_string.length();
  2776. if (l > length()) {
  2777. return false;
  2778. }
  2779. if (l == 0) {
  2780. return true;
  2781. }
  2782. const char32_t *p = &p_string[0];
  2783. const char32_t *s = &operator[](0);
  2784. for (int i = 0; i < l; i++) {
  2785. if (p[i] != s[i]) {
  2786. return false;
  2787. }
  2788. }
  2789. return true;
  2790. }
  2791. bool String::begins_with(const char *p_string) const {
  2792. int l = length();
  2793. if (!p_string) {
  2794. return false;
  2795. }
  2796. if (l == 0) {
  2797. return *p_string == 0;
  2798. }
  2799. const char32_t *str = &operator[](0);
  2800. int i = 0;
  2801. while (*p_string && i < l) {
  2802. if ((char32_t)*p_string != str[i]) {
  2803. return false;
  2804. }
  2805. i++;
  2806. p_string++;
  2807. }
  2808. return *p_string == 0;
  2809. }
  2810. bool String::is_enclosed_in(const String &p_string) const {
  2811. return begins_with(p_string) && ends_with(p_string);
  2812. }
  2813. bool String::is_subsequence_of(const String &p_string) const {
  2814. return _base_is_subsequence_of(p_string, false);
  2815. }
  2816. bool String::is_subsequence_ofn(const String &p_string) const {
  2817. return _base_is_subsequence_of(p_string, true);
  2818. }
  2819. bool String::is_quoted() const {
  2820. return is_enclosed_in("\"") || is_enclosed_in("'");
  2821. }
  2822. int String::_count(const String &p_string, int p_from, int p_to, bool p_case_insensitive) const {
  2823. if (p_string.is_empty()) {
  2824. return 0;
  2825. }
  2826. int len = length();
  2827. int slen = p_string.length();
  2828. if (len < slen) {
  2829. return 0;
  2830. }
  2831. String str;
  2832. if (p_from >= 0 && p_to >= 0) {
  2833. if (p_to == 0) {
  2834. p_to = len;
  2835. } else if (p_from >= p_to) {
  2836. return 0;
  2837. }
  2838. if (p_from == 0 && p_to == len) {
  2839. str = String();
  2840. str.copy_from_unchecked(&get_data()[0], len);
  2841. } else {
  2842. str = substr(p_from, p_to - p_from);
  2843. }
  2844. } else {
  2845. return 0;
  2846. }
  2847. int c = 0;
  2848. int idx = -1;
  2849. do {
  2850. idx = p_case_insensitive ? str.findn(p_string) : str.find(p_string);
  2851. if (idx != -1) {
  2852. str = str.substr(idx + slen, str.length() - slen);
  2853. ++c;
  2854. }
  2855. } while (idx != -1);
  2856. return c;
  2857. }
  2858. int String::count(const String &p_string, int p_from, int p_to) const {
  2859. return _count(p_string, p_from, p_to, false);
  2860. }
  2861. int String::countn(const String &p_string, int p_from, int p_to) const {
  2862. return _count(p_string, p_from, p_to, true);
  2863. }
  2864. bool String::_base_is_subsequence_of(const String &p_string, bool case_insensitive) const {
  2865. int len = length();
  2866. if (len == 0) {
  2867. // Technically an empty string is subsequence of any string
  2868. return true;
  2869. }
  2870. if (len > p_string.length()) {
  2871. return false;
  2872. }
  2873. const char32_t *src = &operator[](0);
  2874. const char32_t *tgt = &p_string[0];
  2875. for (; *src && *tgt; tgt++) {
  2876. bool match = false;
  2877. if (case_insensitive) {
  2878. char32_t srcc = _find_lower(*src);
  2879. char32_t tgtc = _find_lower(*tgt);
  2880. match = srcc == tgtc;
  2881. } else {
  2882. match = *src == *tgt;
  2883. }
  2884. if (match) {
  2885. src++;
  2886. if (!*src) {
  2887. return true;
  2888. }
  2889. }
  2890. }
  2891. return false;
  2892. }
  2893. Vector<String> String::bigrams() const {
  2894. int n_pairs = length() - 1;
  2895. Vector<String> b;
  2896. if (n_pairs <= 0) {
  2897. return b;
  2898. }
  2899. b.resize(n_pairs);
  2900. for (int i = 0; i < n_pairs; i++) {
  2901. b.write[i] = substr(i, 2);
  2902. }
  2903. return b;
  2904. }
  2905. // Similarity according to Sorensen-Dice coefficient
  2906. float String::similarity(const String &p_string) const {
  2907. if (operator==(p_string)) {
  2908. // Equal strings are totally similar
  2909. return 1.0f;
  2910. }
  2911. if (length() < 2 || p_string.length() < 2) {
  2912. // No way to calculate similarity without a single bigram
  2913. return 0.0f;
  2914. }
  2915. Vector<String> src_bigrams = bigrams();
  2916. Vector<String> tgt_bigrams = p_string.bigrams();
  2917. int src_size = src_bigrams.size();
  2918. int tgt_size = tgt_bigrams.size();
  2919. int sum = src_size + tgt_size;
  2920. int inter = 0;
  2921. for (int i = 0; i < src_size; i++) {
  2922. for (int j = 0; j < tgt_size; j++) {
  2923. if (src_bigrams[i] == tgt_bigrams[j]) {
  2924. inter++;
  2925. break;
  2926. }
  2927. }
  2928. }
  2929. return (2.0f * inter) / sum;
  2930. }
  2931. static bool _wildcard_match(const char32_t *p_pattern, const char32_t *p_string, bool p_case_sensitive) {
  2932. switch (*p_pattern) {
  2933. case '\0':
  2934. return !*p_string;
  2935. case '*':
  2936. return _wildcard_match(p_pattern + 1, p_string, p_case_sensitive) || (*p_string && _wildcard_match(p_pattern, p_string + 1, p_case_sensitive));
  2937. case '?':
  2938. return *p_string && (*p_string != '.') && _wildcard_match(p_pattern + 1, p_string + 1, p_case_sensitive);
  2939. default:
  2940. return (p_case_sensitive ? (*p_string == *p_pattern) : (_find_upper(*p_string) == _find_upper(*p_pattern))) && _wildcard_match(p_pattern + 1, p_string + 1, p_case_sensitive);
  2941. }
  2942. }
  2943. bool String::match(const String &p_wildcard) const {
  2944. if (!p_wildcard.length() || !length()) {
  2945. return false;
  2946. }
  2947. return _wildcard_match(p_wildcard.get_data(), get_data(), true);
  2948. }
  2949. bool String::matchn(const String &p_wildcard) const {
  2950. if (!p_wildcard.length() || !length()) {
  2951. return false;
  2952. }
  2953. return _wildcard_match(p_wildcard.get_data(), get_data(), false);
  2954. }
  2955. String String::format(const Variant &values, String placeholder) const {
  2956. String new_string = String(this->ptr());
  2957. if (values.get_type() == Variant::ARRAY) {
  2958. Array values_arr = values;
  2959. for (int i = 0; i < values_arr.size(); i++) {
  2960. String i_as_str = String::num_int64(i);
  2961. if (values_arr[i].get_type() == Variant::ARRAY) { //Array in Array structure [["name","RobotGuy"],[0,"godot"],["strength",9000.91]]
  2962. Array value_arr = values_arr[i];
  2963. if (value_arr.size() == 2) {
  2964. Variant v_key = value_arr[0];
  2965. String key = v_key;
  2966. Variant v_val = value_arr[1];
  2967. String val = v_val;
  2968. new_string = new_string.replace(placeholder.replace("_", key), val);
  2969. } else {
  2970. ERR_PRINT(String("STRING.format Inner Array size != 2 ").ascii().get_data());
  2971. }
  2972. } else { //Array structure ["RobotGuy","Logis","rookie"]
  2973. Variant v_val = values_arr[i];
  2974. String val = v_val;
  2975. if (placeholder.find("_") > -1) {
  2976. new_string = new_string.replace(placeholder.replace("_", i_as_str), val);
  2977. } else {
  2978. new_string = new_string.replace_first(placeholder, val);
  2979. }
  2980. }
  2981. }
  2982. } else if (values.get_type() == Variant::DICTIONARY) {
  2983. Dictionary d = values;
  2984. List<Variant> keys;
  2985. d.get_key_list(&keys);
  2986. for (const Variant &key : keys) {
  2987. new_string = new_string.replace(placeholder.replace("_", key), d[key]);
  2988. }
  2989. } else {
  2990. ERR_PRINT(String("Invalid type: use Array or Dictionary.").ascii().get_data());
  2991. }
  2992. return new_string;
  2993. }
  2994. String String::replace(const String &p_key, const String &p_with) const {
  2995. String new_string;
  2996. int search_from = 0;
  2997. int result = 0;
  2998. while ((result = find(p_key, search_from)) >= 0) {
  2999. new_string += substr(search_from, result - search_from);
  3000. new_string += p_with;
  3001. search_from = result + p_key.length();
  3002. }
  3003. if (search_from == 0) {
  3004. return *this;
  3005. }
  3006. new_string += substr(search_from, length() - search_from);
  3007. return new_string;
  3008. }
  3009. String String::replace(const char *p_key, const char *p_with) const {
  3010. String new_string;
  3011. int search_from = 0;
  3012. int result = 0;
  3013. while ((result = find(p_key, search_from)) >= 0) {
  3014. new_string += substr(search_from, result - search_from);
  3015. new_string += p_with;
  3016. int k = 0;
  3017. while (p_key[k] != '\0') {
  3018. k++;
  3019. }
  3020. search_from = result + k;
  3021. }
  3022. if (search_from == 0) {
  3023. return *this;
  3024. }
  3025. new_string += substr(search_from, length() - search_from);
  3026. return new_string;
  3027. }
  3028. String String::replace_first(const String &p_key, const String &p_with) const {
  3029. int pos = find(p_key);
  3030. if (pos >= 0) {
  3031. return substr(0, pos) + p_with + substr(pos + p_key.length(), length());
  3032. }
  3033. return *this;
  3034. }
  3035. String String::replacen(const String &p_key, const String &p_with) const {
  3036. String new_string;
  3037. int search_from = 0;
  3038. int result = 0;
  3039. while ((result = findn(p_key, search_from)) >= 0) {
  3040. new_string += substr(search_from, result - search_from);
  3041. new_string += p_with;
  3042. search_from = result + p_key.length();
  3043. }
  3044. if (search_from == 0) {
  3045. return *this;
  3046. }
  3047. new_string += substr(search_from, length() - search_from);
  3048. return new_string;
  3049. }
  3050. String String::repeat(int p_count) const {
  3051. ERR_FAIL_COND_V_MSG(p_count < 0, "", "Parameter count should be a positive number.");
  3052. if (p_count == 0) {
  3053. return "";
  3054. }
  3055. if (p_count == 1) {
  3056. return *this;
  3057. }
  3058. int len = length();
  3059. String new_string = *this;
  3060. new_string.resize(p_count * len + 1);
  3061. char32_t *dst = new_string.ptrw();
  3062. int offset = 1;
  3063. int stride = 1;
  3064. while (offset < p_count) {
  3065. memcpy(dst + offset * len, dst, stride * len * sizeof(char32_t));
  3066. offset += stride;
  3067. stride = MIN(stride * 2, p_count - offset);
  3068. }
  3069. dst[p_count * len] = _null;
  3070. return new_string;
  3071. }
  3072. String String::reverse() const {
  3073. int len = length();
  3074. if (len <= 1) {
  3075. return *this;
  3076. }
  3077. String new_string;
  3078. new_string.resize(len + 1);
  3079. const char32_t *src = ptr();
  3080. char32_t *dst = new_string.ptrw();
  3081. for (int i = 0; i < len; i++) {
  3082. dst[i] = src[len - i - 1];
  3083. }
  3084. dst[len] = _null;
  3085. return new_string;
  3086. }
  3087. String String::left(int p_len) const {
  3088. if (p_len < 0) {
  3089. p_len = length() + p_len;
  3090. }
  3091. if (p_len <= 0) {
  3092. return "";
  3093. }
  3094. if (p_len >= length()) {
  3095. return *this;
  3096. }
  3097. String s;
  3098. s.copy_from_unchecked(&get_data()[0], p_len);
  3099. return s;
  3100. }
  3101. String String::right(int p_len) const {
  3102. if (p_len < 0) {
  3103. p_len = length() + p_len;
  3104. }
  3105. if (p_len <= 0) {
  3106. return "";
  3107. }
  3108. if (p_len >= length()) {
  3109. return *this;
  3110. }
  3111. String s;
  3112. s.copy_from_unchecked(&get_data()[length() - p_len], p_len);
  3113. return s;
  3114. }
  3115. char32_t String::unicode_at(int p_idx) const {
  3116. ERR_FAIL_INDEX_V(p_idx, length(), 0);
  3117. return operator[](p_idx);
  3118. }
  3119. String String::indent(const String &p_prefix) const {
  3120. String new_string;
  3121. int line_start = 0;
  3122. for (int i = 0; i < length(); i++) {
  3123. const char32_t c = operator[](i);
  3124. if (c == '\n') {
  3125. if (i == line_start) {
  3126. new_string += c; // Leave empty lines empty.
  3127. } else {
  3128. new_string += p_prefix + substr(line_start, i - line_start + 1);
  3129. }
  3130. line_start = i + 1;
  3131. }
  3132. }
  3133. if (line_start != length()) {
  3134. new_string += p_prefix + substr(line_start);
  3135. }
  3136. return new_string;
  3137. }
  3138. String String::dedent() const {
  3139. String new_string;
  3140. String indent;
  3141. bool has_indent = false;
  3142. bool has_text = false;
  3143. int line_start = 0;
  3144. int indent_stop = -1;
  3145. for (int i = 0; i < length(); i++) {
  3146. char32_t c = operator[](i);
  3147. if (c == '\n') {
  3148. if (has_text) {
  3149. new_string += substr(indent_stop, i - indent_stop);
  3150. }
  3151. new_string += "\n";
  3152. has_text = false;
  3153. line_start = i + 1;
  3154. indent_stop = -1;
  3155. } else if (!has_text) {
  3156. if (c > 32) {
  3157. has_text = true;
  3158. if (!has_indent) {
  3159. has_indent = true;
  3160. indent = substr(line_start, i - line_start);
  3161. indent_stop = i;
  3162. }
  3163. }
  3164. if (has_indent && indent_stop < 0) {
  3165. int j = i - line_start;
  3166. if (j >= indent.length() || c != indent[j]) {
  3167. indent_stop = i;
  3168. }
  3169. }
  3170. }
  3171. }
  3172. if (has_text) {
  3173. new_string += substr(indent_stop, length() - indent_stop);
  3174. }
  3175. return new_string;
  3176. }
  3177. String String::strip_edges(bool left, bool right) const {
  3178. int len = length();
  3179. int beg = 0, end = len;
  3180. if (left) {
  3181. for (int i = 0; i < len; i++) {
  3182. if (operator[](i) <= 32) {
  3183. beg++;
  3184. } else {
  3185. break;
  3186. }
  3187. }
  3188. }
  3189. if (right) {
  3190. for (int i = len - 1; i >= 0; i--) {
  3191. if (operator[](i) <= 32) {
  3192. end--;
  3193. } else {
  3194. break;
  3195. }
  3196. }
  3197. }
  3198. if (beg == 0 && end == len) {
  3199. return *this;
  3200. }
  3201. return substr(beg, end - beg);
  3202. }
  3203. String String::strip_escapes() const {
  3204. String new_string;
  3205. for (int i = 0; i < length(); i++) {
  3206. // Escape characters on first page of the ASCII table, before 32 (Space).
  3207. if (operator[](i) < 32) {
  3208. continue;
  3209. }
  3210. new_string += operator[](i);
  3211. }
  3212. return new_string;
  3213. }
  3214. String String::lstrip(const String &p_chars) const {
  3215. int len = length();
  3216. int beg;
  3217. for (beg = 0; beg < len; beg++) {
  3218. if (p_chars.find_char(get(beg)) == -1) {
  3219. break;
  3220. }
  3221. }
  3222. if (beg == 0) {
  3223. return *this;
  3224. }
  3225. return substr(beg, len - beg);
  3226. }
  3227. String String::rstrip(const String &p_chars) const {
  3228. int len = length();
  3229. int end;
  3230. for (end = len - 1; end >= 0; end--) {
  3231. if (p_chars.find_char(get(end)) == -1) {
  3232. break;
  3233. }
  3234. }
  3235. if (end == len - 1) {
  3236. return *this;
  3237. }
  3238. return substr(0, end + 1);
  3239. }
  3240. bool String::is_network_share_path() const {
  3241. return begins_with("//") || begins_with("\\\\");
  3242. }
  3243. String String::simplify_path() const {
  3244. String s = *this;
  3245. String drive;
  3246. // Check if we have a special path (like res://) or a protocol identifier.
  3247. int p = s.find("://");
  3248. bool found = false;
  3249. if (p > 0) {
  3250. bool only_chars = true;
  3251. for (int i = 0; i < p; i++) {
  3252. if (!is_ascii_alphanumeric_char(s[i])) {
  3253. only_chars = false;
  3254. break;
  3255. }
  3256. }
  3257. if (only_chars) {
  3258. found = true;
  3259. drive = s.substr(0, p + 3);
  3260. s = s.substr(p + 3);
  3261. }
  3262. }
  3263. if (!found) {
  3264. if (is_network_share_path()) {
  3265. // Network path, beginning with // or \\.
  3266. drive = s.substr(0, 2);
  3267. s = s.substr(2);
  3268. } else if (s.begins_with("/") || s.begins_with("\\")) {
  3269. // Absolute path.
  3270. drive = s.substr(0, 1);
  3271. s = s.substr(1);
  3272. } else {
  3273. // Windows-style drive path, like C:/ or C:\.
  3274. p = s.find(":/");
  3275. if (p == -1) {
  3276. p = s.find(":\\");
  3277. }
  3278. if (p != -1 && p < s.find("/")) {
  3279. drive = s.substr(0, p + 2);
  3280. s = s.substr(p + 2);
  3281. }
  3282. }
  3283. }
  3284. s = s.replace("\\", "/");
  3285. while (true) { // in case of using 2 or more slash
  3286. String compare = s.replace("//", "/");
  3287. if (s == compare) {
  3288. break;
  3289. } else {
  3290. s = compare;
  3291. }
  3292. }
  3293. Vector<String> dirs = s.split("/", false);
  3294. for (int i = 0; i < dirs.size(); i++) {
  3295. String d = dirs[i];
  3296. if (d == ".") {
  3297. dirs.remove_at(i);
  3298. i--;
  3299. } else if (d == "..") {
  3300. if (i == 0) {
  3301. dirs.remove_at(i);
  3302. i--;
  3303. } else {
  3304. dirs.remove_at(i);
  3305. dirs.remove_at(i - 1);
  3306. i -= 2;
  3307. }
  3308. }
  3309. }
  3310. s = "";
  3311. for (int i = 0; i < dirs.size(); i++) {
  3312. if (i > 0) {
  3313. s += "/";
  3314. }
  3315. s += dirs[i];
  3316. }
  3317. return drive + s;
  3318. }
  3319. static int _humanize_digits(int p_num) {
  3320. if (p_num < 100) {
  3321. return 2;
  3322. } else if (p_num < 1024) {
  3323. return 1;
  3324. } else {
  3325. return 0;
  3326. }
  3327. }
  3328. String String::humanize_size(uint64_t p_size) {
  3329. uint64_t _div = 1;
  3330. Vector<String> prefixes;
  3331. prefixes.push_back(RTR("B"));
  3332. prefixes.push_back(RTR("KiB"));
  3333. prefixes.push_back(RTR("MiB"));
  3334. prefixes.push_back(RTR("GiB"));
  3335. prefixes.push_back(RTR("TiB"));
  3336. prefixes.push_back(RTR("PiB"));
  3337. prefixes.push_back(RTR("EiB"));
  3338. int prefix_idx = 0;
  3339. while (prefix_idx < prefixes.size() - 1 && p_size > (_div * 1024)) {
  3340. _div *= 1024;
  3341. prefix_idx++;
  3342. }
  3343. const int digits = prefix_idx > 0 ? _humanize_digits(p_size / _div) : 0;
  3344. const double divisor = prefix_idx > 0 ? _div : 1;
  3345. return String::num(p_size / divisor).pad_decimals(digits) + " " + prefixes[prefix_idx];
  3346. }
  3347. bool String::is_absolute_path() const {
  3348. if (length() > 1) {
  3349. return (operator[](0) == '/' || operator[](0) == '\\' || find(":/") != -1 || find(":\\") != -1);
  3350. } else if ((length()) == 1) {
  3351. return (operator[](0) == '/' || operator[](0) == '\\');
  3352. } else {
  3353. return false;
  3354. }
  3355. }
  3356. String String::validate_identifier() const {
  3357. if (is_empty()) {
  3358. return "_"; // Empty string is not a valid identifier;
  3359. }
  3360. String result;
  3361. if (is_digit(operator[](0))) {
  3362. result = "_" + *this;
  3363. } else {
  3364. result = *this;
  3365. }
  3366. int len = result.length();
  3367. char32_t *buffer = result.ptrw();
  3368. for (int i = 0; i < len; i++) {
  3369. if (!is_ascii_identifier_char(buffer[i])) {
  3370. buffer[i] = '_';
  3371. }
  3372. }
  3373. return result;
  3374. }
  3375. bool String::is_valid_identifier() const {
  3376. int len = length();
  3377. if (len == 0) {
  3378. return false;
  3379. }
  3380. if (is_digit(operator[](0))) {
  3381. return false;
  3382. }
  3383. const char32_t *str = &operator[](0);
  3384. for (int i = 0; i < len; i++) {
  3385. if (!is_ascii_identifier_char(str[i])) {
  3386. return false;
  3387. }
  3388. }
  3389. return true;
  3390. }
  3391. bool String::is_valid_string() const {
  3392. int l = length();
  3393. const char32_t *src = get_data();
  3394. bool valid = true;
  3395. for (int i = 0; i < l; i++) {
  3396. valid = valid && (src[i] < 0xd800 || (src[i] > 0xdfff && src[i] <= 0x10ffff));
  3397. }
  3398. return valid;
  3399. }
  3400. String String::uri_encode() const {
  3401. const CharString temp = utf8();
  3402. String res;
  3403. for (int i = 0; i < temp.length(); ++i) {
  3404. uint8_t ord = temp[i];
  3405. if (ord == '.' || ord == '-' || ord == '~' || is_ascii_identifier_char(ord)) {
  3406. res += ord;
  3407. } else {
  3408. char p[4] = { '%', 0, 0, 0 };
  3409. static const char hex[16] = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F' };
  3410. p[1] = hex[ord >> 4];
  3411. p[2] = hex[ord & 0xF];
  3412. res += p;
  3413. }
  3414. }
  3415. return res;
  3416. }
  3417. String String::uri_decode() const {
  3418. CharString src = utf8();
  3419. CharString res;
  3420. for (int i = 0; i < src.length(); ++i) {
  3421. if (src[i] == '%' && i + 2 < src.length()) {
  3422. char ord1 = src[i + 1];
  3423. if (is_digit(ord1) || is_ascii_upper_case(ord1)) {
  3424. char ord2 = src[i + 2];
  3425. if (is_digit(ord2) || is_ascii_upper_case(ord2)) {
  3426. char bytes[3] = { (char)ord1, (char)ord2, 0 };
  3427. res += (char)strtol(bytes, nullptr, 16);
  3428. i += 2;
  3429. }
  3430. } else {
  3431. res += src[i];
  3432. }
  3433. } else if (src[i] == '+') {
  3434. res += ' ';
  3435. } else {
  3436. res += src[i];
  3437. }
  3438. }
  3439. return String::utf8(res);
  3440. }
  3441. String String::c_unescape() const {
  3442. String escaped = *this;
  3443. escaped = escaped.replace("\\a", "\a");
  3444. escaped = escaped.replace("\\b", "\b");
  3445. escaped = escaped.replace("\\f", "\f");
  3446. escaped = escaped.replace("\\n", "\n");
  3447. escaped = escaped.replace("\\r", "\r");
  3448. escaped = escaped.replace("\\t", "\t");
  3449. escaped = escaped.replace("\\v", "\v");
  3450. escaped = escaped.replace("\\'", "\'");
  3451. escaped = escaped.replace("\\\"", "\"");
  3452. escaped = escaped.replace("\\\\", "\\");
  3453. return escaped;
  3454. }
  3455. String String::c_escape() const {
  3456. String escaped = *this;
  3457. escaped = escaped.replace("\\", "\\\\");
  3458. escaped = escaped.replace("\a", "\\a");
  3459. escaped = escaped.replace("\b", "\\b");
  3460. escaped = escaped.replace("\f", "\\f");
  3461. escaped = escaped.replace("\n", "\\n");
  3462. escaped = escaped.replace("\r", "\\r");
  3463. escaped = escaped.replace("\t", "\\t");
  3464. escaped = escaped.replace("\v", "\\v");
  3465. escaped = escaped.replace("\'", "\\'");
  3466. escaped = escaped.replace("\"", "\\\"");
  3467. return escaped;
  3468. }
  3469. String String::c_escape_multiline() const {
  3470. String escaped = *this;
  3471. escaped = escaped.replace("\\", "\\\\");
  3472. escaped = escaped.replace("\"", "\\\"");
  3473. return escaped;
  3474. }
  3475. String String::json_escape() const {
  3476. String escaped = *this;
  3477. escaped = escaped.replace("\\", "\\\\");
  3478. escaped = escaped.replace("\b", "\\b");
  3479. escaped = escaped.replace("\f", "\\f");
  3480. escaped = escaped.replace("\n", "\\n");
  3481. escaped = escaped.replace("\r", "\\r");
  3482. escaped = escaped.replace("\t", "\\t");
  3483. escaped = escaped.replace("\v", "\\v");
  3484. escaped = escaped.replace("\"", "\\\"");
  3485. return escaped;
  3486. }
  3487. String String::xml_escape(bool p_escape_quotes) const {
  3488. String str = *this;
  3489. str = str.replace("&", "&amp;");
  3490. str = str.replace("<", "&lt;");
  3491. str = str.replace(">", "&gt;");
  3492. if (p_escape_quotes) {
  3493. str = str.replace("'", "&apos;");
  3494. str = str.replace("\"", "&quot;");
  3495. }
  3496. /*
  3497. for (int i=1;i<32;i++) {
  3498. char chr[2]={i,0};
  3499. str=str.replace(chr,"&#"+String::num(i)+";");
  3500. }*/
  3501. return str;
  3502. }
  3503. static _FORCE_INLINE_ int _xml_unescape(const char32_t *p_src, int p_src_len, char32_t *p_dst) {
  3504. int len = 0;
  3505. while (p_src_len) {
  3506. if (*p_src == '&') {
  3507. int eat = 0;
  3508. if (p_src_len >= 4 && p_src[1] == '#') {
  3509. char32_t c = 0;
  3510. bool overflow = false;
  3511. if (p_src[2] == 'x') {
  3512. // Hex entity &#x<num>;
  3513. for (int i = 3; i < p_src_len; i++) {
  3514. eat = i + 1;
  3515. char32_t ct = p_src[i];
  3516. if (ct == ';') {
  3517. break;
  3518. } else if (is_digit(ct)) {
  3519. ct = ct - '0';
  3520. } else if (ct >= 'a' && ct <= 'f') {
  3521. ct = (ct - 'a') + 10;
  3522. } else if (ct >= 'A' && ct <= 'F') {
  3523. ct = (ct - 'A') + 10;
  3524. } else {
  3525. break;
  3526. }
  3527. if (c > (UINT32_MAX >> 4)) {
  3528. overflow = true;
  3529. break;
  3530. }
  3531. c <<= 4;
  3532. c |= ct;
  3533. }
  3534. } else {
  3535. // Decimal entity &#<num>;
  3536. for (int i = 2; i < p_src_len; i++) {
  3537. eat = i + 1;
  3538. char32_t ct = p_src[i];
  3539. if (ct == ';' || !is_digit(ct)) {
  3540. break;
  3541. }
  3542. }
  3543. if (p_src[eat - 1] == ';') {
  3544. int64_t val = String::to_int(p_src + 2, eat - 3);
  3545. if (val > 0 && val <= UINT32_MAX) {
  3546. c = (char32_t)val;
  3547. } else {
  3548. overflow = true;
  3549. }
  3550. }
  3551. }
  3552. // Value must be non-zero, in the range of char32_t,
  3553. // actually end with ';'. If invalid, leave the entity as-is
  3554. if (c == '\0' || overflow || p_src[eat - 1] != ';') {
  3555. eat = 1;
  3556. c = *p_src;
  3557. }
  3558. if (p_dst) {
  3559. *p_dst = c;
  3560. }
  3561. } else if (p_src_len >= 4 && p_src[1] == 'g' && p_src[2] == 't' && p_src[3] == ';') {
  3562. if (p_dst) {
  3563. *p_dst = '>';
  3564. }
  3565. eat = 4;
  3566. } else if (p_src_len >= 4 && p_src[1] == 'l' && p_src[2] == 't' && p_src[3] == ';') {
  3567. if (p_dst) {
  3568. *p_dst = '<';
  3569. }
  3570. eat = 4;
  3571. } else if (p_src_len >= 5 && p_src[1] == 'a' && p_src[2] == 'm' && p_src[3] == 'p' && p_src[4] == ';') {
  3572. if (p_dst) {
  3573. *p_dst = '&';
  3574. }
  3575. eat = 5;
  3576. } else if (p_src_len >= 6 && p_src[1] == 'q' && p_src[2] == 'u' && p_src[3] == 'o' && p_src[4] == 't' && p_src[5] == ';') {
  3577. if (p_dst) {
  3578. *p_dst = '"';
  3579. }
  3580. eat = 6;
  3581. } else if (p_src_len >= 6 && p_src[1] == 'a' && p_src[2] == 'p' && p_src[3] == 'o' && p_src[4] == 's' && p_src[5] == ';') {
  3582. if (p_dst) {
  3583. *p_dst = '\'';
  3584. }
  3585. eat = 6;
  3586. } else {
  3587. if (p_dst) {
  3588. *p_dst = *p_src;
  3589. }
  3590. eat = 1;
  3591. }
  3592. if (p_dst) {
  3593. p_dst++;
  3594. }
  3595. len++;
  3596. p_src += eat;
  3597. p_src_len -= eat;
  3598. } else {
  3599. if (p_dst) {
  3600. *p_dst = *p_src;
  3601. p_dst++;
  3602. }
  3603. len++;
  3604. p_src++;
  3605. p_src_len--;
  3606. }
  3607. }
  3608. return len;
  3609. }
  3610. String String::xml_unescape() const {
  3611. String str;
  3612. int l = length();
  3613. int len = _xml_unescape(get_data(), l, nullptr);
  3614. if (len == 0) {
  3615. return String();
  3616. }
  3617. str.resize(len + 1);
  3618. _xml_unescape(get_data(), l, str.ptrw());
  3619. str[len] = 0;
  3620. return str;
  3621. }
  3622. String String::pad_decimals(int p_digits) const {
  3623. String s = *this;
  3624. int c = s.find(".");
  3625. if (c == -1) {
  3626. if (p_digits <= 0) {
  3627. return s;
  3628. }
  3629. s += ".";
  3630. c = s.length() - 1;
  3631. } else {
  3632. if (p_digits <= 0) {
  3633. return s.substr(0, c);
  3634. }
  3635. }
  3636. if (s.length() - (c + 1) > p_digits) {
  3637. return s.substr(0, c + p_digits + 1);
  3638. } else {
  3639. int zeros_to_add = p_digits - s.length() + (c + 1);
  3640. return s + String("0").repeat(zeros_to_add);
  3641. }
  3642. }
  3643. String String::pad_zeros(int p_digits) const {
  3644. String s = *this;
  3645. int end = s.find(".");
  3646. if (end == -1) {
  3647. end = s.length();
  3648. }
  3649. if (end == 0) {
  3650. return s;
  3651. }
  3652. int begin = 0;
  3653. while (begin < end && !is_digit(s[begin])) {
  3654. begin++;
  3655. }
  3656. int zeros_to_add = p_digits - (end - begin);
  3657. if (zeros_to_add <= 0) {
  3658. return s;
  3659. } else {
  3660. return s.insert(begin, String("0").repeat(zeros_to_add));
  3661. }
  3662. }
  3663. String String::trim_prefix(const String &p_prefix) const {
  3664. String s = *this;
  3665. if (s.begins_with(p_prefix)) {
  3666. return s.substr(p_prefix.length(), s.length() - p_prefix.length());
  3667. }
  3668. return s;
  3669. }
  3670. String String::trim_suffix(const String &p_suffix) const {
  3671. String s = *this;
  3672. if (s.ends_with(p_suffix)) {
  3673. return s.substr(0, s.length() - p_suffix.length());
  3674. }
  3675. return s;
  3676. }
  3677. bool String::is_valid_int() const {
  3678. int len = length();
  3679. if (len == 0) {
  3680. return false;
  3681. }
  3682. int from = 0;
  3683. if (len != 1 && (operator[](0) == '+' || operator[](0) == '-')) {
  3684. from++;
  3685. }
  3686. for (int i = from; i < len; i++) {
  3687. if (!is_digit(operator[](i))) {
  3688. return false; // no start with number plz
  3689. }
  3690. }
  3691. return true;
  3692. }
  3693. bool String::is_valid_hex_number(bool p_with_prefix) const {
  3694. int len = length();
  3695. if (len == 0) {
  3696. return false;
  3697. }
  3698. int from = 0;
  3699. if (len != 1 && (operator[](0) == '+' || operator[](0) == '-')) {
  3700. from++;
  3701. }
  3702. if (p_with_prefix) {
  3703. if (len < 3) {
  3704. return false;
  3705. }
  3706. if (operator[](from) != '0' || operator[](from + 1) != 'x') {
  3707. return false;
  3708. }
  3709. from += 2;
  3710. }
  3711. for (int i = from; i < len; i++) {
  3712. char32_t c = operator[](i);
  3713. if (is_hex_digit(c)) {
  3714. continue;
  3715. }
  3716. return false;
  3717. }
  3718. return true;
  3719. }
  3720. bool String::is_valid_float() const {
  3721. int len = length();
  3722. if (len == 0) {
  3723. return false;
  3724. }
  3725. int from = 0;
  3726. if (operator[](0) == '+' || operator[](0) == '-') {
  3727. from++;
  3728. }
  3729. bool exponent_found = false;
  3730. bool period_found = false;
  3731. bool sign_found = false;
  3732. bool exponent_values_found = false;
  3733. bool numbers_found = false;
  3734. for (int i = from; i < len; i++) {
  3735. if (is_digit(operator[](i))) {
  3736. if (exponent_found) {
  3737. exponent_values_found = true;
  3738. } else {
  3739. numbers_found = true;
  3740. }
  3741. } else if (numbers_found && !exponent_found && operator[](i) == 'e') {
  3742. exponent_found = true;
  3743. } else if (!period_found && !exponent_found && operator[](i) == '.') {
  3744. period_found = true;
  3745. } else if ((operator[](i) == '-' || operator[](i) == '+') && exponent_found && !exponent_values_found && !sign_found) {
  3746. sign_found = true;
  3747. } else {
  3748. return false; // no start with number plz
  3749. }
  3750. }
  3751. return numbers_found;
  3752. }
  3753. String String::path_to_file(const String &p_path) const {
  3754. // Don't get base dir for src, this is expected to be a dir already.
  3755. String src = this->replace("\\", "/");
  3756. String dst = p_path.replace("\\", "/").get_base_dir();
  3757. String rel = src.path_to(dst);
  3758. if (rel == dst) { // failed
  3759. return p_path;
  3760. } else {
  3761. return rel + p_path.get_file();
  3762. }
  3763. }
  3764. String String::path_to(const String &p_path) const {
  3765. String src = this->replace("\\", "/");
  3766. String dst = p_path.replace("\\", "/");
  3767. if (!src.ends_with("/")) {
  3768. src += "/";
  3769. }
  3770. if (!dst.ends_with("/")) {
  3771. dst += "/";
  3772. }
  3773. if (src.begins_with("res://") && dst.begins_with("res://")) {
  3774. src = src.replace("res://", "/");
  3775. dst = dst.replace("res://", "/");
  3776. } else if (src.begins_with("user://") && dst.begins_with("user://")) {
  3777. src = src.replace("user://", "/");
  3778. dst = dst.replace("user://", "/");
  3779. } else if (src.begins_with("/") && dst.begins_with("/")) {
  3780. //nothing
  3781. } else {
  3782. //dos style
  3783. String src_begin = src.get_slicec('/', 0);
  3784. String dst_begin = dst.get_slicec('/', 0);
  3785. if (src_begin != dst_begin) {
  3786. return p_path; //impossible to do this
  3787. }
  3788. src = src.substr(src_begin.length(), src.length());
  3789. dst = dst.substr(dst_begin.length(), dst.length());
  3790. }
  3791. //remove leading and trailing slash and split
  3792. Vector<String> src_dirs = src.substr(1, src.length() - 2).split("/");
  3793. Vector<String> dst_dirs = dst.substr(1, dst.length() - 2).split("/");
  3794. //find common parent
  3795. int common_parent = 0;
  3796. while (true) {
  3797. if (src_dirs.size() == common_parent) {
  3798. break;
  3799. }
  3800. if (dst_dirs.size() == common_parent) {
  3801. break;
  3802. }
  3803. if (src_dirs[common_parent] != dst_dirs[common_parent]) {
  3804. break;
  3805. }
  3806. common_parent++;
  3807. }
  3808. common_parent--;
  3809. int dirs_to_backtrack = (src_dirs.size() - 1) - common_parent;
  3810. String dir = String("../").repeat(dirs_to_backtrack);
  3811. for (int i = common_parent + 1; i < dst_dirs.size(); i++) {
  3812. dir += dst_dirs[i] + "/";
  3813. }
  3814. if (dir.length() == 0) {
  3815. dir = "./";
  3816. }
  3817. return dir;
  3818. }
  3819. bool String::is_valid_html_color() const {
  3820. return Color::html_is_valid(*this);
  3821. }
  3822. // Changes made to the set of invalid filename characters must also be reflected in the String documentation for is_valid_filename.
  3823. static const char *invalid_filename_characters = ": / \\ ? * \" | % < >";
  3824. bool String::is_valid_filename() const {
  3825. String stripped = strip_edges();
  3826. if (*this != stripped) {
  3827. return false;
  3828. }
  3829. if (stripped.is_empty()) {
  3830. return false;
  3831. }
  3832. Vector<String> chars = String(invalid_filename_characters).split(" ");
  3833. for (const String &ch : chars) {
  3834. if (contains(ch)) {
  3835. return false;
  3836. }
  3837. }
  3838. return true;
  3839. }
  3840. String String::validate_filename() const {
  3841. Vector<String> chars = String(invalid_filename_characters).split(" ");
  3842. String name = strip_edges();
  3843. for (int i = 0; i < chars.size(); i++) {
  3844. name = name.replace(chars[i], "_");
  3845. }
  3846. return name;
  3847. }
  3848. bool String::is_valid_ip_address() const {
  3849. if (find(":") >= 0) {
  3850. Vector<String> ip = split(":");
  3851. for (int i = 0; i < ip.size(); i++) {
  3852. String n = ip[i];
  3853. if (n.is_empty()) {
  3854. continue;
  3855. }
  3856. if (n.is_valid_hex_number(false)) {
  3857. int64_t nint = n.hex_to_int();
  3858. if (nint < 0 || nint > 0xffff) {
  3859. return false;
  3860. }
  3861. continue;
  3862. }
  3863. if (!n.is_valid_ip_address()) {
  3864. return false;
  3865. }
  3866. }
  3867. } else {
  3868. Vector<String> ip = split(".");
  3869. if (ip.size() != 4) {
  3870. return false;
  3871. }
  3872. for (int i = 0; i < ip.size(); i++) {
  3873. String n = ip[i];
  3874. if (!n.is_valid_int()) {
  3875. return false;
  3876. }
  3877. int val = n.to_int();
  3878. if (val < 0 || val > 255) {
  3879. return false;
  3880. }
  3881. }
  3882. }
  3883. return true;
  3884. }
  3885. bool String::is_resource_file() const {
  3886. return begins_with("res://") && find("::") == -1;
  3887. }
  3888. bool String::is_relative_path() const {
  3889. return !is_absolute_path();
  3890. }
  3891. String String::get_base_dir() const {
  3892. int end = 0;
  3893. // URL scheme style base.
  3894. int basepos = find("://");
  3895. if (basepos != -1) {
  3896. end = basepos + 3;
  3897. }
  3898. // Windows top level directory base.
  3899. if (end == 0) {
  3900. basepos = find(":/");
  3901. if (basepos == -1) {
  3902. basepos = find(":\\");
  3903. }
  3904. if (basepos != -1) {
  3905. end = basepos + 2;
  3906. }
  3907. }
  3908. // Windows UNC network share path.
  3909. if (end == 0) {
  3910. if (is_network_share_path()) {
  3911. basepos = find("/", 2);
  3912. if (basepos == -1) {
  3913. basepos = find("\\", 2);
  3914. }
  3915. int servpos = find("/", basepos + 1);
  3916. if (servpos == -1) {
  3917. servpos = find("\\", basepos + 1);
  3918. }
  3919. if (servpos != -1) {
  3920. end = servpos + 1;
  3921. }
  3922. }
  3923. }
  3924. // Unix root directory base.
  3925. if (end == 0) {
  3926. if (begins_with("/")) {
  3927. end = 1;
  3928. }
  3929. }
  3930. String rs;
  3931. String base;
  3932. if (end != 0) {
  3933. rs = substr(end, length());
  3934. base = substr(0, end);
  3935. } else {
  3936. rs = *this;
  3937. }
  3938. int sep = MAX(rs.rfind("/"), rs.rfind("\\"));
  3939. if (sep == -1) {
  3940. return base;
  3941. }
  3942. return base + rs.substr(0, sep);
  3943. }
  3944. String String::get_file() const {
  3945. int sep = MAX(rfind("/"), rfind("\\"));
  3946. if (sep == -1) {
  3947. return *this;
  3948. }
  3949. return substr(sep + 1, length());
  3950. }
  3951. String String::get_extension() const {
  3952. int pos = rfind(".");
  3953. if (pos < 0 || pos < MAX(rfind("/"), rfind("\\"))) {
  3954. return "";
  3955. }
  3956. return substr(pos + 1, length());
  3957. }
  3958. String String::path_join(const String &p_file) const {
  3959. if (is_empty()) {
  3960. return p_file;
  3961. }
  3962. if (operator[](length() - 1) == '/' || (p_file.size() > 0 && p_file.operator[](0) == '/')) {
  3963. return *this + p_file;
  3964. }
  3965. return *this + "/" + p_file;
  3966. }
  3967. String String::property_name_encode() const {
  3968. // Escape and quote strings with extended ASCII or further Unicode characters
  3969. // as well as '"', '=' or ' ' (32)
  3970. const char32_t *cstr = get_data();
  3971. for (int i = 0; cstr[i]; i++) {
  3972. if (cstr[i] == '=' || cstr[i] == '"' || cstr[i] == ';' || cstr[i] == '[' || cstr[i] == ']' || cstr[i] < 33 || cstr[i] > 126) {
  3973. return "\"" + c_escape_multiline() + "\"";
  3974. }
  3975. }
  3976. // Keep as is
  3977. return *this;
  3978. }
  3979. // Changes made to the set of invalid characters must also be reflected in the String documentation.
  3980. static const char32_t invalid_node_name_characters[] = { '.', ':', '@', '/', '\"', UNIQUE_NODE_PREFIX[0], 0 };
  3981. String String::get_invalid_node_name_characters(bool p_allow_internal) {
  3982. // Do not use this function for critical validation.
  3983. String r;
  3984. const char32_t *c = invalid_node_name_characters;
  3985. while (*c) {
  3986. if (p_allow_internal && *c == '@') {
  3987. c++;
  3988. continue;
  3989. }
  3990. if (c != invalid_node_name_characters) {
  3991. r += " ";
  3992. }
  3993. r += String::chr(*c);
  3994. c++;
  3995. }
  3996. return r;
  3997. }
  3998. String String::validate_node_name() const {
  3999. // This is a critical validation in node addition, so it must be optimized.
  4000. const char32_t *cn = ptr();
  4001. if (cn == nullptr) {
  4002. return String();
  4003. }
  4004. bool valid = true;
  4005. uint32_t idx = 0;
  4006. while (cn[idx]) {
  4007. const char32_t *c = invalid_node_name_characters;
  4008. while (*c) {
  4009. if (cn[idx] == *c) {
  4010. valid = false;
  4011. break;
  4012. }
  4013. c++;
  4014. }
  4015. if (!valid) {
  4016. break;
  4017. }
  4018. idx++;
  4019. }
  4020. if (valid) {
  4021. return *this;
  4022. }
  4023. String validated = *this;
  4024. char32_t *nn = validated.ptrw();
  4025. while (nn[idx]) {
  4026. const char32_t *c = invalid_node_name_characters;
  4027. while (*c) {
  4028. if (nn[idx] == *c) {
  4029. nn[idx] = '_';
  4030. break;
  4031. }
  4032. c++;
  4033. }
  4034. idx++;
  4035. }
  4036. return validated;
  4037. }
  4038. String String::get_basename() const {
  4039. int pos = rfind(".");
  4040. if (pos < 0 || pos < MAX(rfind("/"), rfind("\\"))) {
  4041. return *this;
  4042. }
  4043. return substr(0, pos);
  4044. }
  4045. String itos(int64_t p_val) {
  4046. return String::num_int64(p_val);
  4047. }
  4048. String uitos(uint64_t p_val) {
  4049. return String::num_uint64(p_val);
  4050. }
  4051. String rtos(double p_val) {
  4052. return String::num(p_val);
  4053. }
  4054. String rtoss(double p_val) {
  4055. return String::num_scientific(p_val);
  4056. }
  4057. // Right-pad with a character.
  4058. String String::rpad(int min_length, const String &character) const {
  4059. String s = *this;
  4060. int padding = min_length - s.length();
  4061. if (padding > 0) {
  4062. s += character.repeat(padding);
  4063. }
  4064. return s;
  4065. }
  4066. // Left-pad with a character.
  4067. String String::lpad(int min_length, const String &character) const {
  4068. String s = *this;
  4069. int padding = min_length - s.length();
  4070. if (padding > 0) {
  4071. s = character.repeat(padding) + s;
  4072. }
  4073. return s;
  4074. }
  4075. // sprintf is implemented in GDScript via:
  4076. // "fish %s pie" % "frog"
  4077. // "fish %s %d pie" % ["frog", 12]
  4078. // In case of an error, the string returned is the error description and "error" is true.
  4079. String String::sprintf(const Array &values, bool *error) const {
  4080. String formatted;
  4081. char32_t *self = (char32_t *)get_data();
  4082. bool in_format = false;
  4083. int value_index = 0;
  4084. int min_chars = 0;
  4085. int min_decimals = 0;
  4086. bool in_decimals = false;
  4087. bool pad_with_zeros = false;
  4088. bool left_justified = false;
  4089. bool show_sign = false;
  4090. if (error) {
  4091. *error = true;
  4092. }
  4093. for (; *self; self++) {
  4094. const char32_t c = *self;
  4095. if (in_format) { // We have % - let's see what else we get.
  4096. switch (c) {
  4097. case '%': { // Replace %% with %
  4098. formatted += chr(c);
  4099. in_format = false;
  4100. break;
  4101. }
  4102. case 'd': // Integer (signed)
  4103. case 'o': // Octal
  4104. case 'x': // Hexadecimal (lowercase)
  4105. case 'X': { // Hexadecimal (uppercase)
  4106. if (value_index >= values.size()) {
  4107. return "not enough arguments for format string";
  4108. }
  4109. if (!values[value_index].is_num()) {
  4110. return "a number is required";
  4111. }
  4112. int64_t value = values[value_index];
  4113. int base = 16;
  4114. bool capitalize = false;
  4115. switch (c) {
  4116. case 'd':
  4117. base = 10;
  4118. break;
  4119. case 'o':
  4120. base = 8;
  4121. break;
  4122. case 'x':
  4123. break;
  4124. case 'X':
  4125. base = 16;
  4126. capitalize = true;
  4127. break;
  4128. }
  4129. // Get basic number.
  4130. String str = String::num_int64(ABS(value), base, capitalize);
  4131. int number_len = str.length();
  4132. // Padding.
  4133. int pad_chars_count = (value < 0 || show_sign) ? min_chars - 1 : min_chars;
  4134. String pad_char = pad_with_zeros ? String("0") : String(" ");
  4135. if (left_justified) {
  4136. str = str.rpad(pad_chars_count, pad_char);
  4137. } else {
  4138. str = str.lpad(pad_chars_count, pad_char);
  4139. }
  4140. // Sign.
  4141. if (show_sign || value < 0) {
  4142. String sign_char = value < 0 ? "-" : "+";
  4143. if (left_justified) {
  4144. str = str.insert(0, sign_char);
  4145. } else {
  4146. str = str.insert(pad_with_zeros ? 0 : str.length() - number_len, sign_char);
  4147. }
  4148. }
  4149. formatted += str;
  4150. ++value_index;
  4151. in_format = false;
  4152. break;
  4153. }
  4154. case 'f': { // Float
  4155. if (value_index >= values.size()) {
  4156. return "not enough arguments for format string";
  4157. }
  4158. if (!values[value_index].is_num()) {
  4159. return "a number is required";
  4160. }
  4161. double value = values[value_index];
  4162. bool is_negative = signbit(value);
  4163. String str = String::num(Math::abs(value), min_decimals);
  4164. const bool is_finite = Math::is_finite(value);
  4165. // Pad decimals out.
  4166. if (is_finite) {
  4167. str = str.pad_decimals(min_decimals);
  4168. }
  4169. int initial_len = str.length();
  4170. // Padding. Leave room for sign later if required.
  4171. int pad_chars_count = (is_negative || show_sign) ? min_chars - 1 : min_chars;
  4172. String pad_char = (pad_with_zeros && is_finite) ? String("0") : String(" "); // Never pad NaN or inf with zeros
  4173. if (left_justified) {
  4174. str = str.rpad(pad_chars_count, pad_char);
  4175. } else {
  4176. str = str.lpad(pad_chars_count, pad_char);
  4177. }
  4178. // Add sign if needed.
  4179. if (show_sign || is_negative) {
  4180. String sign_char = is_negative ? "-" : "+";
  4181. if (left_justified) {
  4182. str = str.insert(0, sign_char);
  4183. } else {
  4184. str = str.insert(pad_with_zeros ? 0 : str.length() - initial_len, sign_char);
  4185. }
  4186. }
  4187. formatted += str;
  4188. ++value_index;
  4189. in_format = false;
  4190. break;
  4191. }
  4192. case 'v': { // Vector2/3/4/2i/3i/4i
  4193. if (value_index >= values.size()) {
  4194. return "not enough arguments for format string";
  4195. }
  4196. int count;
  4197. switch (values[value_index].get_type()) {
  4198. case Variant::VECTOR2:
  4199. case Variant::VECTOR2I: {
  4200. count = 2;
  4201. } break;
  4202. case Variant::VECTOR3:
  4203. case Variant::VECTOR3I: {
  4204. count = 3;
  4205. } break;
  4206. case Variant::VECTOR4:
  4207. case Variant::VECTOR4I: {
  4208. count = 4;
  4209. } break;
  4210. default: {
  4211. return "%v requires a vector type (Vector2/3/4/2i/3i/4i)";
  4212. }
  4213. }
  4214. Vector4 vec = values[value_index];
  4215. String str = "(";
  4216. for (int i = 0; i < count; i++) {
  4217. double val = vec[i];
  4218. String number_str = String::num(Math::abs(val), min_decimals);
  4219. const bool is_finite = Math::is_finite(val);
  4220. // Pad decimals out.
  4221. if (is_finite) {
  4222. number_str = number_str.pad_decimals(min_decimals);
  4223. }
  4224. int initial_len = number_str.length();
  4225. // Padding. Leave room for sign later if required.
  4226. int pad_chars_count = val < 0 ? min_chars - 1 : min_chars;
  4227. String pad_char = (pad_with_zeros && is_finite) ? String("0") : String(" "); // Never pad NaN or inf with zeros
  4228. if (left_justified) {
  4229. number_str = number_str.rpad(pad_chars_count, pad_char);
  4230. } else {
  4231. number_str = number_str.lpad(pad_chars_count, pad_char);
  4232. }
  4233. // Add sign if needed.
  4234. if (val < 0) {
  4235. if (left_justified) {
  4236. number_str = number_str.insert(0, "-");
  4237. } else {
  4238. number_str = number_str.insert(pad_with_zeros ? 0 : number_str.length() - initial_len, "-");
  4239. }
  4240. }
  4241. // Add number to combined string
  4242. str += number_str;
  4243. if (i < count - 1) {
  4244. str += ", ";
  4245. }
  4246. }
  4247. str += ")";
  4248. formatted += str;
  4249. ++value_index;
  4250. in_format = false;
  4251. break;
  4252. }
  4253. case 's': { // String
  4254. if (value_index >= values.size()) {
  4255. return "not enough arguments for format string";
  4256. }
  4257. String str = values[value_index];
  4258. // Padding.
  4259. if (left_justified) {
  4260. str = str.rpad(min_chars);
  4261. } else {
  4262. str = str.lpad(min_chars);
  4263. }
  4264. formatted += str;
  4265. ++value_index;
  4266. in_format = false;
  4267. break;
  4268. }
  4269. case 'c': {
  4270. if (value_index >= values.size()) {
  4271. return "not enough arguments for format string";
  4272. }
  4273. // Convert to character.
  4274. String str;
  4275. if (values[value_index].is_num()) {
  4276. int value = values[value_index];
  4277. if (value < 0) {
  4278. return "unsigned integer is lower than minimum";
  4279. } else if (value >= 0xd800 && value <= 0xdfff) {
  4280. return "unsigned integer is invalid Unicode character";
  4281. } else if (value > 0x10ffff) {
  4282. return "unsigned integer is greater than maximum";
  4283. }
  4284. str = chr(values[value_index]);
  4285. } else if (values[value_index].get_type() == Variant::STRING) {
  4286. str = values[value_index];
  4287. if (str.length() != 1) {
  4288. return "%c requires number or single-character string";
  4289. }
  4290. } else {
  4291. return "%c requires number or single-character string";
  4292. }
  4293. // Padding.
  4294. if (left_justified) {
  4295. str = str.rpad(min_chars);
  4296. } else {
  4297. str = str.lpad(min_chars);
  4298. }
  4299. formatted += str;
  4300. ++value_index;
  4301. in_format = false;
  4302. break;
  4303. }
  4304. case '-': { // Left justify
  4305. left_justified = true;
  4306. break;
  4307. }
  4308. case '+': { // Show + if positive.
  4309. show_sign = true;
  4310. break;
  4311. }
  4312. case '0':
  4313. case '1':
  4314. case '2':
  4315. case '3':
  4316. case '4':
  4317. case '5':
  4318. case '6':
  4319. case '7':
  4320. case '8':
  4321. case '9': {
  4322. int n = c - '0';
  4323. if (in_decimals) {
  4324. min_decimals *= 10;
  4325. min_decimals += n;
  4326. } else {
  4327. if (c == '0' && min_chars == 0) {
  4328. if (left_justified) {
  4329. WARN_PRINT("'0' flag ignored with '-' flag in string format");
  4330. } else {
  4331. pad_with_zeros = true;
  4332. }
  4333. } else {
  4334. min_chars *= 10;
  4335. min_chars += n;
  4336. }
  4337. }
  4338. break;
  4339. }
  4340. case '.': { // Float/Vector separator.
  4341. if (in_decimals) {
  4342. return "too many decimal points in format";
  4343. }
  4344. in_decimals = true;
  4345. min_decimals = 0; // We want to add the value manually.
  4346. break;
  4347. }
  4348. case '*': { // Dynamic width, based on value.
  4349. if (value_index >= values.size()) {
  4350. return "not enough arguments for format string";
  4351. }
  4352. Variant::Type value_type = values[value_index].get_type();
  4353. if (!values[value_index].is_num() &&
  4354. value_type != Variant::VECTOR2 && value_type != Variant::VECTOR2I &&
  4355. value_type != Variant::VECTOR3 && value_type != Variant::VECTOR3I &&
  4356. value_type != Variant::VECTOR4 && value_type != Variant::VECTOR4I) {
  4357. return "* wants number or vector";
  4358. }
  4359. int size = values[value_index];
  4360. if (in_decimals) {
  4361. min_decimals = size;
  4362. } else {
  4363. min_chars = size;
  4364. }
  4365. ++value_index;
  4366. break;
  4367. }
  4368. default: {
  4369. return "unsupported format character";
  4370. }
  4371. }
  4372. } else { // Not in format string.
  4373. switch (c) {
  4374. case '%':
  4375. in_format = true;
  4376. // Back to defaults:
  4377. min_chars = 0;
  4378. min_decimals = 6;
  4379. pad_with_zeros = false;
  4380. left_justified = false;
  4381. show_sign = false;
  4382. in_decimals = false;
  4383. break;
  4384. default:
  4385. formatted += chr(c);
  4386. }
  4387. }
  4388. }
  4389. if (in_format) {
  4390. return "incomplete format";
  4391. }
  4392. if (value_index != values.size()) {
  4393. return "not all arguments converted during string formatting";
  4394. }
  4395. if (error) {
  4396. *error = false;
  4397. }
  4398. return formatted;
  4399. }
  4400. String String::quote(String quotechar) const {
  4401. return quotechar + *this + quotechar;
  4402. }
  4403. String String::unquote() const {
  4404. if (!is_quoted()) {
  4405. return *this;
  4406. }
  4407. return substr(1, length() - 2);
  4408. }
  4409. Vector<uint8_t> String::to_ascii_buffer() const {
  4410. const String *s = this;
  4411. if (s->is_empty()) {
  4412. return Vector<uint8_t>();
  4413. }
  4414. CharString charstr = s->ascii();
  4415. Vector<uint8_t> retval;
  4416. size_t len = charstr.length();
  4417. retval.resize(len);
  4418. uint8_t *w = retval.ptrw();
  4419. memcpy(w, charstr.ptr(), len);
  4420. return retval;
  4421. }
  4422. Vector<uint8_t> String::to_utf8_buffer() const {
  4423. const String *s = this;
  4424. if (s->is_empty()) {
  4425. return Vector<uint8_t>();
  4426. }
  4427. CharString charstr = s->utf8();
  4428. Vector<uint8_t> retval;
  4429. size_t len = charstr.length();
  4430. retval.resize(len);
  4431. uint8_t *w = retval.ptrw();
  4432. memcpy(w, charstr.ptr(), len);
  4433. return retval;
  4434. }
  4435. Vector<uint8_t> String::to_utf16_buffer() const {
  4436. const String *s = this;
  4437. if (s->is_empty()) {
  4438. return Vector<uint8_t>();
  4439. }
  4440. Char16String charstr = s->utf16();
  4441. Vector<uint8_t> retval;
  4442. size_t len = charstr.length() * sizeof(char16_t);
  4443. retval.resize(len);
  4444. uint8_t *w = retval.ptrw();
  4445. memcpy(w, (const void *)charstr.ptr(), len);
  4446. return retval;
  4447. }
  4448. Vector<uint8_t> String::to_utf32_buffer() const {
  4449. const String *s = this;
  4450. if (s->is_empty()) {
  4451. return Vector<uint8_t>();
  4452. }
  4453. Vector<uint8_t> retval;
  4454. size_t len = s->length() * sizeof(char32_t);
  4455. retval.resize(len);
  4456. uint8_t *w = retval.ptrw();
  4457. memcpy(w, (const void *)s->ptr(), len);
  4458. return retval;
  4459. }
  4460. Vector<uint8_t> String::to_wchar_buffer() const {
  4461. #ifdef WINDOWS_ENABLED
  4462. return to_utf16_buffer();
  4463. #else
  4464. return to_utf32_buffer();
  4465. #endif
  4466. }
  4467. #ifdef TOOLS_ENABLED
  4468. /**
  4469. * "Tools TRanslate". Performs string replacement for internationalization
  4470. * within the editor. A translation context can optionally be specified to
  4471. * disambiguate between identical source strings in translations. When
  4472. * placeholders are desired, use `vformat(TTR("Example: %s"), some_string)`.
  4473. * If a string mentions a quantity (and may therefore need a dynamic plural form),
  4474. * use `TTRN()` instead of `TTR()`.
  4475. *
  4476. * NOTE: Only use `TTR()` in editor-only code (typically within the `editor/` folder).
  4477. * For translations that can be supplied by exported projects, use `RTR()` instead.
  4478. */
  4479. String TTR(const String &p_text, const String &p_context) {
  4480. if (TranslationServer::get_singleton()) {
  4481. return TranslationServer::get_singleton()->tool_translate(p_text, p_context);
  4482. }
  4483. return p_text;
  4484. }
  4485. /**
  4486. * "Tools TRanslate for N items". Performs string replacement for
  4487. * internationalization within the editor. A translation context can optionally
  4488. * be specified to disambiguate between identical source strings in
  4489. * translations. Use `TTR()` if the string doesn't need dynamic plural form.
  4490. * When placeholders are desired, use
  4491. * `vformat(TTRN("%d item", "%d items", some_integer), some_integer)`.
  4492. * The placeholder must be present in both strings to avoid run-time warnings in `vformat()`.
  4493. *
  4494. * NOTE: Only use `TTRN()` in editor-only code (typically within the `editor/` folder).
  4495. * For translations that can be supplied by exported projects, use `RTRN()` instead.
  4496. */
  4497. String TTRN(const String &p_text, const String &p_text_plural, int p_n, const String &p_context) {
  4498. if (TranslationServer::get_singleton()) {
  4499. return TranslationServer::get_singleton()->tool_translate_plural(p_text, p_text_plural, p_n, p_context);
  4500. }
  4501. // Return message based on English plural rule if translation is not possible.
  4502. if (p_n == 1) {
  4503. return p_text;
  4504. }
  4505. return p_text_plural;
  4506. }
  4507. /**
  4508. * "Docs TRanslate". Used for the editor class reference documentation,
  4509. * handling descriptions extracted from the XML.
  4510. * It also replaces `$DOCS_URL` with the actual URL to the documentation's branch,
  4511. * to allow dehardcoding it in the XML and doing proper substitutions everywhere.
  4512. */
  4513. String DTR(const String &p_text, const String &p_context) {
  4514. // Comes straight from the XML, so remove indentation and any trailing whitespace.
  4515. const String text = p_text.dedent().strip_edges();
  4516. if (TranslationServer::get_singleton()) {
  4517. return String(TranslationServer::get_singleton()->doc_translate(text, p_context)).replace("$DOCS_URL", VERSION_DOCS_URL);
  4518. }
  4519. return text.replace("$DOCS_URL", VERSION_DOCS_URL);
  4520. }
  4521. /**
  4522. * "Docs TRanslate for N items". Used for the editor class reference documentation
  4523. * (with support for plurals), handling descriptions extracted from the XML.
  4524. * It also replaces `$DOCS_URL` with the actual URL to the documentation's branch,
  4525. * to allow dehardcoding it in the XML and doing proper substitutions everywhere.
  4526. */
  4527. String DTRN(const String &p_text, const String &p_text_plural, int p_n, const String &p_context) {
  4528. const String text = p_text.dedent().strip_edges();
  4529. const String text_plural = p_text_plural.dedent().strip_edges();
  4530. if (TranslationServer::get_singleton()) {
  4531. return String(TranslationServer::get_singleton()->doc_translate_plural(text, text_plural, p_n, p_context)).replace("$DOCS_URL", VERSION_DOCS_URL);
  4532. }
  4533. // Return message based on English plural rule if translation is not possible.
  4534. if (p_n == 1) {
  4535. return text.replace("$DOCS_URL", VERSION_DOCS_URL);
  4536. }
  4537. return text_plural.replace("$DOCS_URL", VERSION_DOCS_URL);
  4538. }
  4539. #endif
  4540. /**
  4541. * "Run-time TRanslate". Performs string replacement for internationalization
  4542. * within a running project. The translation string must be supplied by the
  4543. * project, as Godot does not provide built-in translations for `RTR()` strings
  4544. * to keep binary size low. A translation context can optionally be specified to
  4545. * disambiguate between identical source strings in translations. When
  4546. * placeholders are desired, use `vformat(RTR("Example: %s"), some_string)`.
  4547. * If a string mentions a quantity (and may therefore need a dynamic plural form),
  4548. * use `RTRN()` instead of `RTR()`.
  4549. *
  4550. * NOTE: Do not use `RTR()` in editor-only code (typically within the `editor/`
  4551. * folder). For editor translations, use `TTR()` instead.
  4552. */
  4553. String RTR(const String &p_text, const String &p_context) {
  4554. if (TranslationServer::get_singleton()) {
  4555. String rtr = TranslationServer::get_singleton()->tool_translate(p_text, p_context);
  4556. if (rtr.is_empty() || rtr == p_text) {
  4557. return TranslationServer::get_singleton()->translate(p_text, p_context);
  4558. } else {
  4559. return rtr;
  4560. }
  4561. }
  4562. return p_text;
  4563. }
  4564. /**
  4565. * "Run-time TRanslate for N items". Performs string replacement for
  4566. * internationalization within a running project. The translation string must be
  4567. * supplied by the project, as Godot does not provide built-in translations for
  4568. * `RTRN()` strings to keep binary size low. A translation context can
  4569. * optionally be specified to disambiguate between identical source strings in
  4570. * translations. Use `RTR()` if the string doesn't need dynamic plural form.
  4571. * When placeholders are desired, use
  4572. * `vformat(RTRN("%d item", "%d items", some_integer), some_integer)`.
  4573. * The placeholder must be present in both strings to avoid run-time warnings in `vformat()`.
  4574. *
  4575. * NOTE: Do not use `RTRN()` in editor-only code (typically within the `editor/`
  4576. * folder). For editor translations, use `TTRN()` instead.
  4577. */
  4578. String RTRN(const String &p_text, const String &p_text_plural, int p_n, const String &p_context) {
  4579. if (TranslationServer::get_singleton()) {
  4580. String rtr = TranslationServer::get_singleton()->tool_translate_plural(p_text, p_text_plural, p_n, p_context);
  4581. if (rtr.is_empty() || rtr == p_text || rtr == p_text_plural) {
  4582. return TranslationServer::get_singleton()->translate_plural(p_text, p_text_plural, p_n, p_context);
  4583. } else {
  4584. return rtr;
  4585. }
  4586. }
  4587. // Return message based on English plural rule if translation is not possible.
  4588. if (p_n == 1) {
  4589. return p_text;
  4590. }
  4591. return p_text_plural;
  4592. }