ustring.cpp 66 KB

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