ustring.cpp 113 KB

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