ustring.cpp 68 KB

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