ustring.cpp 113 KB

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