ustring.cpp 77 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008
  1. /*************************************************************************/
  2. /* ustring.cpp */
  3. /*************************************************************************/
  4. /* This file is part of: */
  5. /* GODOT ENGINE */
  6. /* https://godotengine.org */
  7. /*************************************************************************/
  8. /* Copyright (c) 2007-2017 Juan Linietsky, Ariel Manzur. */
  9. /* Copyright (c) 2014-2017 Godot Engine contributors (cf. AUTHORS.md) */
  10. /* */
  11. /* Permission is hereby granted, free of charge, to any person obtaining */
  12. /* a copy of this software and associated documentation files (the */
  13. /* "Software"), to deal in the Software without restriction, including */
  14. /* without limitation the rights to use, copy, modify, merge, publish, */
  15. /* distribute, sublicense, and/or sell copies of the Software, and to */
  16. /* permit persons to whom the Software is furnished to do so, subject to */
  17. /* the following conditions: */
  18. /* */
  19. /* The above copyright notice and this permission notice shall be */
  20. /* included in all copies or substantial portions of the Software. */
  21. /* */
  22. /* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, */
  23. /* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF */
  24. /* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.*/
  25. /* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY */
  26. /* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, */
  27. /* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE */
  28. /* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */
  29. /*************************************************************************/
  30. #include "ustring.h"
  31. #include "color.h"
  32. #include "math_funcs.h"
  33. #include "os/memory.h"
  34. #include "print_string.h"
  35. #include "ucaps.h"
  36. #include "variant.h"
  37. #include "thirdparty/misc/md5.h"
  38. #include "thirdparty/misc/sha256.h"
  39. #include <wchar.h>
  40. #ifndef NO_USE_STDLIB
  41. #include <stdio.h>
  42. #include <stdlib.h>
  43. #endif
  44. #if defined(MINGW_ENABLED) || defined(_MSC_VER)
  45. #define snprintf _snprintf
  46. #endif
  47. #define MAX_DIGITS 6
  48. #define UPPERCASE(m_c) (((m_c) >= 'a' && (m_c) <= 'z') ? ((m_c) - ('a' - 'A')) : (m_c))
  49. #define LOWERCASE(m_c) (((m_c) >= 'A' && (m_c) <= 'Z') ? ((m_c) + ('a' - 'A')) : (m_c))
  50. #define IS_DIGIT(m_d) ((m_d) >= '0' && (m_d) <= '9')
  51. #define IS_HEX_DIGIT(m_d) (((m_d) >= '0' && (m_d) <= '9') || ((m_d) >= 'a' && (m_d) <= 'f') || ((m_d) >= 'A' && (m_d) <= 'F'))
  52. /** STRING **/
  53. bool CharString::operator<(const CharString &p_right) const {
  54. if (length() == 0) {
  55. return p_right.length() != 0;
  56. }
  57. const char *this_str = get_data();
  58. const char *that_str = p_right.get_data();
  59. while (true) {
  60. if (*that_str == 0 && *this_str == 0)
  61. return false; //this can't be equal, sadly
  62. else if (*this_str == 0)
  63. return true; //if this is empty, and the other one is not, then we're less.. I think?
  64. else if (*that_str == 0)
  65. return false; //otherwise the other one is smaller..
  66. else if (*this_str < *that_str) //more than
  67. return true;
  68. else if (*this_str > *that_str) //less than
  69. return false;
  70. this_str++;
  71. that_str++;
  72. }
  73. return false; //should never reach here anyway
  74. }
  75. const char *CharString::get_data() const {
  76. if (size())
  77. return &operator[](0);
  78. else
  79. return "";
  80. }
  81. void String::copy_from(const char *p_cstr) {
  82. if (!p_cstr) {
  83. resize(0);
  84. return;
  85. }
  86. int len = 0;
  87. const char *ptr = p_cstr;
  88. while (*(ptr++) != 0)
  89. len++;
  90. if (len == 0) {
  91. resize(0);
  92. return;
  93. }
  94. resize(len + 1); // include 0
  95. CharType *dst = this->ptrw();
  96. for (int i = 0; i < len + 1; i++) {
  97. dst[i] = p_cstr[i];
  98. }
  99. }
  100. void String::copy_from(const CharType *p_cstr, int p_clip_to) {
  101. if (!p_cstr) {
  102. resize(0);
  103. return;
  104. }
  105. int len = 0;
  106. const CharType *ptr = p_cstr;
  107. while (*(ptr++) != 0)
  108. len++;
  109. if (p_clip_to >= 0 && len > p_clip_to)
  110. len = p_clip_to;
  111. if (len == 0) {
  112. resize(0);
  113. return;
  114. }
  115. resize(len + 1);
  116. set(len, 0);
  117. CharType *dst = &operator[](0);
  118. for (int i = 0; i < len; i++) {
  119. dst[i] = p_cstr[i];
  120. }
  121. }
  122. void String::copy_from(const CharType &p_char) {
  123. resize(2);
  124. set(0, p_char);
  125. set(1, 0);
  126. }
  127. bool String::operator==(const String &p_str) const {
  128. if (length() != p_str.length())
  129. return false;
  130. if (empty())
  131. return true;
  132. int l = length();
  133. const CharType *src = c_str();
  134. const CharType *dst = p_str.c_str();
  135. /* Compare char by char */
  136. for (int i = 0; i < l; i++) {
  137. if (src[i] != dst[i])
  138. return false;
  139. }
  140. return true;
  141. }
  142. bool String::operator!=(const String &p_str) const {
  143. return !(*this == p_str);
  144. }
  145. String String::operator+(const String &p_str) const {
  146. String res = *this;
  147. res += p_str;
  148. return res;
  149. }
  150. /*
  151. String String::operator+(CharType p_chr) const {
  152. String res=*this;
  153. res+=p_chr;
  154. return res;
  155. }
  156. */
  157. String &String::operator+=(const String &p_str) {
  158. if (empty()) {
  159. *this = p_str;
  160. return *this;
  161. }
  162. if (p_str.empty())
  163. return *this;
  164. int from = length();
  165. resize(length() + p_str.size());
  166. const CharType *src = p_str.c_str();
  167. CharType *dst = &operator[](0);
  168. set(length(), 0);
  169. for (int i = 0; i < p_str.length(); i++)
  170. dst[from + i] = src[i];
  171. return *this;
  172. }
  173. String &String::operator+=(const CharType *p_str) {
  174. *this += String(p_str);
  175. return *this;
  176. }
  177. String &String::operator+=(CharType p_char) {
  178. resize(size() ? size() + 1 : 2);
  179. set(length(), 0);
  180. set(length() - 1, p_char);
  181. return *this;
  182. }
  183. String &String::operator+=(const char *p_str) {
  184. if (!p_str || p_str[0] == 0)
  185. return *this;
  186. int src_len = 0;
  187. const char *ptr = p_str;
  188. while (*(ptr++) != 0)
  189. src_len++;
  190. int from = length();
  191. resize(from + src_len + 1);
  192. CharType *dst = &operator[](0);
  193. set(length(), 0);
  194. for (int i = 0; i < src_len; i++)
  195. dst[from + i] = p_str[i];
  196. return *this;
  197. }
  198. void String::operator=(const char *p_str) {
  199. copy_from(p_str);
  200. }
  201. void String::operator=(const CharType *p_str) {
  202. copy_from(p_str);
  203. }
  204. bool String::operator==(const StrRange &p_str_range) const {
  205. int len = p_str_range.len;
  206. if (length() != len)
  207. return false;
  208. if (empty())
  209. return true;
  210. const CharType *c_str = p_str_range.c_str;
  211. const CharType *dst = &operator[](0);
  212. /* Compare char by char */
  213. for (int i = 0; i < len; i++) {
  214. if (c_str[i] != dst[i])
  215. return false;
  216. }
  217. return true;
  218. }
  219. bool String::operator==(const char *p_str) const {
  220. int len = 0;
  221. const char *aux = p_str;
  222. while (*(aux++) != 0)
  223. len++;
  224. if (length() != len)
  225. return false;
  226. if (empty())
  227. return true;
  228. int l = length();
  229. const CharType *dst = c_str();
  230. /* Compare char by char */
  231. for (int i = 0; i < l; i++) {
  232. if (p_str[i] != dst[i])
  233. return false;
  234. }
  235. return true;
  236. }
  237. bool String::operator==(const CharType *p_str) const {
  238. int len = 0;
  239. const CharType *aux = p_str;
  240. while (*(aux++) != 0)
  241. len++;
  242. if (length() != len)
  243. return false;
  244. if (empty())
  245. return true;
  246. int l = length();
  247. const CharType *dst = c_str();
  248. /* Compare char by char */
  249. for (int i = 0; i < l; i++) {
  250. if (p_str[i] != dst[i])
  251. return false;
  252. }
  253. return true;
  254. }
  255. bool String::operator!=(const char *p_str) const {
  256. return (!(*this == p_str));
  257. }
  258. bool String::operator!=(const CharType *p_str) const {
  259. return (!(*this == p_str));
  260. }
  261. bool String::operator<(const CharType *p_str) const {
  262. if (empty() && p_str[0] == 0)
  263. return false;
  264. if (empty())
  265. return true;
  266. const CharType *this_str = c_str();
  267. while (true) {
  268. if (*p_str == 0 && *this_str == 0)
  269. return false; //this can't be equal, sadly
  270. else if (*this_str == 0)
  271. return true; //if this is empty, and the other one is not, then we're less.. I think?
  272. else if (*p_str == 0)
  273. return false; //otherwise the other one is smaller..
  274. else if (*this_str < *p_str) //more than
  275. return true;
  276. else if (*this_str > *p_str) //less than
  277. return false;
  278. this_str++;
  279. p_str++;
  280. }
  281. return false; //should never reach here anyway
  282. }
  283. bool String::operator<=(String p_str) const {
  284. return (*this < p_str) || (*this == p_str);
  285. }
  286. bool String::operator<(const char *p_str) const {
  287. if (empty() && p_str[0] == 0)
  288. return false;
  289. if (empty())
  290. return true;
  291. const CharType *this_str = c_str();
  292. while (true) {
  293. if (*p_str == 0 && *this_str == 0)
  294. return false; //this can't be equal, sadly
  295. else if (*this_str == 0)
  296. return true; //if this is empty, and the other one is not, then we're less.. I think?
  297. else if (*p_str == 0)
  298. return false; //otherwise the other one is smaller..
  299. else if (*this_str < *p_str) //more than
  300. return true;
  301. else if (*this_str > *p_str) //less than
  302. return false;
  303. this_str++;
  304. p_str++;
  305. }
  306. return false; //should never reach here anyway
  307. }
  308. bool String::operator<(String p_str) const {
  309. return operator<(p_str.c_str());
  310. }
  311. signed char String::nocasecmp_to(const String &p_str) const {
  312. if (empty() && p_str.empty())
  313. return 0;
  314. if (empty())
  315. return -1;
  316. if (p_str.empty())
  317. return 1;
  318. const CharType *that_str = p_str.c_str();
  319. const CharType *this_str = c_str();
  320. while (true) {
  321. if (*that_str == 0 && *this_str == 0)
  322. return 0; //we're equal
  323. else if (*this_str == 0)
  324. return -1; //if this is empty, and the other one is not, then we're less.. I think?
  325. else if (*that_str == 0)
  326. return 1; //otherwise the other one is smaller..
  327. else if (_find_upper(*this_str) < _find_upper(*that_str)) //more than
  328. return -1;
  329. else if (_find_upper(*this_str) > _find_upper(*that_str)) //less than
  330. return 1;
  331. this_str++;
  332. that_str++;
  333. }
  334. return 0; //should never reach anyway
  335. }
  336. signed char String::casecmp_to(const String &p_str) const {
  337. if (empty() && p_str.empty())
  338. return 0;
  339. if (empty())
  340. return -1;
  341. if (p_str.empty())
  342. return 1;
  343. const CharType *that_str = p_str.c_str();
  344. const CharType *this_str = c_str();
  345. while (true) {
  346. if (*that_str == 0 && *this_str == 0)
  347. return 0; //we're equal
  348. else if (*this_str == 0)
  349. return -1; //if this is empty, and the other one is not, then we're less.. I think?
  350. else if (*that_str == 0)
  351. return 1; //otherwise the other one is smaller..
  352. else if (*this_str < *that_str) //more than
  353. return -1;
  354. else if (*this_str > *that_str) //less than
  355. return 1;
  356. this_str++;
  357. that_str++;
  358. }
  359. return 0; //should never reach anyway
  360. }
  361. signed char String::naturalnocasecmp_to(const String &p_str) const {
  362. const CharType *this_str = c_str();
  363. const CharType *that_str = p_str.c_str();
  364. if (this_str && that_str) {
  365. while (*this_str == '.' || *that_str == '.') {
  366. if (*this_str++ != '.')
  367. return 1;
  368. if (*that_str++ != '.')
  369. return -1;
  370. if (!*that_str)
  371. return 1;
  372. if (!*this_str)
  373. return -1;
  374. }
  375. while (*this_str) {
  376. if (!*that_str)
  377. return 1;
  378. else if (IS_DIGIT(*this_str)) {
  379. int64_t this_int, that_int;
  380. if (!IS_DIGIT(*that_str))
  381. return -1;
  382. /* Compare the numbers */
  383. this_int = to_int(this_str);
  384. that_int = to_int(that_str);
  385. if (this_int < that_int)
  386. return -1;
  387. else if (this_int > that_int)
  388. return 1;
  389. /* Skip */
  390. while (IS_DIGIT(*this_str))
  391. this_str++;
  392. while (IS_DIGIT(*that_str))
  393. that_str++;
  394. } else if (IS_DIGIT(*that_str))
  395. return 1;
  396. else {
  397. if (_find_upper(*this_str) < _find_upper(*that_str)) //more than
  398. return -1;
  399. else if (_find_upper(*this_str) > _find_upper(*that_str)) //less than
  400. return 1;
  401. this_str++;
  402. that_str++;
  403. }
  404. }
  405. if (*that_str)
  406. return -1;
  407. }
  408. return 0;
  409. }
  410. void String::erase(int p_pos, int p_chars) {
  411. *this = left(p_pos) + substr(p_pos + p_chars, length() - ((p_pos + p_chars)));
  412. }
  413. String String::capitalize() const {
  414. String aux = this->camelcase_to_underscore(true).replace("_", " ").strip_edges();
  415. String cap;
  416. for (int i = 0; i < aux.get_slice_count(" "); i++) {
  417. String slice = aux.get_slicec(' ', i);
  418. if (slice.length() > 0) {
  419. slice[0] = _find_upper(slice[0]);
  420. if (i > 0)
  421. cap += " ";
  422. cap += slice;
  423. }
  424. }
  425. return cap;
  426. }
  427. String String::camelcase_to_underscore(bool lowercase) const {
  428. const CharType *cstr = c_str();
  429. String new_string;
  430. const char A = 'A', Z = 'Z';
  431. const char a = 'a', z = 'z';
  432. int start_index = 0;
  433. for (int i = 1; i < this->size(); i++) {
  434. bool is_upper = cstr[i] >= A && cstr[i] <= Z;
  435. bool is_number = cstr[i] >= '0' && cstr[i] <= '9';
  436. bool are_next_2_lower = false;
  437. bool was_precedent_upper = cstr[i - 1] >= A && cstr[i - 1] <= Z;
  438. bool was_precedent_number = cstr[i - 1] >= '0' && cstr[i - 1] <= '9';
  439. if (i + 2 < this->size()) {
  440. are_next_2_lower = cstr[i + 1] >= a && cstr[i + 1] <= z && cstr[i + 2] >= a && cstr[i + 2] <= z;
  441. }
  442. bool should_split = ((is_upper && !was_precedent_upper && !was_precedent_number) || (was_precedent_upper && is_upper && are_next_2_lower) || (is_number && !was_precedent_number));
  443. if (should_split) {
  444. new_string += this->substr(start_index, i - start_index) + "_";
  445. start_index = i;
  446. }
  447. }
  448. new_string += this->substr(start_index, this->size() - start_index);
  449. return lowercase ? new_string.to_lower() : new_string;
  450. }
  451. int String::get_slice_count(String p_splitter) const {
  452. if (empty())
  453. return 0;
  454. if (p_splitter.empty())
  455. return 0;
  456. int pos = 0;
  457. int slices = 1;
  458. while ((pos = find(p_splitter, pos)) >= 0) {
  459. slices++;
  460. pos += p_splitter.length();
  461. }
  462. return slices;
  463. }
  464. String String::get_slice(String p_splitter, int p_slice) const {
  465. if (empty() || p_splitter.empty())
  466. return "";
  467. int pos = 0;
  468. int prev_pos = 0;
  469. //int slices=1;
  470. if (p_slice < 0)
  471. return "";
  472. if (find(p_splitter) == -1)
  473. return *this;
  474. int i = 0;
  475. while (true) {
  476. pos = find(p_splitter, pos);
  477. if (pos == -1)
  478. pos = length(); //reached end
  479. int from = prev_pos;
  480. //int to=pos;
  481. if (p_slice == i) {
  482. return substr(from, pos - from);
  483. }
  484. if (pos == length()) //reached end and no find
  485. break;
  486. pos += p_splitter.length();
  487. prev_pos = pos;
  488. i++;
  489. }
  490. return ""; //no find!
  491. }
  492. String String::get_slicec(CharType p_splitter, int p_slice) const {
  493. if (empty())
  494. return String();
  495. if (p_slice < 0)
  496. return String();
  497. const CharType *c = this->ptr();
  498. int i = 0;
  499. int prev = 0;
  500. int count = 0;
  501. while (true) {
  502. if (c[i] == 0 || c[i] == p_splitter) {
  503. if (p_slice == count) {
  504. return substr(prev, i - prev);
  505. } else if (c[i] == 0) {
  506. return String();
  507. } else {
  508. count++;
  509. prev = i + 1;
  510. }
  511. }
  512. i++;
  513. }
  514. return String(); //no find!
  515. }
  516. Vector<String> String::split_spaces() const {
  517. Vector<String> ret;
  518. int from = 0;
  519. int i = 0;
  520. int len = length();
  521. bool inside = false;
  522. while (true) {
  523. bool empty = operator[](i) < 33;
  524. if (i == 0)
  525. inside = !empty;
  526. if (!empty && !inside) {
  527. inside = true;
  528. from = i;
  529. }
  530. if (empty && inside) {
  531. ret.push_back(substr(from, i - from));
  532. inside = false;
  533. }
  534. if (i == len)
  535. break;
  536. i++;
  537. }
  538. return ret;
  539. }
  540. Vector<String> String::split(const String &p_splitter, bool p_allow_empty) const {
  541. Vector<String> ret;
  542. int from = 0;
  543. int len = length();
  544. while (true) {
  545. int end = find(p_splitter, from);
  546. if (end < 0)
  547. end = len;
  548. if (p_allow_empty || (end > from))
  549. ret.push_back(substr(from, end - from));
  550. if (end == len)
  551. break;
  552. from = end + p_splitter.length();
  553. }
  554. return ret;
  555. }
  556. Vector<float> String::split_floats(const String &p_splitter, bool p_allow_empty) const {
  557. Vector<float> ret;
  558. int from = 0;
  559. int len = length();
  560. while (true) {
  561. int end = find(p_splitter, from);
  562. if (end < 0)
  563. end = len;
  564. if (p_allow_empty || (end > from))
  565. ret.push_back(String::to_double(&c_str()[from]));
  566. if (end == len)
  567. break;
  568. from = end + p_splitter.length();
  569. }
  570. return ret;
  571. }
  572. Vector<float> String::split_floats_mk(const Vector<String> &p_splitters, bool p_allow_empty) const {
  573. Vector<float> ret;
  574. int from = 0;
  575. int len = length();
  576. while (true) {
  577. int idx;
  578. int end = findmk(p_splitters, from, &idx);
  579. int spl_len = 1;
  580. if (end < 0) {
  581. end = len;
  582. } else {
  583. spl_len = p_splitters[idx].length();
  584. }
  585. if (p_allow_empty || (end > from)) {
  586. ret.push_back(String::to_double(&c_str()[from]));
  587. }
  588. if (end == len)
  589. break;
  590. from = end + spl_len;
  591. }
  592. return ret;
  593. }
  594. Vector<int> String::split_ints(const String &p_splitter, bool p_allow_empty) const {
  595. Vector<int> ret;
  596. int from = 0;
  597. int len = length();
  598. while (true) {
  599. int end = find(p_splitter, from);
  600. if (end < 0)
  601. end = len;
  602. if (p_allow_empty || (end > from))
  603. ret.push_back(String::to_int(&c_str()[from], end - from));
  604. if (end == len)
  605. break;
  606. from = end + p_splitter.length();
  607. }
  608. return ret;
  609. }
  610. Vector<int> String::split_ints_mk(const Vector<String> &p_splitters, bool p_allow_empty) const {
  611. Vector<int> ret;
  612. int from = 0;
  613. int len = length();
  614. while (true) {
  615. int idx;
  616. int end = findmk(p_splitters, from, &idx);
  617. int spl_len = 1;
  618. if (end < 0) {
  619. end = len;
  620. } else {
  621. spl_len = p_splitters[idx].length();
  622. }
  623. if (p_allow_empty || (end > from))
  624. ret.push_back(String::to_int(&c_str()[from], end - from));
  625. if (end == len)
  626. break;
  627. from = end + spl_len;
  628. }
  629. return ret;
  630. }
  631. String String::join(Vector<String> parts) {
  632. String ret;
  633. for (int i = 0; i < parts.size(); ++i) {
  634. if (i > 0) {
  635. ret += *this;
  636. }
  637. ret += parts[i];
  638. }
  639. return ret;
  640. }
  641. CharType String::char_uppercase(CharType p_char) {
  642. return _find_upper(p_char);
  643. }
  644. CharType String::char_lowercase(CharType p_char) {
  645. return _find_lower(p_char);
  646. }
  647. String String::to_upper() const {
  648. String upper = *this;
  649. for (int i = 0; i < upper.size(); i++) {
  650. upper[i] = _find_upper(upper[i]);
  651. }
  652. return upper;
  653. }
  654. String String::to_lower() const {
  655. String upper = *this;
  656. for (int i = 0; i < upper.size(); i++) {
  657. upper[i] = _find_lower(upper[i]);
  658. }
  659. return upper;
  660. }
  661. int String::length() const {
  662. int s = size();
  663. return s ? (s - 1) : 0; // length does not include zero
  664. }
  665. const CharType *String::c_str() const {
  666. static const CharType zero = 0;
  667. return size() ? &operator[](0) : &zero;
  668. }
  669. String String::md5(const uint8_t *p_md5) {
  670. return String::hex_encode_buffer(p_md5, 16);
  671. }
  672. String String::hex_encode_buffer(const uint8_t *p_buffer, int p_len) {
  673. static const char hex[16] = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f' };
  674. String ret;
  675. char v[2] = { 0, 0 };
  676. for (int i = 0; i < p_len; i++) {
  677. v[0] = hex[p_buffer[i] >> 4];
  678. ret += v;
  679. v[0] = hex[p_buffer[i] & 0xF];
  680. ret += v;
  681. }
  682. return ret;
  683. }
  684. String String::chr(CharType p_char) {
  685. CharType c[2] = { p_char, 0 };
  686. return String(c);
  687. }
  688. String String::num(double p_num, int p_decimals) {
  689. #ifndef NO_USE_STDLIB
  690. if (p_decimals > 12)
  691. p_decimals = 12;
  692. char fmt[7];
  693. fmt[0] = '%';
  694. fmt[1] = '.';
  695. if (p_decimals < 0) {
  696. fmt[1] = 'l';
  697. fmt[2] = 'f';
  698. fmt[3] = 0;
  699. } else if (p_decimals < 10) {
  700. fmt[2] = '0' + p_decimals;
  701. fmt[3] = 'l';
  702. fmt[4] = 'f';
  703. fmt[5] = 0;
  704. } else {
  705. fmt[2] = '0' + (p_decimals / 10);
  706. fmt[3] = '0' + (p_decimals % 10);
  707. fmt[4] = 'l';
  708. fmt[5] = 'f';
  709. fmt[6] = 0;
  710. }
  711. char buf[256];
  712. #if defined(__GNUC__) || defined(_MSC_VER)
  713. snprintf(buf, 256, fmt, p_num);
  714. #else
  715. sprintf(buf, fmt, p_num);
  716. #endif
  717. buf[255] = 0;
  718. //destroy trailing zeroes
  719. {
  720. bool period = false;
  721. int z = 0;
  722. while (buf[z]) {
  723. if (buf[z] == '.')
  724. period = true;
  725. z++;
  726. }
  727. if (period) {
  728. z--;
  729. while (z > 0) {
  730. if (buf[z] == '0') {
  731. buf[z] = 0;
  732. } else if (buf[z] == '.') {
  733. buf[z] = 0;
  734. break;
  735. } else {
  736. break;
  737. }
  738. z--;
  739. }
  740. }
  741. }
  742. return buf;
  743. #else
  744. String s;
  745. String sd;
  746. /* integer part */
  747. bool neg = p_num < 0;
  748. p_num = ABS(p_num);
  749. int intn = (int)p_num;
  750. /* decimal part */
  751. if (p_decimals > 0 || (p_decimals == -1 && (int)p_num != p_num)) {
  752. double dec = p_num - (float)((int)p_num);
  753. int digit = 0;
  754. if (p_decimals > MAX_DIGITS)
  755. p_decimals = MAX_DIGITS;
  756. int dec_int = 0;
  757. int dec_max = 0;
  758. while (true) {
  759. dec *= 10.0;
  760. dec_int = dec_int * 10 + (int)dec % 10;
  761. dec_max = dec_max * 10 + 9;
  762. digit++;
  763. if (p_decimals == -1) {
  764. if (digit == MAX_DIGITS) //no point in going to infinite
  765. break;
  766. if ((dec - (float)((int)dec)) < 1e-6)
  767. break;
  768. }
  769. if (digit == p_decimals)
  770. break;
  771. }
  772. dec *= 10;
  773. int last = (int)dec % 10;
  774. if (last > 5) {
  775. if (dec_int == dec_max) {
  776. dec_int = 0;
  777. intn++;
  778. } else {
  779. dec_int++;
  780. }
  781. }
  782. String decimal;
  783. for (int i = 0; i < digit; i++) {
  784. char num[2] = { 0, 0 };
  785. num[0] = '0' + dec_int % 10;
  786. decimal = num + decimal;
  787. dec_int /= 10;
  788. }
  789. sd = '.' + decimal;
  790. }
  791. if (intn == 0)
  792. s = "0";
  793. else {
  794. while (intn) {
  795. CharType num = '0' + (intn % 10);
  796. intn /= 10;
  797. s = num + s;
  798. }
  799. }
  800. s = s + sd;
  801. if (neg)
  802. s = "-" + s;
  803. return s;
  804. #endif
  805. }
  806. String String::num_int64(int64_t p_num, int base, bool capitalize_hex) {
  807. bool sign = p_num < 0;
  808. int64_t num = ABS(p_num);
  809. int64_t n = num;
  810. int chars = 0;
  811. do {
  812. n /= base;
  813. chars++;
  814. } while (n);
  815. if (sign)
  816. chars++;
  817. String s;
  818. s.resize(chars + 1);
  819. CharType *c = s.ptrw();
  820. c[chars] = 0;
  821. n = num;
  822. do {
  823. int mod = n % base;
  824. if (mod >= 10) {
  825. char a = (capitalize_hex ? 'A' : 'a');
  826. c[--chars] = a + (mod - 10);
  827. } else {
  828. c[--chars] = '0' + mod;
  829. }
  830. n /= base;
  831. } while (n);
  832. if (sign)
  833. c[0] = '-';
  834. return s;
  835. }
  836. String String::num_real(double p_num) {
  837. String s;
  838. String sd;
  839. /* integer part */
  840. bool neg = p_num < 0;
  841. p_num = ABS(p_num);
  842. int intn = (int)p_num;
  843. /* decimal part */
  844. if ((int)p_num != p_num) {
  845. double dec = p_num - (float)((int)p_num);
  846. int digit = 0;
  847. int decimals = MAX_DIGITS;
  848. int dec_int = 0;
  849. int dec_max = 0;
  850. while (true) {
  851. dec *= 10.0;
  852. dec_int = dec_int * 10 + (int)dec % 10;
  853. dec_max = dec_max * 10 + 9;
  854. digit++;
  855. if ((dec - (float)((int)dec)) < 1e-6)
  856. break;
  857. if (digit == decimals)
  858. break;
  859. }
  860. dec *= 10;
  861. int last = (int)dec % 10;
  862. if (last > 5) {
  863. if (dec_int == dec_max) {
  864. dec_int = 0;
  865. intn++;
  866. } else {
  867. dec_int++;
  868. }
  869. }
  870. String decimal;
  871. for (int i = 0; i < digit; i++) {
  872. char num[2] = { 0, 0 };
  873. num[0] = '0' + dec_int % 10;
  874. decimal = num + decimal;
  875. dec_int /= 10;
  876. }
  877. sd = '.' + decimal;
  878. } else {
  879. sd = ".0";
  880. }
  881. if (intn == 0)
  882. s = "0";
  883. else {
  884. while (intn) {
  885. CharType num = '0' + (intn % 10);
  886. intn /= 10;
  887. s = num + s;
  888. }
  889. }
  890. s = s + sd;
  891. if (neg)
  892. s = "-" + s;
  893. return s;
  894. }
  895. String String::num_scientific(double p_num) {
  896. #ifndef NO_USE_STDLIB
  897. char buf[256];
  898. #if defined(__GNUC__) || defined(_MSC_VER)
  899. snprintf(buf, 256, "%lg", p_num);
  900. #else
  901. sprintf(buf, "%.16lg", p_num);
  902. #endif
  903. buf[255] = 0;
  904. return buf;
  905. #else
  906. return String::num(p_num);
  907. #endif
  908. }
  909. CharString String::ascii(bool p_allow_extended) const {
  910. if (!length())
  911. return CharString();
  912. CharString cs;
  913. cs.resize(size());
  914. for (int i = 0; i < size(); i++)
  915. cs[i] = operator[](i);
  916. return cs;
  917. }
  918. String String::utf8(const char *p_utf8, int p_len) {
  919. String ret;
  920. ret.parse_utf8(p_utf8, p_len);
  921. return ret;
  922. };
  923. bool String::parse_utf8(const char *p_utf8, int p_len) {
  924. #define _UNICERROR(m_err) print_line("unicode error: " + String(m_err));
  925. String aux;
  926. int cstr_size = 0;
  927. int str_size = 0;
  928. /* HANDLE BOM (Byte Order Mark) */
  929. if (p_len < 0 || p_len >= 3) {
  930. bool has_bom = uint8_t(p_utf8[0]) == 0xEF && uint8_t(p_utf8[1]) == 0xBB && uint8_t(p_utf8[2]) == 0xBF;
  931. if (has_bom) {
  932. //just skip it
  933. if (p_len >= 0)
  934. p_len -= 3;
  935. p_utf8 += 3;
  936. }
  937. }
  938. {
  939. const char *ptrtmp = p_utf8;
  940. const char *ptrtmp_limit = &p_utf8[p_len];
  941. int skip = 0;
  942. while (ptrtmp != ptrtmp_limit && *ptrtmp) {
  943. if (skip == 0) {
  944. uint8_t c = *ptrtmp;
  945. /* Determine the number of characters in sequence */
  946. if ((c & 0x80) == 0)
  947. skip = 0;
  948. else if ((c & 0xE0) == 0xC0)
  949. skip = 1;
  950. else if ((c & 0xF0) == 0xE0)
  951. skip = 2;
  952. else if ((c & 0xF8) == 0xF0)
  953. skip = 3;
  954. else if ((c & 0xFC) == 0xF8)
  955. skip = 4;
  956. else if ((c & 0xFE) == 0xFC)
  957. skip = 5;
  958. else {
  959. _UNICERROR("invalid skip");
  960. return true; //invalid utf8
  961. }
  962. if (skip == 1 && (c & 0x1E) == 0) {
  963. //printf("overlong rejected\n");
  964. _UNICERROR("overlong rejected");
  965. return true; //reject overlong
  966. }
  967. str_size++;
  968. } else {
  969. --skip;
  970. }
  971. cstr_size++;
  972. ptrtmp++;
  973. }
  974. if (skip) {
  975. _UNICERROR("no space left");
  976. return true; //not enough spac
  977. }
  978. }
  979. if (str_size == 0) {
  980. clear();
  981. return false;
  982. }
  983. resize(str_size + 1);
  984. CharType *dst = &operator[](0);
  985. dst[str_size] = 0;
  986. while (cstr_size) {
  987. int len = 0;
  988. /* Determine the number of characters in sequence */
  989. if ((*p_utf8 & 0x80) == 0)
  990. len = 1;
  991. else if ((*p_utf8 & 0xE0) == 0xC0)
  992. len = 2;
  993. else if ((*p_utf8 & 0xF0) == 0xE0)
  994. len = 3;
  995. else if ((*p_utf8 & 0xF8) == 0xF0)
  996. len = 4;
  997. else if ((*p_utf8 & 0xFC) == 0xF8)
  998. len = 5;
  999. else if ((*p_utf8 & 0xFE) == 0xFC)
  1000. len = 6;
  1001. else {
  1002. _UNICERROR("invalid len");
  1003. return true; //invalid UTF8
  1004. }
  1005. if (len > cstr_size) {
  1006. _UNICERROR("no space left");
  1007. return true; //not enough space
  1008. }
  1009. if (len == 2 && (*p_utf8 & 0x1E) == 0) {
  1010. //printf("overlong rejected\n");
  1011. _UNICERROR("no space left");
  1012. return true; //reject overlong
  1013. }
  1014. /* Convert the first character */
  1015. uint32_t unichar = 0;
  1016. if (len == 1)
  1017. unichar = *p_utf8;
  1018. else {
  1019. unichar = (0xFF >> (len + 1)) & *p_utf8;
  1020. for (int i = 1; i < len; i++) {
  1021. if ((p_utf8[i] & 0xC0) != 0x80) {
  1022. _UNICERROR("invalid utf8");
  1023. return true; //invalid utf8
  1024. }
  1025. if (unichar == 0 && i == 2 && ((p_utf8[i] & 0x7F) >> (7 - len)) == 0) {
  1026. _UNICERROR("invalid utf8 overlong");
  1027. return true; //no overlong
  1028. }
  1029. unichar = (unichar << 6) | (p_utf8[i] & 0x3F);
  1030. }
  1031. }
  1032. //printf("char %i, len %i\n",unichar,len);
  1033. if (sizeof(wchar_t) == 2 && unichar > 0xFFFF) {
  1034. unichar = ' '; //too long for windows
  1035. }
  1036. *(dst++) = unichar;
  1037. cstr_size -= len;
  1038. p_utf8 += len;
  1039. }
  1040. return false;
  1041. }
  1042. CharString String::utf8() const {
  1043. int l = length();
  1044. if (!l)
  1045. return CharString();
  1046. const CharType *d = &operator[](0);
  1047. int fl = 0;
  1048. for (int i = 0; i < l; i++) {
  1049. uint32_t c = d[i];
  1050. if (c <= 0x7f) // 7 bits.
  1051. fl += 1;
  1052. else if (c <= 0x7ff) { // 11 bits
  1053. fl += 2;
  1054. } else if (c <= 0xffff) { // 16 bits
  1055. fl += 3;
  1056. } else if (c <= 0x001fffff) { // 21 bits
  1057. fl += 4;
  1058. } else if (c <= 0x03ffffff) { // 26 bits
  1059. fl += 5;
  1060. } else if (c <= 0x7fffffff) { // 31 bits
  1061. fl += 6;
  1062. }
  1063. }
  1064. CharString utf8s;
  1065. if (fl == 0) {
  1066. return utf8s;
  1067. }
  1068. utf8s.resize(fl + 1);
  1069. uint8_t *cdst = (uint8_t *)utf8s.get_data();
  1070. #define APPEND_CHAR(m_c) *(cdst++) = m_c
  1071. for (int i = 0; i < l; i++) {
  1072. uint32_t c = d[i];
  1073. if (c <= 0x7f) // 7 bits.
  1074. APPEND_CHAR(c);
  1075. else if (c <= 0x7ff) { // 11 bits
  1076. APPEND_CHAR(uint32_t(0xc0 | ((c >> 6) & 0x1f))); // Top 5 bits.
  1077. APPEND_CHAR(uint32_t(0x80 | (c & 0x3f))); // Bottom 6 bits.
  1078. } else if (c <= 0xffff) { // 16 bits
  1079. APPEND_CHAR(uint32_t(0xe0 | ((c >> 12) & 0x0f))); // Top 4 bits.
  1080. APPEND_CHAR(uint32_t(0x80 | ((c >> 6) & 0x3f))); // Middle 6 bits.
  1081. APPEND_CHAR(uint32_t(0x80 | (c & 0x3f))); // Bottom 6 bits.
  1082. } else if (c <= 0x001fffff) { // 21 bits
  1083. APPEND_CHAR(uint32_t(0xf0 | ((c >> 18) & 0x07))); // Top 3 bits.
  1084. APPEND_CHAR(uint32_t(0x80 | ((c >> 12) & 0x3f))); // Upper middle 6 bits.
  1085. APPEND_CHAR(uint32_t(0x80 | ((c >> 6) & 0x3f))); // Lower middle 6 bits.
  1086. APPEND_CHAR(uint32_t(0x80 | (c & 0x3f))); // Bottom 6 bits.
  1087. } else if (c <= 0x03ffffff) { // 26 bits
  1088. APPEND_CHAR(uint32_t(0xf8 | ((c >> 24) & 0x03))); // Top 2 bits.
  1089. APPEND_CHAR(uint32_t(0x80 | ((c >> 18) & 0x3f))); // Upper middle 6 bits.
  1090. APPEND_CHAR(uint32_t(0x80 | ((c >> 12) & 0x3f))); // middle 6 bits.
  1091. APPEND_CHAR(uint32_t(0x80 | ((c >> 6) & 0x3f))); // Lower middle 6 bits.
  1092. APPEND_CHAR(uint32_t(0x80 | (c & 0x3f))); // Bottom 6 bits.
  1093. } else if (c <= 0x7fffffff) { // 31 bits
  1094. APPEND_CHAR(uint32_t(0xfc | ((c >> 30) & 0x01))); // Top 1 bit.
  1095. APPEND_CHAR(uint32_t(0x80 | ((c >> 24) & 0x3f))); // Upper upper middle 6 bits.
  1096. APPEND_CHAR(uint32_t(0x80 | ((c >> 18) & 0x3f))); // Lower upper middle 6 bits.
  1097. APPEND_CHAR(uint32_t(0x80 | ((c >> 12) & 0x3f))); // Upper lower middle 6 bits.
  1098. APPEND_CHAR(uint32_t(0x80 | ((c >> 6) & 0x3f))); // Lower lower middle 6 bits.
  1099. APPEND_CHAR(uint32_t(0x80 | (c & 0x3f))); // Bottom 6 bits.
  1100. }
  1101. }
  1102. #undef APPEND_CHAR
  1103. *cdst = 0; //trailing zero
  1104. return utf8s;
  1105. }
  1106. /*
  1107. String::String(CharType p_char) {
  1108. shared=NULL;
  1109. copy_from(p_char);
  1110. }
  1111. */
  1112. String::String(const char *p_str) {
  1113. copy_from(p_str);
  1114. }
  1115. String::String(const CharType *p_str, int p_clip_to_len) {
  1116. copy_from(p_str, p_clip_to_len);
  1117. }
  1118. String::String(const StrRange &p_range) {
  1119. if (!p_range.c_str)
  1120. return;
  1121. copy_from(p_range.c_str, p_range.len);
  1122. }
  1123. int String::hex_to_int(bool p_with_prefix) const {
  1124. int l = length();
  1125. if (p_with_prefix && l < 3)
  1126. return 0;
  1127. const CharType *s = ptr();
  1128. int sign = s[0] == '-' ? -1 : 1;
  1129. if (sign < 0) {
  1130. s++;
  1131. l--;
  1132. if (p_with_prefix && l < 2)
  1133. return 0;
  1134. }
  1135. if (p_with_prefix) {
  1136. if (s[0] != '0' || s[1] != 'x')
  1137. return 0;
  1138. s += 2;
  1139. l -= 2;
  1140. };
  1141. int hex = 0;
  1142. while (*s) {
  1143. CharType c = LOWERCASE(*s);
  1144. int n;
  1145. if (c >= '0' && c <= '9') {
  1146. n = c - '0';
  1147. } else if (c >= 'a' && c <= 'f') {
  1148. n = (c - 'a') + 10;
  1149. } else {
  1150. return 0;
  1151. }
  1152. hex *= 16;
  1153. hex += n;
  1154. s++;
  1155. }
  1156. return hex * sign;
  1157. }
  1158. int64_t String::hex_to_int64(bool p_with_prefix) const {
  1159. int l = length();
  1160. if (p_with_prefix && l < 3)
  1161. return 0;
  1162. const CharType *s = ptr();
  1163. int64_t sign = s[0] == '-' ? -1 : 1;
  1164. if (sign < 0) {
  1165. s++;
  1166. l--;
  1167. if (p_with_prefix && l < 2)
  1168. return 0;
  1169. }
  1170. if (p_with_prefix) {
  1171. if (s[0] != '0' || s[1] != 'x')
  1172. return 0;
  1173. s += 2;
  1174. l -= 2;
  1175. };
  1176. int64_t hex = 0;
  1177. while (*s) {
  1178. CharType c = LOWERCASE(*s);
  1179. int64_t n;
  1180. if (c >= '0' && c <= '9') {
  1181. n = c - '0';
  1182. } else if (c >= 'a' && c <= 'f') {
  1183. n = (c - 'a') + 10;
  1184. } else {
  1185. return 0;
  1186. }
  1187. hex *= 16;
  1188. hex += n;
  1189. s++;
  1190. }
  1191. return hex * sign;
  1192. }
  1193. int String::to_int() const {
  1194. if (length() == 0)
  1195. return 0;
  1196. int to = (find(".") >= 0) ? find(".") : length();
  1197. int integer = 0;
  1198. int sign = 1;
  1199. for (int i = 0; i < to; i++) {
  1200. CharType c = operator[](i);
  1201. if (c >= '0' && c <= '9') {
  1202. integer *= 10;
  1203. integer += c - '0';
  1204. } else if (integer == 0 && c == '-') {
  1205. sign = -sign;
  1206. }
  1207. }
  1208. return integer * sign;
  1209. }
  1210. int64_t String::to_int64() const {
  1211. if (length() == 0)
  1212. return 0;
  1213. int to = (find(".") >= 0) ? find(".") : length();
  1214. int64_t integer = 0;
  1215. int64_t sign = 1;
  1216. for (int i = 0; i < to; i++) {
  1217. CharType c = operator[](i);
  1218. if (c >= '0' && c <= '9') {
  1219. integer *= 10;
  1220. integer += c - '0';
  1221. } else if (integer == 0 && c == '-') {
  1222. sign = -sign;
  1223. }
  1224. }
  1225. return integer * sign;
  1226. }
  1227. int String::to_int(const char *p_str, int p_len) {
  1228. int to = 0;
  1229. if (p_len >= 0)
  1230. to = p_len;
  1231. else {
  1232. while (p_str[to] != 0 && p_str[to] != '.')
  1233. to++;
  1234. }
  1235. int integer = 0;
  1236. int sign = 1;
  1237. for (int i = 0; i < to; i++) {
  1238. char c = p_str[i];
  1239. if (c >= '0' && c <= '9') {
  1240. integer *= 10;
  1241. integer += c - '0';
  1242. } else if (c == '-' && integer == 0) {
  1243. sign = -sign;
  1244. } else if (c != ' ')
  1245. break;
  1246. }
  1247. return integer * sign;
  1248. }
  1249. bool String::is_numeric() const {
  1250. if (length() == 0) {
  1251. return false;
  1252. };
  1253. int s = 0;
  1254. if (operator[](0) == '-') ++s;
  1255. bool dot = false;
  1256. for (int i = s; i < length(); i++) {
  1257. CharType c = operator[](i);
  1258. if (c == '.') {
  1259. if (dot) {
  1260. return false;
  1261. };
  1262. dot = true;
  1263. }
  1264. if (c < '0' || c > '9') {
  1265. return false;
  1266. };
  1267. };
  1268. return true; // TODO: Use the parser below for this instead
  1269. };
  1270. template <class C>
  1271. static double built_in_strtod(const C *string, /* A decimal ASCII floating-point number,
  1272. * optionally preceded by white space. Must
  1273. * have form "-I.FE-X", where I is the integer
  1274. * part of the mantissa, F is the fractional
  1275. * part of the mantissa, and X is the
  1276. * exponent. Either of the signs may be "+",
  1277. * "-", or omitted. Either I or F may be
  1278. * omitted, or both. The decimal point isn't
  1279. * necessary unless F is present. The "E" may
  1280. * actually be an "e". E and X may both be
  1281. * omitted (but not just one). */
  1282. C **endPtr = NULL) /* If non-NULL, store terminating Cacter's
  1283. * address here. */
  1284. {
  1285. static const int maxExponent = 511; /* Largest possible base 10 exponent. Any
  1286. * exponent larger than this will already
  1287. * produce underflow or overflow, so there's
  1288. * no need to worry about additional digits.
  1289. */
  1290. static const double powersOf10[] = { /* Table giving binary powers of 10. Entry */
  1291. 10., /* is 10^2^i. Used to convert decimal */
  1292. 100., /* exponents into floating-point numbers. */
  1293. 1.0e4,
  1294. 1.0e8,
  1295. 1.0e16,
  1296. 1.0e32,
  1297. 1.0e64,
  1298. 1.0e128,
  1299. 1.0e256
  1300. };
  1301. int sign, expSign = false;
  1302. double fraction, dblExp;
  1303. const double *d;
  1304. register const C *p;
  1305. register int c;
  1306. int exp = 0; /* Exponent read from "EX" field. */
  1307. int fracExp = 0; /* Exponent that derives from the fractional
  1308. * part. Under normal circumstances, it is
  1309. * the negative of the number of digits in F.
  1310. * However, if I is very long, the last digits
  1311. * of I get dropped (otherwise a long I with a
  1312. * large negative exponent could cause an
  1313. * unnecessary overflow on I alone). In this
  1314. * case, fracExp is incremented one for each
  1315. * dropped digit. */
  1316. int mantSize; /* Number of digits in mantissa. */
  1317. int decPt; /* Number of mantissa digits BEFORE decimal
  1318. * point. */
  1319. const C *pExp; /* Temporarily holds location of exponent in
  1320. * string. */
  1321. /*
  1322. * Strip off leading blanks and check for a sign.
  1323. */
  1324. p = string;
  1325. while (*p == ' ' || *p == '\t' || *p == '\n') {
  1326. p += 1;
  1327. }
  1328. if (*p == '-') {
  1329. sign = true;
  1330. p += 1;
  1331. } else {
  1332. if (*p == '+') {
  1333. p += 1;
  1334. }
  1335. sign = false;
  1336. }
  1337. /*
  1338. * Count the number of digits in the mantissa (including the decimal
  1339. * point), and also locate the decimal point.
  1340. */
  1341. decPt = -1;
  1342. for (mantSize = 0;; mantSize += 1) {
  1343. c = *p;
  1344. if (!IS_DIGIT(c)) {
  1345. if ((c != '.') || (decPt >= 0)) {
  1346. break;
  1347. }
  1348. decPt = mantSize;
  1349. }
  1350. p += 1;
  1351. }
  1352. /*
  1353. * Now suck up the digits in the mantissa. Use two integers to collect 9
  1354. * digits each (this is faster than using floating-point). If the mantissa
  1355. * has more than 18 digits, ignore the extras, since they can't affect the
  1356. * value anyway.
  1357. */
  1358. pExp = p;
  1359. p -= mantSize;
  1360. if (decPt < 0) {
  1361. decPt = mantSize;
  1362. } else {
  1363. mantSize -= 1; /* One of the digits was the point. */
  1364. }
  1365. if (mantSize > 18) {
  1366. fracExp = decPt - 18;
  1367. mantSize = 18;
  1368. } else {
  1369. fracExp = decPt - mantSize;
  1370. }
  1371. if (mantSize == 0) {
  1372. fraction = 0.0;
  1373. p = string;
  1374. goto done;
  1375. } else {
  1376. int frac1, frac2;
  1377. frac1 = 0;
  1378. for (; mantSize > 9; mantSize -= 1) {
  1379. c = *p;
  1380. p += 1;
  1381. if (c == '.') {
  1382. c = *p;
  1383. p += 1;
  1384. }
  1385. frac1 = 10 * frac1 + (c - '0');
  1386. }
  1387. frac2 = 0;
  1388. for (; mantSize > 0; mantSize -= 1) {
  1389. c = *p;
  1390. p += 1;
  1391. if (c == '.') {
  1392. c = *p;
  1393. p += 1;
  1394. }
  1395. frac2 = 10 * frac2 + (c - '0');
  1396. }
  1397. fraction = (1.0e9 * frac1) + frac2;
  1398. }
  1399. /*
  1400. * Skim off the exponent.
  1401. */
  1402. p = pExp;
  1403. if ((*p == 'E') || (*p == 'e')) {
  1404. p += 1;
  1405. if (*p == '-') {
  1406. expSign = true;
  1407. p += 1;
  1408. } else {
  1409. if (*p == '+') {
  1410. p += 1;
  1411. }
  1412. expSign = false;
  1413. }
  1414. if (!IS_DIGIT(CharType(*p))) {
  1415. p = pExp;
  1416. goto done;
  1417. }
  1418. while (IS_DIGIT(CharType(*p))) {
  1419. exp = exp * 10 + (*p - '0');
  1420. p += 1;
  1421. }
  1422. }
  1423. if (expSign) {
  1424. exp = fracExp - exp;
  1425. } else {
  1426. exp = fracExp + exp;
  1427. }
  1428. /*
  1429. * Generate a floating-point number that represents the exponent. Do this
  1430. * by processing the exponent one bit at a time to combine many powers of
  1431. * 2 of 10. Then combine the exponent with the fraction.
  1432. */
  1433. if (exp < 0) {
  1434. expSign = true;
  1435. exp = -exp;
  1436. } else {
  1437. expSign = false;
  1438. }
  1439. if (exp > maxExponent) {
  1440. exp = maxExponent;
  1441. WARN_PRINT("Exponent too high");
  1442. }
  1443. dblExp = 1.0;
  1444. for (d = powersOf10; exp != 0; exp >>= 1, ++d) {
  1445. if (exp & 01) {
  1446. dblExp *= *d;
  1447. }
  1448. }
  1449. if (expSign) {
  1450. fraction /= dblExp;
  1451. } else {
  1452. fraction *= dblExp;
  1453. }
  1454. done:
  1455. if (endPtr != NULL) {
  1456. *endPtr = (C *)p;
  1457. }
  1458. if (sign) {
  1459. return -fraction;
  1460. }
  1461. return fraction;
  1462. }
  1463. #define READING_SIGN 0
  1464. #define READING_INT 1
  1465. #define READING_DEC 2
  1466. #define READING_EXP 3
  1467. #define READING_DONE 4
  1468. double String::to_double(const char *p_str) {
  1469. #ifndef NO_USE_STDLIB
  1470. return built_in_strtod<char>(p_str);
  1471. //return atof(p_str); DOES NOT WORK ON ANDROID(??)
  1472. #else
  1473. return built_in_strtod<char>(p_str);
  1474. #endif
  1475. }
  1476. float String::to_float() const {
  1477. return to_double();
  1478. }
  1479. double String::to_double(const CharType *p_str, const CharType **r_end) {
  1480. return built_in_strtod<CharType>(p_str, (CharType **)r_end);
  1481. }
  1482. int64_t String::to_int(const CharType *p_str, int p_len) {
  1483. if (p_len == 0 || !p_str[0])
  1484. return 0;
  1485. ///@todo make more exact so saving and loading does not lose precision
  1486. int64_t integer = 0;
  1487. int64_t sign = 1;
  1488. int reading = READING_SIGN;
  1489. const CharType *str = p_str;
  1490. const CharType *limit = &p_str[p_len];
  1491. while (*str && reading != READING_DONE && str != limit) {
  1492. CharType c = *(str++);
  1493. switch (reading) {
  1494. case READING_SIGN: {
  1495. if (c >= '0' && c <= '9') {
  1496. reading = READING_INT;
  1497. // let it fallthrough
  1498. } else if (c == '-') {
  1499. sign = -1;
  1500. reading = READING_INT;
  1501. break;
  1502. } else if (c == '+') {
  1503. sign = 1;
  1504. reading = READING_INT;
  1505. break;
  1506. } else {
  1507. break;
  1508. }
  1509. }
  1510. case READING_INT: {
  1511. if (c >= '0' && c <= '9') {
  1512. integer *= 10;
  1513. integer += c - '0';
  1514. } else {
  1515. reading = READING_DONE;
  1516. }
  1517. } break;
  1518. }
  1519. }
  1520. return sign * integer;
  1521. }
  1522. double String::to_double() const {
  1523. if (empty())
  1524. return 0;
  1525. #ifndef NO_USE_STDLIB
  1526. return built_in_strtod<CharType>(c_str());
  1527. //return wcstod(c_str(),NULL); DOES NOT WORK ON ANDROID :(
  1528. #else
  1529. return built_in_strtod<CharType>(c_str());
  1530. #endif
  1531. }
  1532. bool operator==(const char *p_chr, const String &p_str) {
  1533. return p_str == p_chr;
  1534. }
  1535. String operator+(const char *p_chr, const String &p_str) {
  1536. String tmp = p_chr;
  1537. tmp += p_str;
  1538. return tmp;
  1539. }
  1540. String operator+(CharType p_chr, const String &p_str) {
  1541. return (String::chr(p_chr) + p_str);
  1542. }
  1543. uint32_t String::hash(const char *p_cstr) {
  1544. uint32_t hashv = 5381;
  1545. uint32_t c;
  1546. while ((c = *p_cstr++))
  1547. hashv = ((hashv << 5) + hashv) + c; /* hash * 33 + c */
  1548. return hashv;
  1549. }
  1550. uint32_t String::hash(const char *p_cstr, int p_len) {
  1551. uint32_t hashv = 5381;
  1552. for (int i = 0; i < p_len; i++)
  1553. hashv = ((hashv << 5) + hashv) + p_cstr[i]; /* hash * 33 + c */
  1554. return hashv;
  1555. }
  1556. uint32_t String::hash(const CharType *p_cstr, int p_len) {
  1557. uint32_t hashv = 5381;
  1558. for (int i = 0; i < p_len; i++)
  1559. hashv = ((hashv << 5) + hashv) + p_cstr[i]; /* hash * 33 + c */
  1560. return hashv;
  1561. }
  1562. uint32_t String::hash(const CharType *p_cstr) {
  1563. uint32_t hashv = 5381;
  1564. uint32_t c;
  1565. while ((c = *p_cstr++))
  1566. hashv = ((hashv << 5) + hashv) + c; /* hash * 33 + c */
  1567. return hashv;
  1568. }
  1569. uint32_t String::hash() const {
  1570. /* simple djb2 hashing */
  1571. const CharType *chr = c_str();
  1572. uint32_t hashv = 5381;
  1573. uint32_t c;
  1574. while ((c = *chr++))
  1575. hashv = ((hashv << 5) + hashv) + c; /* hash * 33 + c */
  1576. return hashv;
  1577. }
  1578. uint64_t String::hash64() const {
  1579. /* simple djb2 hashing */
  1580. const CharType *chr = c_str();
  1581. uint64_t hashv = 5381;
  1582. uint64_t c;
  1583. while ((c = *chr++))
  1584. hashv = ((hashv << 5) + hashv) + c; /* hash * 33 + c */
  1585. return hashv;
  1586. }
  1587. String String::md5_text() const {
  1588. CharString cs = utf8();
  1589. MD5_CTX ctx;
  1590. MD5Init(&ctx);
  1591. MD5Update(&ctx, (unsigned char *)cs.ptr(), cs.length());
  1592. MD5Final(&ctx);
  1593. return String::md5(ctx.digest);
  1594. }
  1595. String String::sha256_text() const {
  1596. CharString cs = utf8();
  1597. unsigned char hash[32];
  1598. sha256_context ctx;
  1599. sha256_init(&ctx);
  1600. sha256_hash(&ctx, (unsigned char *)cs.ptr(), cs.length());
  1601. sha256_done(&ctx, hash);
  1602. return String::hex_encode_buffer(hash, 32);
  1603. }
  1604. Vector<uint8_t> String::md5_buffer() const {
  1605. CharString cs = utf8();
  1606. MD5_CTX ctx;
  1607. MD5Init(&ctx);
  1608. MD5Update(&ctx, (unsigned char *)cs.ptr(), cs.length());
  1609. MD5Final(&ctx);
  1610. Vector<uint8_t> ret;
  1611. ret.resize(16);
  1612. for (int i = 0; i < 16; i++) {
  1613. ret[i] = ctx.digest[i];
  1614. };
  1615. return ret;
  1616. };
  1617. Vector<uint8_t> String::sha256_buffer() const {
  1618. CharString cs = utf8();
  1619. unsigned char hash[32];
  1620. sha256_context ctx;
  1621. sha256_init(&ctx);
  1622. sha256_hash(&ctx, (unsigned char *)cs.ptr(), cs.length());
  1623. sha256_done(&ctx, hash);
  1624. Vector<uint8_t> ret;
  1625. ret.resize(32);
  1626. for (int i = 0; i < 32; i++) {
  1627. ret[i] = hash[i];
  1628. }
  1629. return ret;
  1630. }
  1631. String String::insert(int p_at_pos, String p_string) const {
  1632. if (p_at_pos < 0)
  1633. return *this;
  1634. if (p_at_pos > length())
  1635. p_at_pos = length();
  1636. String pre;
  1637. if (p_at_pos > 0)
  1638. pre = substr(0, p_at_pos);
  1639. String post;
  1640. if (p_at_pos < length())
  1641. post = substr(p_at_pos, length() - p_at_pos);
  1642. return pre + p_string + post;
  1643. }
  1644. String String::substr(int p_from, int p_chars) const {
  1645. if (empty() || p_from < 0 || p_from >= length() || p_chars <= 0)
  1646. return "";
  1647. if ((p_from + p_chars) > length()) {
  1648. p_chars = length() - p_from;
  1649. }
  1650. return String(&c_str()[p_from], p_chars);
  1651. }
  1652. int String::find_last(String p_str) const {
  1653. int pos = -1;
  1654. int findfrom = 0;
  1655. int findres = -1;
  1656. while ((findres = find(p_str, findfrom)) != -1) {
  1657. pos = findres;
  1658. findfrom = pos + 1;
  1659. }
  1660. return pos;
  1661. }
  1662. int String::find(String p_str, int p_from) const {
  1663. if (p_from < 0)
  1664. return -1;
  1665. int src_len = p_str.length();
  1666. int len = length();
  1667. if (src_len == 0 || len == 0)
  1668. return -1; //wont find anything!
  1669. const CharType *src = c_str();
  1670. for (int i = p_from; i <= (len - src_len); i++) {
  1671. bool found = true;
  1672. for (int j = 0; j < src_len; j++) {
  1673. int read_pos = i + j;
  1674. if (read_pos >= len) {
  1675. ERR_PRINT("read_pos>=len");
  1676. return -1;
  1677. };
  1678. if (src[read_pos] != p_str[j]) {
  1679. found = false;
  1680. break;
  1681. }
  1682. }
  1683. if (found)
  1684. return i;
  1685. }
  1686. return -1;
  1687. }
  1688. int String::findmk(const Vector<String> &p_keys, int p_from, int *r_key) const {
  1689. if (p_from < 0)
  1690. return -1;
  1691. if (p_keys.size() == 0)
  1692. return -1;
  1693. //int src_len=p_str.length();
  1694. const String *keys = &p_keys[0];
  1695. int key_count = p_keys.size();
  1696. int len = length();
  1697. if (len == 0)
  1698. return -1; //wont find anything!
  1699. const CharType *src = c_str();
  1700. for (int i = p_from; i < len; i++) {
  1701. bool found = true;
  1702. for (int k = 0; k < key_count; k++) {
  1703. found = true;
  1704. if (r_key)
  1705. *r_key = k;
  1706. const CharType *cmp = keys[k].c_str();
  1707. int l = keys[k].length();
  1708. for (int j = 0; j < l; j++) {
  1709. int read_pos = i + j;
  1710. if (read_pos >= len) {
  1711. found = false;
  1712. break;
  1713. };
  1714. if (src[read_pos] != cmp[j]) {
  1715. found = false;
  1716. break;
  1717. }
  1718. }
  1719. if (found)
  1720. break;
  1721. }
  1722. if (found)
  1723. return i;
  1724. }
  1725. return -1;
  1726. }
  1727. int String::findn(String p_str, int p_from) const {
  1728. if (p_from < 0)
  1729. return -1;
  1730. int src_len = p_str.length();
  1731. if (src_len == 0 || length() == 0)
  1732. return -1; //wont find anything!
  1733. const CharType *srcd = c_str();
  1734. for (int i = p_from; i <= (length() - src_len); i++) {
  1735. bool found = true;
  1736. for (int j = 0; j < src_len; j++) {
  1737. int read_pos = i + j;
  1738. if (read_pos >= length()) {
  1739. ERR_PRINT("read_pos>=length()");
  1740. return -1;
  1741. };
  1742. CharType src = _find_lower(srcd[read_pos]);
  1743. CharType dst = _find_lower(p_str[j]);
  1744. if (src != dst) {
  1745. found = false;
  1746. break;
  1747. }
  1748. }
  1749. if (found)
  1750. return i;
  1751. }
  1752. return -1;
  1753. }
  1754. int String::rfind(String p_str, int p_from) const {
  1755. // establish a limit
  1756. int limit = length() - p_str.length();
  1757. if (limit < 0)
  1758. return -1;
  1759. // establish a starting point
  1760. if (p_from < 0)
  1761. p_from = limit;
  1762. else if (p_from > limit)
  1763. p_from = limit;
  1764. int src_len = p_str.length();
  1765. int len = length();
  1766. if (src_len == 0 || len == 0)
  1767. return -1; // won't find anything!
  1768. const CharType *src = c_str();
  1769. for (int i = p_from; i >= 0; i--) {
  1770. bool found = true;
  1771. for (int j = 0; j < src_len; j++) {
  1772. int read_pos = i + j;
  1773. if (read_pos >= len) {
  1774. ERR_PRINT("read_pos>=len");
  1775. return -1;
  1776. };
  1777. if (src[read_pos] != p_str[j]) {
  1778. found = false;
  1779. break;
  1780. }
  1781. }
  1782. if (found)
  1783. return i;
  1784. }
  1785. return -1;
  1786. }
  1787. int String::rfindn(String p_str, int p_from) const {
  1788. // establish a limit
  1789. int limit = length() - p_str.length();
  1790. if (limit < 0)
  1791. return -1;
  1792. // establish a starting point
  1793. if (p_from < 0)
  1794. p_from = limit;
  1795. else if (p_from > limit)
  1796. p_from = limit;
  1797. int src_len = p_str.length();
  1798. int len = length();
  1799. if (src_len == 0 || len == 0)
  1800. return -1; //wont find anything!
  1801. const CharType *src = c_str();
  1802. for (int i = p_from; i >= 0; i--) {
  1803. bool found = true;
  1804. for (int j = 0; j < src_len; j++) {
  1805. int read_pos = i + j;
  1806. if (read_pos >= len) {
  1807. ERR_PRINT("read_pos>=len");
  1808. return -1;
  1809. };
  1810. CharType srcc = _find_lower(src[read_pos]);
  1811. CharType dstc = _find_lower(p_str[j]);
  1812. if (srcc != dstc) {
  1813. found = false;
  1814. break;
  1815. }
  1816. }
  1817. if (found)
  1818. return i;
  1819. }
  1820. return -1;
  1821. }
  1822. bool String::ends_with(const String &p_string) const {
  1823. int pos = find_last(p_string);
  1824. if (pos == -1)
  1825. return false;
  1826. return pos + p_string.length() == length();
  1827. }
  1828. bool String::begins_with(const String &p_string) const {
  1829. if (p_string.length() > length())
  1830. return false;
  1831. int l = p_string.length();
  1832. if (l == 0)
  1833. return true;
  1834. const CharType *src = &p_string[0];
  1835. const CharType *str = &operator[](0);
  1836. int i = 0;
  1837. for (; i < l; i++) {
  1838. if (src[i] != str[i])
  1839. return false;
  1840. }
  1841. // only if i == l the p_string matches the beginning
  1842. return i == l;
  1843. }
  1844. bool String::begins_with(const char *p_string) const {
  1845. int l = length();
  1846. if (l == 0 || !p_string)
  1847. return false;
  1848. const CharType *str = &operator[](0);
  1849. int i = 0;
  1850. while (*p_string && i < l) {
  1851. if (*p_string != str[i])
  1852. return false;
  1853. i++;
  1854. p_string++;
  1855. }
  1856. return *p_string == 0;
  1857. }
  1858. bool String::is_enclosed_in(const String &p_string) const {
  1859. return begins_with(p_string) && ends_with(p_string);
  1860. }
  1861. bool String::is_subsequence_of(const String &p_string) const {
  1862. return _base_is_subsequence_of(p_string, false);
  1863. }
  1864. bool String::is_subsequence_ofi(const String &p_string) const {
  1865. return _base_is_subsequence_of(p_string, true);
  1866. }
  1867. bool String::is_quoted() const {
  1868. return is_enclosed_in("\"") || is_enclosed_in("'");
  1869. }
  1870. bool String::_base_is_subsequence_of(const String &p_string, bool case_insensitive) const {
  1871. int len = length();
  1872. if (len == 0) {
  1873. // Technically an empty string is subsequence of any string
  1874. return true;
  1875. }
  1876. if (len > p_string.length()) {
  1877. return false;
  1878. }
  1879. const CharType *src = &operator[](0);
  1880. const CharType *tgt = &p_string[0];
  1881. for (; *src && *tgt; tgt++) {
  1882. bool match = false;
  1883. if (case_insensitive) {
  1884. CharType srcc = _find_lower(*src);
  1885. CharType tgtc = _find_lower(*tgt);
  1886. match = srcc == tgtc;
  1887. } else {
  1888. match = *src == *tgt;
  1889. }
  1890. if (match) {
  1891. src++;
  1892. if (!*src) {
  1893. return true;
  1894. }
  1895. }
  1896. }
  1897. return false;
  1898. }
  1899. Vector<String> String::bigrams() const {
  1900. int n_pairs = length() - 1;
  1901. Vector<String> b;
  1902. if (n_pairs <= 0) {
  1903. return b;
  1904. }
  1905. b.resize(n_pairs);
  1906. for (int i = 0; i < n_pairs; i++) {
  1907. b[i] = substr(i, 2);
  1908. }
  1909. return b;
  1910. }
  1911. // Similarity according to Sorensen-Dice coefficient
  1912. float String::similarity(const String &p_string) const {
  1913. if (operator==(p_string)) {
  1914. // Equal strings are totally similar
  1915. return 1.0f;
  1916. }
  1917. if (length() < 2 || p_string.length() < 2) {
  1918. // No way to calculate similarity without a single bigram
  1919. return 0.0f;
  1920. }
  1921. Vector<String> src_bigrams = bigrams();
  1922. Vector<String> tgt_bigrams = p_string.bigrams();
  1923. int src_size = src_bigrams.size();
  1924. int tgt_size = tgt_bigrams.size();
  1925. float sum = src_size + tgt_size;
  1926. float inter = 0;
  1927. for (int i = 0; i < src_size; i++) {
  1928. for (int j = 0; j < tgt_size; j++) {
  1929. if (src_bigrams[i] == tgt_bigrams[j]) {
  1930. inter++;
  1931. break;
  1932. }
  1933. }
  1934. }
  1935. return (2.0f * inter) / sum;
  1936. }
  1937. static bool _wildcard_match(const CharType *p_pattern, const CharType *p_string, bool p_case_sensitive) {
  1938. switch (*p_pattern) {
  1939. case '\0':
  1940. return !*p_string;
  1941. case '*':
  1942. return _wildcard_match(p_pattern + 1, p_string, p_case_sensitive) || (*p_string && _wildcard_match(p_pattern, p_string + 1, p_case_sensitive));
  1943. case '?':
  1944. return *p_string && (*p_string != '.') && _wildcard_match(p_pattern + 1, p_string + 1, p_case_sensitive);
  1945. default:
  1946. 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);
  1947. }
  1948. }
  1949. bool String::match(const String &p_wildcard) const {
  1950. if (!p_wildcard.length() || !length())
  1951. return false;
  1952. return _wildcard_match(p_wildcard.c_str(), c_str(), true);
  1953. }
  1954. bool String::matchn(const String &p_wildcard) const {
  1955. if (!p_wildcard.length() || !length())
  1956. return false;
  1957. return _wildcard_match(p_wildcard.c_str(), c_str(), false);
  1958. }
  1959. String String::format(const Variant &values, String placeholder) const {
  1960. String new_string = String(this->ptr());
  1961. if (values.get_type() == Variant::ARRAY) {
  1962. Array values_arr = values;
  1963. for (int i = 0; i < values_arr.size(); i++) {
  1964. String i_as_str = String::num_int64(i);
  1965. if (values_arr[i].get_type() == Variant::ARRAY) { //Array in Array structure [["name","RobotGuy"],[0,"godot"],["strength",9000.91]]
  1966. Array value_arr = values_arr[i];
  1967. if (value_arr.size() == 2) {
  1968. Variant v_key = value_arr[0];
  1969. String key;
  1970. key = v_key.get_construct_string();
  1971. if (key.left(1) == "\"" && key.right(key.length() - 1) == "\"") {
  1972. key = key.substr(1, key.length() - 2);
  1973. }
  1974. Variant v_val = value_arr[1];
  1975. String val;
  1976. val = v_val.get_construct_string();
  1977. if (val.left(1) == "\"" && val.right(val.length() - 1) == "\"") {
  1978. val = val.substr(1, val.length() - 2);
  1979. }
  1980. new_string = new_string.replacen(placeholder.replace("_", key), val);
  1981. } else {
  1982. ERR_PRINT(String("STRING.format Inner Array size != 2 ").ascii().get_data());
  1983. }
  1984. } else { //Array structure ["RobotGuy","Logis","rookie"]
  1985. Variant v_val = values_arr[i];
  1986. String val;
  1987. val = v_val.get_construct_string();
  1988. if (val.left(1) == "\"" && val.right(val.length() - 1) == "\"") {
  1989. val = val.substr(1, val.length() - 2);
  1990. }
  1991. new_string = new_string.replacen(placeholder.replace("_", i_as_str), val);
  1992. }
  1993. }
  1994. } else if (values.get_type() == Variant::DICTIONARY) {
  1995. Dictionary d = values;
  1996. List<Variant> keys;
  1997. d.get_key_list(&keys);
  1998. for (List<Variant>::Element *E = keys.front(); E; E = E->next()) {
  1999. String key = E->get().get_construct_string();
  2000. String val = d[E->get()].get_construct_string();
  2001. if (key.left(1) == "\"" && key.right(key.length() - 1) == "\"") {
  2002. key = key.substr(1, key.length() - 2);
  2003. }
  2004. if (val.left(1) == "\"" && val.right(val.length() - 1) == "\"") {
  2005. val = val.substr(1, val.length() - 2);
  2006. }
  2007. new_string = new_string.replacen(placeholder.replace("_", key), val);
  2008. }
  2009. } else {
  2010. ERR_PRINT(String("Invalid type: use Array or Dictionary.").ascii().get_data());
  2011. }
  2012. return new_string;
  2013. }
  2014. String String::replace(String p_key, String p_with) const {
  2015. String new_string;
  2016. int search_from = 0;
  2017. int result = 0;
  2018. while ((result = find(p_key, search_from)) >= 0) {
  2019. new_string += substr(search_from, result - search_from);
  2020. new_string += p_with;
  2021. search_from = result + p_key.length();
  2022. }
  2023. new_string += substr(search_from, length() - search_from);
  2024. return new_string;
  2025. }
  2026. String String::replace_first(String p_key, String p_with) const {
  2027. String new_string;
  2028. int search_from = 0;
  2029. int result = 0;
  2030. while ((result = find(p_key, search_from)) >= 0) {
  2031. new_string += substr(search_from, result - search_from);
  2032. new_string += p_with;
  2033. search_from = result + p_key.length();
  2034. break;
  2035. }
  2036. new_string += substr(search_from, length() - search_from);
  2037. return new_string;
  2038. }
  2039. String String::replacen(String p_key, String p_with) const {
  2040. String new_string;
  2041. int search_from = 0;
  2042. int result = 0;
  2043. while ((result = findn(p_key, search_from)) >= 0) {
  2044. new_string += substr(search_from, result - search_from);
  2045. new_string += p_with;
  2046. search_from = result + p_key.length();
  2047. }
  2048. new_string += substr(search_from, length() - search_from);
  2049. return new_string;
  2050. }
  2051. String String::left(int p_pos) const {
  2052. if (p_pos <= 0)
  2053. return "";
  2054. if (p_pos >= length())
  2055. return *this;
  2056. return substr(0, p_pos);
  2057. }
  2058. String String::right(int p_pos) const {
  2059. if (p_pos >= size())
  2060. return *this;
  2061. if (p_pos < 0)
  2062. return "";
  2063. return substr(p_pos, (length() - p_pos));
  2064. }
  2065. CharType String::ord_at(int p_idx) const {
  2066. ERR_FAIL_INDEX_V(p_idx, length(), 0);
  2067. return operator[](p_idx);
  2068. }
  2069. String String::dedent() const {
  2070. String new_string;
  2071. String indent;
  2072. bool has_indent = false;
  2073. bool has_text = false;
  2074. int line_start = 0;
  2075. int indent_stop = -1;
  2076. for (int i = 0; i < length(); i++) {
  2077. CharType c = operator[](i);
  2078. if (c == '\n') {
  2079. if (has_text)
  2080. new_string += substr(indent_stop, i - indent_stop);
  2081. new_string += "\n";
  2082. has_text = false;
  2083. line_start = i + 1;
  2084. indent_stop = -1;
  2085. } else if (!has_text) {
  2086. if (c > 32) {
  2087. has_text = true;
  2088. if (!has_indent) {
  2089. has_indent = true;
  2090. indent = substr(line_start, i - line_start);
  2091. indent_stop = i;
  2092. }
  2093. }
  2094. if (has_indent && indent_stop < 0) {
  2095. int j = i - line_start;
  2096. if (j >= indent.length() || c != indent[j])
  2097. indent_stop = i;
  2098. }
  2099. }
  2100. }
  2101. if (has_text)
  2102. new_string += substr(indent_stop, length() - indent_stop);
  2103. return new_string;
  2104. }
  2105. String String::strip_edges(bool left, bool right) const {
  2106. int len = length();
  2107. int beg = 0, end = len;
  2108. if (left) {
  2109. for (int i = 0; i < len; i++) {
  2110. if (operator[](i) <= 32)
  2111. beg++;
  2112. else
  2113. break;
  2114. }
  2115. }
  2116. if (right) {
  2117. for (int i = (int)(len - 1); i >= 0; i--) {
  2118. if (operator[](i) <= 32)
  2119. end--;
  2120. else
  2121. break;
  2122. }
  2123. }
  2124. if (beg == 0 && end == len)
  2125. return *this;
  2126. return substr(beg, end - beg);
  2127. }
  2128. String String::strip_escapes() const {
  2129. int len = length();
  2130. int beg = 0, end = len;
  2131. for (int i = 0; i < length(); i++) {
  2132. if (operator[](i) <= 31)
  2133. beg++;
  2134. else
  2135. break;
  2136. }
  2137. for (int i = (int)(length() - 1); i >= 0; i--) {
  2138. if (operator[](i) <= 31)
  2139. end--;
  2140. else
  2141. break;
  2142. }
  2143. if (beg == 0 && end == len)
  2144. return *this;
  2145. return substr(beg, end - beg);
  2146. }
  2147. String String::simplify_path() const {
  2148. String s = *this;
  2149. String drive;
  2150. if (s.begins_with("local://")) {
  2151. drive = "local://";
  2152. s = s.substr(8, s.length());
  2153. } else if (s.begins_with("res://")) {
  2154. drive = "res://";
  2155. s = s.substr(6, s.length());
  2156. } else if (s.begins_with("user://")) {
  2157. drive = "user://";
  2158. s = s.substr(6, s.length());
  2159. } else if (s.begins_with("/") || s.begins_with("\\")) {
  2160. drive = s.substr(0, 1);
  2161. s = s.substr(1, s.length() - 1);
  2162. } else {
  2163. int p = s.find(":/");
  2164. if (p == -1)
  2165. p = s.find(":\\");
  2166. if (p != -1 && p < s.find("/")) {
  2167. drive = s.substr(0, p + 2);
  2168. s = s.substr(p + 2, s.length());
  2169. }
  2170. }
  2171. s = s.replace("\\", "/");
  2172. while (true) { // in case of using 2 or more slash
  2173. String compare = s.replace("//", "/");
  2174. if (s == compare)
  2175. break;
  2176. else
  2177. s = compare;
  2178. }
  2179. Vector<String> dirs = s.split("/", false);
  2180. for (int i = 0; i < dirs.size(); i++) {
  2181. String d = dirs[i];
  2182. if (d == ".") {
  2183. dirs.remove(i);
  2184. i--;
  2185. } else if (d == "..") {
  2186. if (i == 0) {
  2187. dirs.remove(i);
  2188. i--;
  2189. } else {
  2190. dirs.remove(i);
  2191. dirs.remove(i - 1);
  2192. i -= 2;
  2193. }
  2194. }
  2195. }
  2196. s = "";
  2197. for (int i = 0; i < dirs.size(); i++) {
  2198. if (i > 0)
  2199. s += "/";
  2200. s += dirs[i];
  2201. }
  2202. return drive + s;
  2203. }
  2204. static int _humanize_digits(int p_num) {
  2205. if (p_num < 10)
  2206. return 2;
  2207. else if (p_num < 100)
  2208. return 2;
  2209. else if (p_num < 1024)
  2210. return 1;
  2211. else
  2212. return 0;
  2213. }
  2214. String String::humanize_size(size_t p_size) {
  2215. uint64_t _div = 1;
  2216. static const char *prefix[] = { " Bytes", " KB", " MB", " GB", "TB", " PB", "HB", "" };
  2217. int prefix_idx = 0;
  2218. while (p_size > (_div * 1024) && prefix[prefix_idx][0]) {
  2219. _div *= 1024;
  2220. prefix_idx++;
  2221. }
  2222. int digits = prefix_idx > 0 ? _humanize_digits(p_size / _div) : 0;
  2223. double divisor = prefix_idx > 0 ? _div : 1;
  2224. return String::num(p_size / divisor, digits) + prefix[prefix_idx];
  2225. }
  2226. bool String::is_abs_path() const {
  2227. if (length() > 1)
  2228. return (operator[](0) == '/' || operator[](0) == '\\' || find(":/") != -1 || find(":\\") != -1);
  2229. else if ((length()) == 1)
  2230. return (operator[](0) == '/' || operator[](0) == '\\');
  2231. else
  2232. return false;
  2233. }
  2234. bool String::is_valid_identifier() const {
  2235. int len = length();
  2236. if (len == 0)
  2237. return false;
  2238. const wchar_t *str = &operator[](0);
  2239. for (int i = 0; i < len; i++) {
  2240. if (i == 0) {
  2241. if (str[0] >= '0' && str[0] <= '9')
  2242. return false; // no start with number plz
  2243. }
  2244. bool valid_char = (str[i] >= '0' && str[i] <= '9') || (str[i] >= 'a' && str[i] <= 'z') || (str[i] >= 'A' && str[i] <= 'Z') || str[i] == '_';
  2245. if (!valid_char)
  2246. return false;
  2247. }
  2248. return true;
  2249. }
  2250. //kind of poor should be rewritten properly
  2251. String String::word_wrap(int p_chars_per_line) const {
  2252. int from = 0;
  2253. int last_space = 0;
  2254. String ret;
  2255. for (int i = 0; i < length(); i++) {
  2256. if (i - from >= p_chars_per_line) {
  2257. if (last_space == -1) {
  2258. ret += substr(from, i - from + 1) + "\n";
  2259. } else {
  2260. ret += substr(from, last_space - from) + "\n";
  2261. i = last_space; //rewind
  2262. }
  2263. from = i + 1;
  2264. last_space = -1;
  2265. } else if (operator[](i) == ' ' || operator[](i) == '\t') {
  2266. last_space = i;
  2267. } else if (operator[](i) == '\n') {
  2268. ret += substr(from, i - from) + "\n";
  2269. from = i + 1;
  2270. last_space = -1;
  2271. }
  2272. }
  2273. if (from < length()) {
  2274. ret += substr(from, length());
  2275. }
  2276. return ret;
  2277. }
  2278. String String::http_escape() const {
  2279. const CharString temp = utf8();
  2280. String res;
  2281. for (int i = 0; i < length(); ++i) {
  2282. CharType ord = temp[i];
  2283. if (ord == '.' || ord == '-' || ord == '_' || ord == '~' ||
  2284. (ord >= 'a' && ord <= 'z') ||
  2285. (ord >= 'A' && ord <= 'Z') ||
  2286. (ord >= '0' && ord <= '9')) {
  2287. res += ord;
  2288. } else {
  2289. char h_Val[3];
  2290. #if defined(__GNUC__) || defined(_MSC_VER)
  2291. snprintf(h_Val, 3, "%.2X", ord);
  2292. #else
  2293. sprintf(h_Val, "%.2X", ord);
  2294. #endif
  2295. res += "%";
  2296. res += h_Val;
  2297. }
  2298. }
  2299. return res;
  2300. }
  2301. String String::http_unescape() const {
  2302. String res;
  2303. for (int i = 0; i < length(); ++i) {
  2304. if (ord_at(i) == '%' && i + 2 < length()) {
  2305. CharType ord1 = ord_at(i + 1);
  2306. if ((ord1 >= '0' && ord1 <= '9') || (ord1 >= 'A' && ord1 <= 'Z')) {
  2307. CharType ord2 = ord_at(i + 2);
  2308. if ((ord2 >= '0' && ord2 <= '9') || (ord2 >= 'A' && ord2 <= 'Z')) {
  2309. char bytes[2] = { ord1, ord2 };
  2310. res += (char)strtol(bytes, NULL, 16);
  2311. i += 2;
  2312. }
  2313. } else {
  2314. res += ord_at(i);
  2315. }
  2316. } else {
  2317. res += ord_at(i);
  2318. }
  2319. }
  2320. return String::utf8(res.ascii());
  2321. }
  2322. String String::c_unescape() const {
  2323. String escaped = *this;
  2324. escaped = escaped.replace("\\a", "\a");
  2325. escaped = escaped.replace("\\b", "\b");
  2326. escaped = escaped.replace("\\f", "\f");
  2327. escaped = escaped.replace("\\n", "\n");
  2328. escaped = escaped.replace("\\r", "\r");
  2329. escaped = escaped.replace("\\t", "\t");
  2330. escaped = escaped.replace("\\v", "\v");
  2331. escaped = escaped.replace("\\'", "\'");
  2332. escaped = escaped.replace("\\\"", "\"");
  2333. escaped = escaped.replace("\\?", "\?");
  2334. escaped = escaped.replace("\\\\", "\\");
  2335. return escaped;
  2336. }
  2337. String String::c_escape() const {
  2338. String escaped = *this;
  2339. escaped = escaped.replace("\\", "\\\\");
  2340. escaped = escaped.replace("\a", "\\a");
  2341. escaped = escaped.replace("\b", "\\b");
  2342. escaped = escaped.replace("\f", "\\f");
  2343. escaped = escaped.replace("\n", "\\n");
  2344. escaped = escaped.replace("\r", "\\r");
  2345. escaped = escaped.replace("\t", "\\t");
  2346. escaped = escaped.replace("\v", "\\v");
  2347. escaped = escaped.replace("\'", "\\'");
  2348. escaped = escaped.replace("\?", "\\?");
  2349. escaped = escaped.replace("\"", "\\\"");
  2350. return escaped;
  2351. }
  2352. String String::c_escape_multiline() const {
  2353. String escaped = *this;
  2354. escaped = escaped.replace("\\", "\\\\");
  2355. escaped = escaped.replace("\"", "\\\"");
  2356. return escaped;
  2357. }
  2358. String String::json_escape() const {
  2359. String escaped = *this;
  2360. escaped = escaped.replace("\\", "\\\\");
  2361. escaped = escaped.replace("\b", "\\b");
  2362. escaped = escaped.replace("\f", "\\f");
  2363. escaped = escaped.replace("\n", "\\n");
  2364. escaped = escaped.replace("\r", "\\r");
  2365. escaped = escaped.replace("\t", "\\t");
  2366. escaped = escaped.replace("\v", "\\v");
  2367. escaped = escaped.replace("\"", "\\\"");
  2368. return escaped;
  2369. }
  2370. String String::xml_escape(bool p_escape_quotes) const {
  2371. String str = *this;
  2372. str = str.replace("&", "&amp;");
  2373. str = str.replace("<", "&lt;");
  2374. str = str.replace(">", "&gt;");
  2375. if (p_escape_quotes) {
  2376. str = str.replace("'", "&apos;");
  2377. str = str.replace("\"", "&quot;");
  2378. }
  2379. /*
  2380. for (int i=1;i<32;i++) {
  2381. char chr[2]={i,0};
  2382. str=str.replace(chr,"&#"+String::num(i)+";");
  2383. }*/
  2384. return str;
  2385. }
  2386. static _FORCE_INLINE_ int _xml_unescape(const CharType *p_src, int p_src_len, CharType *p_dst) {
  2387. int len = 0;
  2388. while (p_src_len) {
  2389. if (*p_src == '&') {
  2390. int eat = 0;
  2391. if (p_src_len >= 4 && p_src[1] == '#') {
  2392. CharType c = 0;
  2393. for (int i = 2; i < p_src_len; i++) {
  2394. eat = i + 1;
  2395. CharType ct = p_src[i];
  2396. if (ct == ';') {
  2397. break;
  2398. } else if (ct >= '0' && ct <= '9') {
  2399. ct = ct - '0';
  2400. } else if (ct >= 'a' && ct <= 'f') {
  2401. ct = (ct - 'a') + 10;
  2402. } else if (ct >= 'A' && ct <= 'F') {
  2403. ct = (ct - 'A') + 10;
  2404. } else {
  2405. continue;
  2406. }
  2407. c <<= 4;
  2408. c |= ct;
  2409. }
  2410. if (p_dst)
  2411. *p_dst = c;
  2412. } else if (p_src_len >= 4 && p_src[1] == 'g' && p_src[2] == 't' && p_src[3] == ';') {
  2413. if (p_dst)
  2414. *p_dst = '>';
  2415. eat = 4;
  2416. } else if (p_src_len >= 4 && p_src[1] == 'l' && p_src[2] == 't' && p_src[3] == ';') {
  2417. if (p_dst)
  2418. *p_dst = '<';
  2419. eat = 4;
  2420. } else if (p_src_len >= 5 && p_src[1] == 'a' && p_src[2] == 'm' && p_src[3] == 'p' && p_src[4] == ';') {
  2421. if (p_dst)
  2422. *p_dst = '&';
  2423. eat = 5;
  2424. } 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] == ';') {
  2425. if (p_dst)
  2426. *p_dst = '"';
  2427. eat = 6;
  2428. } 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] == ';') {
  2429. if (p_dst)
  2430. *p_dst = '\'';
  2431. eat = 6;
  2432. } else {
  2433. if (p_dst)
  2434. *p_dst = *p_src;
  2435. eat = 1;
  2436. }
  2437. if (p_dst)
  2438. p_dst++;
  2439. len++;
  2440. p_src += eat;
  2441. p_src_len -= eat;
  2442. } else {
  2443. if (p_dst) {
  2444. *p_dst = *p_src;
  2445. p_dst++;
  2446. }
  2447. len++;
  2448. p_src++;
  2449. p_src_len--;
  2450. }
  2451. }
  2452. return len;
  2453. }
  2454. String String::xml_unescape() const {
  2455. String str;
  2456. int l = length();
  2457. int len = _xml_unescape(c_str(), l, NULL);
  2458. if (len == 0)
  2459. return String();
  2460. str.resize(len + 1);
  2461. _xml_unescape(c_str(), l, &str[0]);
  2462. str[len] = 0;
  2463. return str;
  2464. }
  2465. String String::pad_decimals(int p_digits) const {
  2466. String s = *this;
  2467. int c = s.find(".");
  2468. if (c == -1) {
  2469. if (p_digits <= 0) {
  2470. return s;
  2471. }
  2472. s += ".";
  2473. c = s.length() - 1;
  2474. } else {
  2475. if (p_digits <= 0) {
  2476. return s.substr(0, c);
  2477. }
  2478. }
  2479. if (s.length() - (c + 1) > p_digits) {
  2480. s = s.substr(0, c + p_digits + 1);
  2481. } else {
  2482. while (s.length() - (c + 1) < p_digits) {
  2483. s += "0";
  2484. }
  2485. }
  2486. return s;
  2487. }
  2488. String String::pad_zeros(int p_digits) const {
  2489. String s = *this;
  2490. int end = s.find(".");
  2491. if (end == -1) {
  2492. end = s.length();
  2493. }
  2494. if (end == 0)
  2495. return s;
  2496. int begin = 0;
  2497. while (begin < end && (s[begin] < '0' || s[begin] > '9')) {
  2498. begin++;
  2499. }
  2500. if (begin >= end)
  2501. return s;
  2502. while (end - begin < p_digits) {
  2503. s = s.insert(begin, "0");
  2504. end++;
  2505. }
  2506. return s;
  2507. }
  2508. bool String::is_valid_integer() const {
  2509. int len = length();
  2510. if (len == 0)
  2511. return false;
  2512. int from = 0;
  2513. if (len != 1 && (operator[](0) == '+' || operator[](0) == '-'))
  2514. from++;
  2515. for (int i = from; i < len; i++) {
  2516. if (operator[](i) < '0' || operator[](i) > '9')
  2517. return false; // no start with number plz
  2518. }
  2519. return true;
  2520. }
  2521. bool String::is_valid_hex_number(bool p_with_prefix) const {
  2522. int from = 0;
  2523. int len = length();
  2524. if (len != 1 && (operator[](0) == '+' || operator[](0) == '-'))
  2525. from++;
  2526. if (p_with_prefix) {
  2527. if (len < 2)
  2528. return false;
  2529. if (operator[](from) != '0' || operator[](from + 1) != 'x') {
  2530. return false;
  2531. };
  2532. from += 2;
  2533. };
  2534. for (int i = from; i < len; i++) {
  2535. CharType c = operator[](i);
  2536. if ((c >= '0' && c <= '9') || (c >= 'a' && c <= 'f') || (c >= 'A' && c <= 'F'))
  2537. continue;
  2538. return false;
  2539. };
  2540. return true;
  2541. };
  2542. bool String::is_valid_float() const {
  2543. int len = length();
  2544. if (len == 0)
  2545. return false;
  2546. int from = 0;
  2547. if (operator[](0) == '+' || operator[](0) == '-') {
  2548. from++;
  2549. }
  2550. bool exponent_found = false;
  2551. bool period_found = false;
  2552. bool sign_found = false;
  2553. bool exponent_values_found = false;
  2554. bool numbers_found = false;
  2555. for (int i = from; i < len; i++) {
  2556. if (operator[](i) >= '0' && operator[](i) <= '9') {
  2557. if (exponent_found)
  2558. exponent_values_found = true;
  2559. else
  2560. numbers_found = true;
  2561. } else if (numbers_found && !exponent_found && operator[](i) == 'e') {
  2562. exponent_found = true;
  2563. } else if (!period_found && !exponent_found && operator[](i) == '.') {
  2564. period_found = true;
  2565. } else if ((operator[](i) == '-' || operator[](i) == '+') && exponent_found && !exponent_values_found && !sign_found) {
  2566. sign_found = true;
  2567. } else
  2568. return false; // no start with number plz
  2569. }
  2570. return numbers_found;
  2571. }
  2572. String String::path_to_file(const String &p_path) const {
  2573. String src = this->replace("\\", "/").get_base_dir();
  2574. String dst = p_path.replace("\\", "/").get_base_dir();
  2575. String rel = src.path_to(dst);
  2576. if (rel == dst) // failed
  2577. return p_path;
  2578. else
  2579. return rel + p_path.get_file();
  2580. }
  2581. String String::path_to(const String &p_path) const {
  2582. String src = this->replace("\\", "/");
  2583. String dst = p_path.replace("\\", "/");
  2584. if (!src.ends_with("/"))
  2585. src += "/";
  2586. if (!dst.ends_with("/"))
  2587. dst += "/";
  2588. String base;
  2589. if (src.begins_with("res://") && dst.begins_with("res://")) {
  2590. base = "res:/";
  2591. src = src.replace("res://", "/");
  2592. dst = dst.replace("res://", "/");
  2593. } else if (src.begins_with("user://") && dst.begins_with("user://")) {
  2594. base = "user:/";
  2595. src = src.replace("user://", "/");
  2596. dst = dst.replace("user://", "/");
  2597. } else if (src.begins_with("/") && dst.begins_with("/")) {
  2598. //nothing
  2599. } else {
  2600. //dos style
  2601. String src_begin = src.get_slicec('/', 0);
  2602. String dst_begin = dst.get_slicec('/', 0);
  2603. if (src_begin != dst_begin)
  2604. return p_path; //impossible to do this
  2605. base = src_begin;
  2606. src = src.substr(src_begin.length(), src.length());
  2607. dst = dst.substr(dst_begin.length(), dst.length());
  2608. }
  2609. //remove leading and trailing slash and split
  2610. Vector<String> src_dirs = src.substr(1, src.length() - 2).split("/");
  2611. Vector<String> dst_dirs = dst.substr(1, dst.length() - 2).split("/");
  2612. //find common parent
  2613. int common_parent = 0;
  2614. while (true) {
  2615. if (src_dirs.size() == common_parent)
  2616. break;
  2617. if (dst_dirs.size() == common_parent)
  2618. break;
  2619. if (src_dirs[common_parent] != dst_dirs[common_parent])
  2620. break;
  2621. common_parent++;
  2622. }
  2623. common_parent--;
  2624. String dir;
  2625. for (int i = src_dirs.size() - 1; i > common_parent; i--) {
  2626. dir += "../";
  2627. }
  2628. for (int i = common_parent + 1; i < dst_dirs.size(); i++) {
  2629. dir += dst_dirs[i] + "/";
  2630. }
  2631. if (dir.length() == 0)
  2632. dir = "./";
  2633. return dir;
  2634. }
  2635. bool String::is_valid_html_color() const {
  2636. return Color::html_is_valid(*this);
  2637. }
  2638. bool String::is_valid_ip_address() const {
  2639. if (find(":") >= 0) {
  2640. Vector<String> ip = split(":");
  2641. for (int i = 0; i < ip.size(); i++) {
  2642. String n = ip[i];
  2643. if (n.empty())
  2644. continue;
  2645. if (n.is_valid_hex_number(false)) {
  2646. int nint = n.hex_to_int(false);
  2647. if (nint < 0 || nint > 0xffff)
  2648. return false;
  2649. continue;
  2650. };
  2651. if (!n.is_valid_ip_address())
  2652. return false;
  2653. };
  2654. } else {
  2655. Vector<String> ip = split(".");
  2656. if (ip.size() != 4)
  2657. return false;
  2658. for (int i = 0; i < ip.size(); i++) {
  2659. String n = ip[i];
  2660. if (!n.is_valid_integer())
  2661. return false;
  2662. int val = n.to_int();
  2663. if (val < 0 || val > 255)
  2664. return false;
  2665. }
  2666. };
  2667. return true;
  2668. }
  2669. bool String::is_resource_file() const {
  2670. return begins_with("res://") && find("::") == -1;
  2671. }
  2672. bool String::is_rel_path() const {
  2673. return !is_abs_path();
  2674. }
  2675. String String::get_base_dir() const {
  2676. int basepos = find("://");
  2677. String rs;
  2678. String base;
  2679. if (basepos != -1) {
  2680. int end = basepos + 3;
  2681. rs = substr(end, length());
  2682. base = substr(0, end);
  2683. } else {
  2684. if (begins_with("/")) {
  2685. rs = substr(1, length());
  2686. base = "/";
  2687. } else {
  2688. rs = *this;
  2689. }
  2690. }
  2691. int sep = MAX(rs.find_last("/"), rs.find_last("\\"));
  2692. if (sep == -1)
  2693. return base;
  2694. return base + rs.substr(0, sep);
  2695. }
  2696. String String::get_file() const {
  2697. int sep = MAX(find_last("/"), find_last("\\"));
  2698. if (sep == -1)
  2699. return *this;
  2700. return substr(sep + 1, length());
  2701. }
  2702. String String::get_extension() const {
  2703. int pos = find_last(".");
  2704. if (pos < 0)
  2705. return *this;
  2706. return substr(pos + 1, length());
  2707. }
  2708. String String::plus_file(const String &p_file) const {
  2709. if (empty())
  2710. return p_file;
  2711. if (operator[](length() - 1) == '/' || (p_file.size() > 0 && p_file.operator[](0) == '/'))
  2712. return *this + p_file;
  2713. return *this + "/" + p_file;
  2714. }
  2715. String String::percent_encode() const {
  2716. CharString cs = utf8();
  2717. String encoded;
  2718. for (int i = 0; i < cs.length(); i++) {
  2719. uint8_t c = cs[i];
  2720. if ((c >= 'A' && c <= 'Z') || (c >= 'a' && c <= 'z') || (c >= '0' && c <= '9') || c == '-' || c == '_' || c == '~' || c == '.') {
  2721. char p[2] = { (char)c, 0 };
  2722. encoded += p;
  2723. } else {
  2724. char p[4] = { '%', 0, 0, 0 };
  2725. static const char hex[16] = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f' };
  2726. p[1] = hex[c >> 4];
  2727. p[2] = hex[c & 0xF];
  2728. encoded += p;
  2729. }
  2730. }
  2731. return encoded;
  2732. }
  2733. String String::percent_decode() const {
  2734. CharString pe;
  2735. CharString cs = utf8();
  2736. for (int i = 0; i < cs.length(); i++) {
  2737. uint8_t c = cs[i];
  2738. if (c == '%' && i < length() - 2) {
  2739. uint8_t a = LOWERCASE(cs[i + 1]);
  2740. uint8_t b = LOWERCASE(cs[i + 2]);
  2741. c = 0;
  2742. if (a >= '0' && a <= '9')
  2743. c = (a - '0') << 4;
  2744. else if (a >= 'a' && a <= 'f')
  2745. c = (a - 'a' + 10) << 4;
  2746. else
  2747. continue;
  2748. uint8_t d = 0;
  2749. if (b >= '0' && b <= '9')
  2750. d = (b - '0');
  2751. else if (b >= 'a' && b <= 'f')
  2752. d = (b - 'a' + 10);
  2753. else
  2754. continue;
  2755. c += d;
  2756. i += 2;
  2757. }
  2758. pe.push_back(c);
  2759. }
  2760. pe.push_back(0);
  2761. return String::utf8(pe.ptr());
  2762. }
  2763. String String::get_basename() const {
  2764. int pos = find_last(".");
  2765. if (pos < 0)
  2766. return *this;
  2767. return substr(0, pos);
  2768. }
  2769. String itos(int64_t p_val) {
  2770. return String::num_int64(p_val);
  2771. }
  2772. String rtos(double p_val) {
  2773. return String::num(p_val);
  2774. }
  2775. String rtoss(double p_val) {
  2776. return String::num_scientific(p_val);
  2777. }
  2778. // Right-pad with a character.
  2779. String String::rpad(int min_length, const String &character) const {
  2780. String s = *this;
  2781. int padding = min_length - s.length();
  2782. if (padding > 0) {
  2783. for (int i = 0; i < padding; i++)
  2784. s = s + character;
  2785. }
  2786. return s;
  2787. }
  2788. // Left-pad with a character.
  2789. String String::lpad(int min_length, const String &character) const {
  2790. String s = *this;
  2791. int padding = min_length - s.length();
  2792. if (padding > 0) {
  2793. for (int i = 0; i < padding; i++)
  2794. s = character + s;
  2795. }
  2796. return s;
  2797. }
  2798. // sprintf is implemented in GDScript via:
  2799. // "fish %s pie" % "frog"
  2800. // "fish %s %d pie" % ["frog", 12]
  2801. // In case of an error, the string returned is the error description and "error" is true.
  2802. String String::sprintf(const Array &values, bool *error) const {
  2803. String formatted;
  2804. CharType *self = (CharType *)c_str();
  2805. bool in_format = false;
  2806. int value_index = 0;
  2807. int min_chars = 0;
  2808. int min_decimals = 0;
  2809. bool in_decimals = false;
  2810. bool pad_with_zeroes = false;
  2811. bool left_justified = false;
  2812. bool show_sign = false;
  2813. *error = true;
  2814. for (; *self; self++) {
  2815. const CharType c = *self;
  2816. if (in_format) { // We have % - lets see what else we get.
  2817. switch (c) {
  2818. case '%': { // Replace %% with %
  2819. formatted += chr(c);
  2820. in_format = false;
  2821. break;
  2822. }
  2823. case 'd': // Integer (signed)
  2824. case 'o': // Octal
  2825. case 'x': // Hexadecimal (lowercase)
  2826. case 'X': { // Hexadecimal (uppercase)
  2827. if (value_index >= values.size()) {
  2828. return "not enough arguments for format string";
  2829. }
  2830. if (!values[value_index].is_num()) {
  2831. return "a number is required";
  2832. }
  2833. int64_t value = values[value_index];
  2834. int base = 16;
  2835. bool capitalize = false;
  2836. switch (c) {
  2837. case 'd': base = 10; break;
  2838. case 'o': base = 8; break;
  2839. case 'x': break;
  2840. case 'X':
  2841. base = 16;
  2842. capitalize = true;
  2843. break;
  2844. }
  2845. // Get basic number.
  2846. String str = String::num_int64(ABS(value), base, capitalize);
  2847. int number_len = str.length();
  2848. // Padding.
  2849. String pad_char = pad_with_zeroes ? String("0") : String(" ");
  2850. if (left_justified) {
  2851. str = str.rpad(min_chars, pad_char);
  2852. } else {
  2853. str = str.lpad(min_chars, pad_char);
  2854. }
  2855. // Sign.
  2856. if (show_sign && value >= 0) {
  2857. str = str.insert(pad_with_zeroes ? 0 : str.length() - number_len, "+");
  2858. } else if (value < 0) {
  2859. str = str.insert(pad_with_zeroes ? 0 : str.length() - number_len, "-");
  2860. }
  2861. formatted += str;
  2862. ++value_index;
  2863. in_format = false;
  2864. break;
  2865. }
  2866. case 'f': { // Float
  2867. if (value_index >= values.size()) {
  2868. return "not enough arguments for format string";
  2869. }
  2870. if (!values[value_index].is_num()) {
  2871. return "a number is required";
  2872. }
  2873. double value = values[value_index];
  2874. String str = String::num(value, min_decimals);
  2875. // Pad decimals out.
  2876. str = str.pad_decimals(min_decimals);
  2877. // Show sign
  2878. if (show_sign && value >= 0) {
  2879. str = str.insert(0, "+");
  2880. }
  2881. // Padding
  2882. if (left_justified) {
  2883. str = str.rpad(min_chars);
  2884. } else {
  2885. str = str.lpad(min_chars);
  2886. }
  2887. formatted += str;
  2888. ++value_index;
  2889. in_format = false;
  2890. break;
  2891. }
  2892. case 's': { // String
  2893. if (value_index >= values.size()) {
  2894. return "not enough arguments for format string";
  2895. }
  2896. String str = values[value_index];
  2897. // Padding.
  2898. if (left_justified) {
  2899. str = str.rpad(min_chars);
  2900. } else {
  2901. str = str.lpad(min_chars);
  2902. }
  2903. formatted += str;
  2904. ++value_index;
  2905. in_format = false;
  2906. break;
  2907. }
  2908. case 'c': {
  2909. if (value_index >= values.size()) {
  2910. return "not enough arguments for format string";
  2911. }
  2912. // Convert to character.
  2913. String str;
  2914. if (values[value_index].is_num()) {
  2915. int value = values[value_index];
  2916. if (value < 0) {
  2917. return "unsigned byte integer is lower than maximum";
  2918. } else if (value > 255) {
  2919. return "unsigned byte integer is greater than maximum";
  2920. }
  2921. str = chr(values[value_index]);
  2922. } else if (values[value_index].get_type() == Variant::STRING) {
  2923. str = values[value_index];
  2924. if (str.length() != 1) {
  2925. return "%c requires number or single-character string";
  2926. }
  2927. } else {
  2928. return "%c requires number or single-character string";
  2929. }
  2930. // Padding.
  2931. if (left_justified) {
  2932. str = str.rpad(min_chars);
  2933. } else {
  2934. str = str.lpad(min_chars);
  2935. }
  2936. formatted += str;
  2937. ++value_index;
  2938. in_format = false;
  2939. break;
  2940. }
  2941. case '-': { // Left justify
  2942. left_justified = true;
  2943. break;
  2944. }
  2945. case '+': { // Show + if positive.
  2946. show_sign = true;
  2947. break;
  2948. }
  2949. case '0':
  2950. case '1':
  2951. case '2':
  2952. case '3':
  2953. case '4':
  2954. case '5':
  2955. case '6':
  2956. case '7':
  2957. case '8':
  2958. case '9': {
  2959. int n = c - '0';
  2960. if (in_decimals) {
  2961. min_decimals *= 10;
  2962. min_decimals += n;
  2963. } else {
  2964. if (c == '0' && min_chars == 0) {
  2965. pad_with_zeroes = true;
  2966. } else {
  2967. min_chars *= 10;
  2968. min_chars += n;
  2969. }
  2970. }
  2971. break;
  2972. }
  2973. case '.': { // Float separator.
  2974. if (in_decimals) {
  2975. return "too many decimal points in format";
  2976. }
  2977. in_decimals = true;
  2978. min_decimals = 0; // We want to add the value manually.
  2979. break;
  2980. }
  2981. case '*': { // Dynamic width, based on value.
  2982. if (value_index >= values.size()) {
  2983. return "not enough arguments for format string";
  2984. }
  2985. if (!values[value_index].is_num()) {
  2986. return "* wants number";
  2987. }
  2988. int size = values[value_index];
  2989. if (in_decimals) {
  2990. min_decimals = size;
  2991. } else {
  2992. min_chars = size;
  2993. }
  2994. ++value_index;
  2995. break;
  2996. }
  2997. default: {
  2998. return "unsupported format character";
  2999. }
  3000. }
  3001. } else { // Not in format string.
  3002. switch (c) {
  3003. case '%':
  3004. in_format = true;
  3005. // Back to defaults:
  3006. min_chars = 0;
  3007. min_decimals = 6;
  3008. pad_with_zeroes = false;
  3009. left_justified = false;
  3010. show_sign = false;
  3011. in_decimals = false;
  3012. break;
  3013. default:
  3014. formatted += chr(c);
  3015. }
  3016. }
  3017. }
  3018. if (in_format) {
  3019. return "incomplete format";
  3020. }
  3021. if (value_index != values.size()) {
  3022. return "not all arguments converted during string formatting";
  3023. }
  3024. *error = false;
  3025. return formatted;
  3026. }
  3027. String String::quote(String quotechar) const {
  3028. return quotechar + *this + quotechar;
  3029. }
  3030. String String::unquote() const {
  3031. if (!is_quoted()) {
  3032. return *this;
  3033. }
  3034. return substr(1, length() - 2);
  3035. }
  3036. #include "translation.h"
  3037. #ifdef TOOLS_ENABLED
  3038. String TTR(const String &p_text) {
  3039. if (TranslationServer::get_singleton()) {
  3040. return TranslationServer::get_singleton()->tool_translate(p_text);
  3041. }
  3042. return p_text;
  3043. }
  3044. #endif
  3045. String RTR(const String &p_text) {
  3046. if (TranslationServer::get_singleton()) {
  3047. String rtr = TranslationServer::get_singleton()->tool_translate(p_text);
  3048. if (rtr == String() || rtr == p_text) {
  3049. return TranslationServer::get_singleton()->translate(p_text);
  3050. } else {
  3051. return rtr;
  3052. }
  3053. }
  3054. return p_text;
  3055. }