ustring.cpp 103 KB

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