ustring.cpp 115 KB

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