ustring.cpp 74 KB

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