ustring.cpp 103 KB

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