ustring.cpp 111 KB

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