ustring.cpp 119 KB

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