ustring.cpp 67 KB

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