ustring.cpp 119 KB

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