ustring.cpp 74 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166
  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. int String::to_int() const {
  1111. if (length()==0)
  1112. return 0;
  1113. int to=(find(".")>=0) ? find(".") : length() ;
  1114. int integer=0;
  1115. int sign=1;
  1116. for (int i=0;i<to;i++) {
  1117. CharType c=operator[](i);
  1118. if (c>='0' && c<='9') {
  1119. integer*=10;
  1120. integer+=c-'0';
  1121. } else if (integer==0 && c=='-') {
  1122. sign=-sign;
  1123. }
  1124. }
  1125. return integer*sign;
  1126. }
  1127. int64_t String::to_int64() const {
  1128. if (length()==0)
  1129. return 0;
  1130. int to=(find(".")>=0) ? find(".") : length() ;
  1131. int64_t integer=0;
  1132. int64_t sign=1;
  1133. for (int i=0;i<to;i++) {
  1134. CharType c=operator[](i);
  1135. if (c>='0' && c<='9') {
  1136. integer*=10;
  1137. integer+=c-'0';
  1138. } else if (integer==0 && c=='-') {
  1139. sign=-sign;
  1140. }
  1141. }
  1142. return integer*sign;
  1143. }
  1144. int String::to_int(const char* p_str,int p_len) {
  1145. int to=0;
  1146. if (p_len>=0)
  1147. to=p_len;
  1148. else {
  1149. while(p_str[to]!=0 && p_str[to]!='.')
  1150. to++;
  1151. }
  1152. int integer=0;
  1153. int sign=1;
  1154. for (int i=0;i<to;i++) {
  1155. char c=p_str[i];
  1156. if (c>='0' && c<='9') {
  1157. integer*=10;
  1158. integer+=c-'0';
  1159. } else if (c=='-' && integer==0) {
  1160. sign=-sign;
  1161. } else if (c!=' ')
  1162. break;
  1163. }
  1164. return integer*sign;
  1165. }
  1166. bool String::is_numeric() const {
  1167. if (length() == 0) {
  1168. return false;
  1169. };
  1170. int s = 0;
  1171. if (operator[](0) == '-') ++s;
  1172. bool dot = false;
  1173. for (int i=s; i<length(); i++) {
  1174. CharType c = operator[](i);
  1175. if (c == '.') {
  1176. if (dot) {
  1177. return false;
  1178. };
  1179. dot = true;
  1180. }
  1181. if (c < '0' || c > '9') {
  1182. return false;
  1183. };
  1184. };
  1185. return true; // TODO: Use the parser below for this instead
  1186. };
  1187. #define IS_DIGIT(m_d) ( (m_d)>='0' && (m_d)<='9' )
  1188. #define IS_HEX_DIGIT(m_d) ( ( (m_d)>='0' && (m_d)<='9' ) || ( (m_d)>='a' && (m_d)<='f' ) || ( (m_d)>='A' && (m_d)<='F' ) )
  1189. template<class C>
  1190. static double built_in_strtod(const C *string, /* A decimal ASCII floating-point number,
  1191. * optionally preceded by white space. Must
  1192. * have form "-I.FE-X", where I is the integer
  1193. * part of the mantissa, F is the fractional
  1194. * part of the mantissa, and X is the
  1195. * exponent. Either of the signs may be "+",
  1196. * "-", or omitted. Either I or F may be
  1197. * omitted, or both. The decimal point isn't
  1198. * necessary unless F is present. The "E" may
  1199. * actually be an "e". E and X may both be
  1200. * omitted (but not just one). */
  1201. C **endPtr=NULL) /* If non-NULL, store terminating Cacter's
  1202. * address here. */
  1203. {
  1204. static const int maxExponent = 511; /* Largest possible base 10 exponent. Any
  1205. * exponent larger than this will already
  1206. * produce underflow or overflow, so there's
  1207. * no need to worry about additional digits.
  1208. */
  1209. static const double powersOf10[] = { /* Table giving binary powers of 10. Entry */
  1210. 10., /* is 10^2^i. Used to convert decimal */
  1211. 100., /* exponents into floating-point numbers. */
  1212. 1.0e4,
  1213. 1.0e8,
  1214. 1.0e16,
  1215. 1.0e32,
  1216. 1.0e64,
  1217. 1.0e128,
  1218. 1.0e256
  1219. };
  1220. int sign, expSign = false;
  1221. double fraction, dblExp;
  1222. const double *d;
  1223. register const C *p;
  1224. register int c;
  1225. int exp = 0; /* Exponent read from "EX" field. */
  1226. int fracExp = 0; /* Exponent that derives from the fractional
  1227. * part. Under normal circumstatnces, it is
  1228. * the negative of the number of digits in F.
  1229. * However, if I is very long, the last digits
  1230. * of I get dropped (otherwise a long I with a
  1231. * large negative exponent could cause an
  1232. * unnecessary overflow on I alone). In this
  1233. * case, fracExp is incremented one for each
  1234. * dropped digit. */
  1235. int mantSize; /* Number of digits in mantissa. */
  1236. int decPt; /* Number of mantissa digits BEFORE decimal
  1237. * point. */
  1238. const C *pExp; /* Temporarily holds location of exponent in
  1239. * string. */
  1240. /*
  1241. * Strip off leading blanks and check for a sign.
  1242. */
  1243. p = string;
  1244. while (*p == ' ' || *p=='\t' || *p=='\n') {
  1245. p += 1;
  1246. }
  1247. if (*p == '-') {
  1248. sign = true;
  1249. p += 1;
  1250. } else {
  1251. if (*p == '+') {
  1252. p += 1;
  1253. }
  1254. sign = false;
  1255. }
  1256. /*
  1257. * Count the number of digits in the mantissa (including the decimal
  1258. * point), and also locate the decimal point.
  1259. */
  1260. decPt = -1;
  1261. for (mantSize = 0; ; mantSize += 1)
  1262. {
  1263. c = *p;
  1264. if (!IS_DIGIT(c)) {
  1265. if ((c != '.') || (decPt >= 0)) {
  1266. break;
  1267. }
  1268. decPt = mantSize;
  1269. }
  1270. p += 1;
  1271. }
  1272. /*
  1273. * Now suck up the digits in the mantissa. Use two integers to collect 9
  1274. * digits each (this is faster than using floating-point). If the mantissa
  1275. * has more than 18 digits, ignore the extras, since they can't affect the
  1276. * value anyway.
  1277. */
  1278. pExp = p;
  1279. p -= mantSize;
  1280. if (decPt < 0) {
  1281. decPt = mantSize;
  1282. } else {
  1283. mantSize -= 1; /* One of the digits was the point. */
  1284. }
  1285. if (mantSize > 18) {
  1286. fracExp = decPt - 18;
  1287. mantSize = 18;
  1288. } else {
  1289. fracExp = decPt - mantSize;
  1290. }
  1291. if (mantSize == 0) {
  1292. fraction = 0.0;
  1293. p = string;
  1294. goto done;
  1295. } else {
  1296. int frac1, frac2;
  1297. frac1 = 0;
  1298. for ( ; mantSize > 9; mantSize -= 1) {
  1299. c = *p;
  1300. p += 1;
  1301. if (c == '.') {
  1302. c = *p;
  1303. p += 1;
  1304. }
  1305. frac1 = 10*frac1 + (c - '0');
  1306. }
  1307. frac2 = 0;
  1308. for (; mantSize > 0; mantSize -= 1) {
  1309. c = *p;
  1310. p += 1;
  1311. if (c == '.') {
  1312. c = *p;
  1313. p += 1;
  1314. }
  1315. frac2 = 10*frac2 + (c - '0');
  1316. }
  1317. fraction = (1.0e9 * frac1) + frac2;
  1318. }
  1319. /*
  1320. * Skim off the exponent.
  1321. */
  1322. p = pExp;
  1323. if ((*p == 'E') || (*p == 'e')) {
  1324. p += 1;
  1325. if (*p == '-') {
  1326. expSign = true;
  1327. p += 1;
  1328. } else {
  1329. if (*p == '+') {
  1330. p += 1;
  1331. }
  1332. expSign = false;
  1333. }
  1334. if (!IS_DIGIT(CharType(*p))) {
  1335. p = pExp;
  1336. goto done;
  1337. }
  1338. while (IS_DIGIT(CharType(*p))) {
  1339. exp = exp * 10 + (*p - '0');
  1340. p += 1;
  1341. }
  1342. }
  1343. if (expSign) {
  1344. exp = fracExp - exp;
  1345. } else {
  1346. exp = fracExp + exp;
  1347. }
  1348. /*
  1349. * Generate a floating-point number that represents the exponent. Do this
  1350. * by processing the exponent one bit at a time to combine many powers of
  1351. * 2 of 10. Then combine the exponent with the fraction.
  1352. */
  1353. if (exp < 0) {
  1354. expSign = true;
  1355. exp = -exp;
  1356. } else {
  1357. expSign = false;
  1358. }
  1359. if (exp > maxExponent) {
  1360. exp = maxExponent;
  1361. WARN_PRINT("Exponent too high");
  1362. }
  1363. dblExp = 1.0;
  1364. for (d = powersOf10; exp != 0; exp >>= 1, ++d) {
  1365. if (exp & 01) {
  1366. dblExp *= *d;
  1367. }
  1368. }
  1369. if (expSign) {
  1370. fraction /= dblExp;
  1371. } else {
  1372. fraction *= dblExp;
  1373. }
  1374. done:
  1375. if (endPtr != NULL) {
  1376. *endPtr = (C *) p;
  1377. }
  1378. if (sign) {
  1379. return -fraction;
  1380. }
  1381. return fraction;
  1382. }
  1383. #define READING_SIGN 0
  1384. #define READING_INT 1
  1385. #define READING_DEC 2
  1386. #define READING_EXP 3
  1387. #define READING_DONE 4
  1388. double String::to_double(const char* p_str) {
  1389. #ifndef NO_USE_STDLIB
  1390. return built_in_strtod<char>(p_str);
  1391. //return atof(p_str); DOES NOT WORK ON ANDROID(??)
  1392. #else
  1393. return built_in_strtod<char>(p_str);
  1394. #endif
  1395. #if 0
  1396. #if 0
  1397. return atof(p_str);
  1398. #else
  1399. if (!p_str[0])
  1400. return 0;
  1401. ///@todo make more exact so saving and loading does not lose precision
  1402. double integer=0;
  1403. double decimal=0;
  1404. double decimal_mult=0.1;
  1405. double sign=1.0;
  1406. double exp=0;
  1407. double exp_sign=1.0;
  1408. int reading=READING_SIGN;
  1409. const char *str=p_str;
  1410. while(*str && reading!=READING_DONE) {
  1411. CharType c=*(str++);
  1412. switch(reading) {
  1413. case READING_SIGN: {
  1414. if (c>='0' && c<='9')
  1415. reading=READING_INT;
  1416. // let it fallthrough
  1417. else if (c=='-') {
  1418. sign=-1.0;
  1419. reading=READING_INT;
  1420. break;
  1421. } else if (c=='.') {
  1422. reading=READING_DEC;
  1423. break;
  1424. } else {
  1425. break;
  1426. }
  1427. }
  1428. case READING_INT: {
  1429. if (c>='0' && c<='9') {
  1430. integer*=10;
  1431. integer+=c-'0';
  1432. } else if (c=='.') {
  1433. reading=READING_DEC;
  1434. } else if (c=='e') {
  1435. reading=READING_EXP;
  1436. } else {
  1437. reading=READING_DONE;
  1438. }
  1439. } break;
  1440. case READING_DEC: {
  1441. if (c>='0' && c<='9') {
  1442. decimal+=(c-'0')*decimal_mult;
  1443. decimal_mult*=0.1;
  1444. } else if (c=='e') {
  1445. reading=READING_EXP;
  1446. } else {
  1447. reading=READING_DONE;
  1448. }
  1449. } break;
  1450. case READING_EXP: {
  1451. if (c>='0' && c<='9') {
  1452. exp*=10.0;
  1453. exp+=(c-'0');
  1454. } else if (c=='-' && exp==0) {
  1455. exp_sign=-1.0;
  1456. } else if (exp_sign>=0 && c=='+') {
  1457. //redundant...
  1458. exp_sign=1.0;
  1459. } else {
  1460. reading=READING_DONE;
  1461. }
  1462. } break;
  1463. }
  1464. }
  1465. return sign*(integer+decimal)*Math::pow(10,exp_sign*exp);
  1466. #endif
  1467. #endif
  1468. }
  1469. float String::to_float() const {
  1470. return to_double();
  1471. }
  1472. double String::to_double(const CharType* p_str, const CharType **r_end) {
  1473. return built_in_strtod<CharType>(p_str,(CharType**)r_end);
  1474. #if 0
  1475. #if 0
  1476. //ndef NO_USE_STDLIB
  1477. return wcstod(p_str,p_len<0?NULL:p_str+p_len);
  1478. #else
  1479. if (p_len==0 || !p_str[0])
  1480. return 0;
  1481. ///@todo make more exact so saving and loading does not lose precision
  1482. double integer=0;
  1483. double decimal=0;
  1484. double decimal_mult=0.1;
  1485. double sign=1.0;
  1486. double exp=0;
  1487. double exp_sign=1.0;
  1488. int reading=READING_SIGN;
  1489. const CharType *str=p_str;
  1490. const CharType *limit=&p_str[p_len];
  1491. while(reading!=READING_DONE && str!=limit) {
  1492. CharType c=*(str++);
  1493. switch(reading) {
  1494. case READING_SIGN: {
  1495. if (c>='0' && c<='9')
  1496. reading=READING_INT;
  1497. // let it fallthrough
  1498. else if (c=='-') {
  1499. sign=-1.0;
  1500. reading=READING_INT;
  1501. break;
  1502. } else if (c=='.') {
  1503. reading=READING_DEC;
  1504. break;
  1505. } else if (c==0) {
  1506. reading=READING_DONE;
  1507. break;
  1508. } else {
  1509. break;
  1510. }
  1511. }
  1512. case READING_INT: {
  1513. if (c>='0' && c<='9') {
  1514. integer*=10;
  1515. integer+=c-'0';
  1516. } else if (c=='.') {
  1517. reading=READING_DEC;
  1518. } else if (c=='e' || c=='E') {
  1519. reading=READING_EXP;
  1520. } else {
  1521. reading=READING_DONE;
  1522. }
  1523. } break;
  1524. case READING_DEC: {
  1525. if (c>='0' && c<='9') {
  1526. decimal+=(c-'0')*decimal_mult;
  1527. decimal_mult*=0.1;
  1528. } else if (c=='e' || c=='E') {
  1529. reading=READING_EXP;
  1530. } else {
  1531. reading=READING_DONE;
  1532. }
  1533. } break;
  1534. case READING_EXP: {
  1535. if (c>='0' && c<='9') {
  1536. exp*=10.0;
  1537. exp+=(c-'0');
  1538. } else if (c=='-' && exp==0) {
  1539. exp_sign=-1.0;
  1540. } else if (exp_sign>=0 && c=='+') {
  1541. //redundant...
  1542. exp_sign=1.0;
  1543. } else {
  1544. reading=READING_DONE;
  1545. }
  1546. } break;
  1547. }
  1548. }
  1549. if (r_end)
  1550. *r_end=str-1;
  1551. return sign*(integer+decimal)*Math::pow(10,exp_sign*exp);
  1552. #endif
  1553. #endif
  1554. }
  1555. int64_t String::to_int(const CharType* p_str,int p_len) {
  1556. if (p_len==0 || !p_str[0])
  1557. return 0;
  1558. ///@todo make more exact so saving and loading does not lose precision
  1559. int64_t integer=0;
  1560. int64_t sign=1;
  1561. int reading=READING_SIGN;
  1562. const CharType *str=p_str;
  1563. const CharType *limit=&p_str[p_len];
  1564. while(*str && reading!=READING_DONE && str!=limit) {
  1565. CharType c=*(str++);
  1566. switch(reading) {
  1567. case READING_SIGN: {
  1568. if (c>='0' && c<='9') {
  1569. reading=READING_INT;
  1570. // let it fallthrough
  1571. } else if (c=='-') {
  1572. sign=-1;
  1573. reading=READING_INT;
  1574. break;
  1575. } else if (c=='+') {
  1576. sign=1;
  1577. reading=READING_INT;
  1578. break;
  1579. } else {
  1580. break;
  1581. }
  1582. }
  1583. case READING_INT: {
  1584. if (c>='0' && c<='9') {
  1585. integer*=10;
  1586. integer+=c-'0';
  1587. } else {
  1588. reading=READING_DONE;
  1589. }
  1590. } break;
  1591. }
  1592. }
  1593. return sign*integer;
  1594. }
  1595. double String::to_double() const {
  1596. if (empty())
  1597. return 0;
  1598. #ifndef NO_USE_STDLIB
  1599. return built_in_strtod<CharType>(c_str());
  1600. //return wcstod(c_str(),NULL); DOES NOT WORK ON ANDROID :(
  1601. #else
  1602. return built_in_strtod<CharType>(c_str());
  1603. #endif
  1604. #if 0
  1605. #ifndef NO_USE_STDLIB
  1606. return atof(utf8().get_data());
  1607. #else
  1608. double integer=0;
  1609. double decimal=0;
  1610. double decimal_mult=0.1;
  1611. double sign=1.0;
  1612. double exp=0;
  1613. double exp_sign=1.0;
  1614. int reading=READING_SIGN;
  1615. const CharType *str=&operator[](0);
  1616. while(*str && reading!=READING_DONE) {
  1617. CharType c=*(str++);
  1618. switch(reading) {
  1619. case READING_SIGN: {
  1620. if (c>='0' && c<='9')
  1621. reading=READING_INT;
  1622. // let it fallthrough
  1623. else if (c=='-') {
  1624. sign=-1.0;
  1625. reading=READING_INT;
  1626. break;
  1627. } else if (c=='.') {
  1628. reading=READING_DEC;
  1629. break;
  1630. } else {
  1631. break;
  1632. }
  1633. }
  1634. case READING_INT: {
  1635. if (c>='0' && c<='9') {
  1636. integer*=10;
  1637. integer+=c-'0';
  1638. } else if (c=='.') {
  1639. reading=READING_DEC;
  1640. } else if (c=='e') {
  1641. reading=READING_EXP;
  1642. } else {
  1643. reading=READING_DONE;
  1644. }
  1645. } break;
  1646. case READING_DEC: {
  1647. if (c>='0' && c<='9') {
  1648. decimal+=(c-'0')*decimal_mult;
  1649. decimal_mult*=0.1;
  1650. } else if (c=='e') {
  1651. reading=READING_EXP;
  1652. } else {
  1653. reading=READING_DONE;
  1654. }
  1655. } break;
  1656. case READING_EXP: {
  1657. if (c>='0' && c<='9') {
  1658. exp*=10.0;
  1659. exp+=(c-'0');
  1660. } else if (c=='-' && exp==0) {
  1661. exp_sign=-1.0;
  1662. } else if (exp_sign>=0 && c=='+') {
  1663. //redundant...
  1664. exp_sign=1.0;
  1665. } else {
  1666. reading=READING_DONE;
  1667. }
  1668. } break;
  1669. }
  1670. }
  1671. return sign*(integer+decimal)*Math::pow(10,exp_sign*exp);
  1672. #endif
  1673. #if 0
  1674. double ret=sign*(integer+decimal)*Math::pow(10,exp_sign*exp);
  1675. print_line(*this +" == "+rtos(ret));
  1676. return ret;
  1677. #endif
  1678. #endif
  1679. }
  1680. bool operator==(const char*p_chr, const String& p_str) {
  1681. return p_str==p_chr;
  1682. }
  1683. String operator+(const char*p_chr, const String& p_str) {
  1684. String tmp=p_chr;
  1685. tmp+=p_str;
  1686. return tmp;
  1687. }
  1688. String operator+(CharType p_chr, const String& p_str) {
  1689. return (String::chr(p_chr)+p_str);
  1690. }
  1691. uint32_t String::hash(const char* p_cstr) {
  1692. uint32_t hashv = 5381;
  1693. uint32_t c;
  1694. while ((c = *p_cstr++))
  1695. hashv = ((hashv << 5) + hashv) + c; /* hash * 33 + c */
  1696. return hashv;
  1697. }
  1698. uint32_t String::hash(const char* p_cstr,int p_len) {
  1699. uint32_t hashv = 5381;
  1700. for(int i=0;i<p_len;i++)
  1701. hashv = ((hashv << 5) + hashv) + p_cstr[i]; /* hash * 33 + c */
  1702. return hashv;
  1703. }
  1704. uint32_t String::hash(const CharType* p_cstr,int p_len) {
  1705. uint32_t hashv = 5381;
  1706. for(int i=0;i<p_len;i++)
  1707. hashv = ((hashv << 5) + hashv) + p_cstr[i]; /* hash * 33 + c */
  1708. return hashv;
  1709. }
  1710. uint32_t String::hash(const CharType* p_cstr) {
  1711. uint32_t hashv = 5381;
  1712. uint32_t c;
  1713. while ((c = *p_cstr++))
  1714. hashv = ((hashv << 5) + hashv) + c; /* hash * 33 + c */
  1715. return hashv;
  1716. }
  1717. uint32_t String::hash() const {
  1718. /* simple djb2 hashing */
  1719. const CharType * chr = c_str();
  1720. uint32_t hashv = 5381;
  1721. uint32_t c;
  1722. while ((c = *chr++))
  1723. hashv = ((hashv << 5) + hashv) + c; /* hash * 33 + c */
  1724. return hashv;
  1725. }
  1726. uint64_t String::hash64() const {
  1727. /* simple djb2 hashing */
  1728. const CharType * chr = c_str();
  1729. uint64_t hashv = 5381;
  1730. uint64_t c;
  1731. while ((c = *chr++))
  1732. hashv = ((hashv << 5) + hashv) + c; /* hash * 33 + c */
  1733. return hashv;
  1734. }
  1735. String String::md5_text() const {
  1736. CharString cs=utf8();
  1737. MD5_CTX ctx;
  1738. MD5Init(&ctx);
  1739. MD5Update(&ctx,(unsigned char*)cs.ptr(),cs.length());
  1740. MD5Final(&ctx);
  1741. return String::md5(ctx.digest);
  1742. }
  1743. String String::sha256_text() const {
  1744. CharString cs=utf8();
  1745. unsigned char hash[32];
  1746. sha256_context ctx;
  1747. sha256_init(&ctx);
  1748. sha256_hash(&ctx,(unsigned char*)cs.ptr(),cs.length());
  1749. sha256_done(&ctx, hash);
  1750. return String::hex_encode_buffer(hash, 32);
  1751. }
  1752. Vector<uint8_t> String::md5_buffer() const {
  1753. CharString cs=utf8();
  1754. MD5_CTX ctx;
  1755. MD5Init(&ctx);
  1756. MD5Update(&ctx,(unsigned char*)cs.ptr(),cs.length());
  1757. MD5Final(&ctx);
  1758. Vector<uint8_t> ret;
  1759. ret.resize(16);
  1760. for (int i=0; i<16; i++) {
  1761. ret[i] = ctx.digest[i];
  1762. };
  1763. return ret;
  1764. };
  1765. Vector<uint8_t> String::sha256_buffer() const {
  1766. CharString cs = utf8();
  1767. unsigned char hash[32];
  1768. sha256_context ctx;
  1769. sha256_init(&ctx);
  1770. sha256_hash(&ctx, (unsigned char*)cs.ptr(), cs.length());
  1771. sha256_done(&ctx, hash);
  1772. Vector<uint8_t> ret;
  1773. ret.resize(32);
  1774. for (int i = 0; i < 32; i++) {
  1775. ret[i] = hash[i];
  1776. }
  1777. return ret;
  1778. }
  1779. String String::insert(int p_at_pos,String p_string) const {
  1780. if (p_at_pos<0)
  1781. return *this;
  1782. if (p_at_pos>length())
  1783. p_at_pos=length();
  1784. String pre;
  1785. if (p_at_pos>0)
  1786. pre=substr( 0, p_at_pos );
  1787. String post;
  1788. if (p_at_pos<length())
  1789. post=substr( p_at_pos, length()-p_at_pos);
  1790. return pre+p_string+post;
  1791. }
  1792. String String::substr(int p_from,int p_chars) const{
  1793. if (empty() || p_from<0 || p_from>=length() || p_chars<=0)
  1794. return "";
  1795. if ( (p_from+p_chars)>length()) {
  1796. p_chars=length()-p_from;
  1797. }
  1798. return String(&c_str()[p_from],p_chars);
  1799. }
  1800. int String::find_last(String p_str) const {
  1801. int pos=-1;
  1802. int findfrom=0;
  1803. int findres=-1;
  1804. while((findres=find(p_str,findfrom))!=-1) {
  1805. pos=findres;
  1806. findfrom=pos+1;
  1807. }
  1808. return pos;
  1809. }
  1810. int String::find(String p_str,int p_from) const {
  1811. if (p_from<0)
  1812. return -1;
  1813. int src_len=p_str.length();
  1814. int len=length();
  1815. if(src_len==0 || len==0)
  1816. return -1; //wont find anything!
  1817. const CharType *src = c_str();
  1818. for (int i=p_from;i<=(len-src_len);i++) {
  1819. bool found=true;
  1820. for (int j=0;j<src_len;j++) {
  1821. int read_pos=i+j;
  1822. if (read_pos>=len) {
  1823. ERR_PRINT("read_pos>=len");
  1824. return -1;
  1825. };
  1826. if (src[read_pos]!=p_str[j]) {
  1827. found=false;
  1828. break;
  1829. }
  1830. }
  1831. if (found)
  1832. return i;
  1833. }
  1834. return -1;
  1835. }
  1836. int String::findmk(const Vector<String>& p_keys,int p_from,int *r_key) const {
  1837. if (p_from<0)
  1838. return -1;
  1839. if (p_keys.size()==0)
  1840. return -1;
  1841. //int src_len=p_str.length();
  1842. const String *keys=&p_keys[0];
  1843. int key_count=p_keys.size();
  1844. int len = length();
  1845. if(len==0)
  1846. return -1; //wont find anything!
  1847. const CharType *src = c_str();
  1848. for (int i=p_from;i<len;i++) {
  1849. bool found=true;
  1850. for(int k=0;k<key_count;k++) {
  1851. found=true;
  1852. if (r_key)
  1853. *r_key=k;
  1854. const CharType *cmp=keys[k].c_str();
  1855. int l=keys[k].length();
  1856. for (int j=0;j<l;j++) {
  1857. int read_pos=i+j;
  1858. if (read_pos>=len) {
  1859. found=false;
  1860. break;
  1861. };
  1862. if (src[read_pos]!=cmp[j]) {
  1863. found=false;
  1864. break;
  1865. }
  1866. }
  1867. if (found)
  1868. break;
  1869. }
  1870. if (found)
  1871. return i;
  1872. }
  1873. return -1;
  1874. }
  1875. int String::findn(String p_str,int p_from) const {
  1876. if (p_from<0)
  1877. return -1;
  1878. int src_len=p_str.length();
  1879. if(src_len==0 || length()==0)
  1880. return -1; //wont find anything!
  1881. const CharType *srcd = c_str();
  1882. for (int i=p_from;i<=(length()-src_len);i++) {
  1883. bool found=true;
  1884. for (int j=0;j<src_len;j++) {
  1885. int read_pos=i+j;
  1886. if (read_pos>=length()) {
  1887. ERR_PRINT("read_pos>=length()");
  1888. return -1;
  1889. };
  1890. CharType src=_find_lower(srcd[read_pos]);
  1891. CharType dst=_find_lower(p_str[j]);
  1892. if (src!=dst) {
  1893. found=false;
  1894. break;
  1895. }
  1896. }
  1897. if (found)
  1898. return i;
  1899. }
  1900. return -1;
  1901. }
  1902. int String::rfind(String p_str,int p_from) const {
  1903. //stabilish a limit
  1904. int limit = length()-p_str.length();
  1905. if (limit<0)
  1906. return -1;
  1907. //stabilish a starting point
  1908. if (p_from<0)
  1909. p_from=limit;
  1910. else if (p_from>limit)
  1911. p_from=limit;
  1912. int src_len=p_str.length();
  1913. int len=length();
  1914. if(src_len==0 || len==0)
  1915. return -1; //wont find anything!
  1916. const CharType *src = c_str();
  1917. for (int i=p_from;i>=0;i--) {
  1918. bool found=true;
  1919. for (int j=0;j<src_len;j++) {
  1920. int read_pos=i+j;
  1921. if (read_pos>=len) {
  1922. ERR_PRINT("read_pos>=len");
  1923. return -1;
  1924. };
  1925. if (src[read_pos]!=p_str[j]) {
  1926. found=false;
  1927. break;
  1928. }
  1929. }
  1930. if (found)
  1931. return i;
  1932. }
  1933. return -1;
  1934. }
  1935. int String::rfindn(String p_str,int p_from) const {
  1936. //stabilish a limit
  1937. int limit = length()-p_str.length();
  1938. if (limit<0)
  1939. return -1;
  1940. //stabilish a starting point
  1941. if (p_from<0)
  1942. p_from=limit;
  1943. else if (p_from>limit)
  1944. p_from=limit;
  1945. int src_len=p_str.length();
  1946. int len=length();
  1947. if(src_len==0 || len==0)
  1948. return -1; //wont find anything!
  1949. const CharType *src = c_str();
  1950. for (int i=p_from;i>=0;i--) {
  1951. bool found=true;
  1952. for (int j=0;j<src_len;j++) {
  1953. int read_pos=i+j;
  1954. if (read_pos>=len) {
  1955. ERR_PRINT("read_pos>=len");
  1956. return -1;
  1957. };
  1958. CharType srcc=_find_lower(src[read_pos]);
  1959. CharType dstc=_find_lower(p_str[j]);
  1960. if (srcc!=dstc) {
  1961. found=false;
  1962. break;
  1963. }
  1964. }
  1965. if (found)
  1966. return i;
  1967. }
  1968. return -1;
  1969. }
  1970. bool String::ends_with(const String& p_string) const {
  1971. int pos = find_last(p_string);
  1972. if (pos==-1)
  1973. return false;
  1974. return pos+p_string.length()==length();
  1975. }
  1976. bool String::begins_with(const String& p_string) const {
  1977. if (p_string.length() > length())
  1978. return false;
  1979. int l=p_string.length();
  1980. if (l==0)
  1981. return true;
  1982. const CharType *src=&p_string[0];
  1983. const CharType *str=&operator[](0);
  1984. int i = 0;
  1985. for (;i<l;i++) {
  1986. if (src[i]!=str[i])
  1987. return false;
  1988. }
  1989. // only if i == l the p_string matches the beginning
  1990. return i == l;
  1991. }
  1992. bool String::begins_with(const char* p_string) const {
  1993. int l=length();
  1994. if (l==0||!p_string)
  1995. return false;
  1996. const CharType *str=&operator[](0);
  1997. int i=0;
  1998. while (*p_string && i<l) {
  1999. if (*p_string != str[i])
  2000. return false;
  2001. i++;
  2002. p_string++;
  2003. }
  2004. return *p_string == 0;
  2005. }
  2006. bool String::is_subsequence_of(const String& p_string) const {
  2007. return _base_is_subsequence_of(p_string, false);
  2008. }
  2009. bool String::is_subsequence_ofi(const String& p_string) const {
  2010. return _base_is_subsequence_of(p_string, true);
  2011. }
  2012. bool String::_base_is_subsequence_of(const String& p_string, bool case_insensitive) const {
  2013. int len=length();
  2014. if (len == 0) {
  2015. // Technically an empty string is subsequence of any string
  2016. return true;
  2017. }
  2018. if (len > p_string.length()) {
  2019. return false;
  2020. }
  2021. const CharType *src = &operator[](0);
  2022. const CharType *tgt = &p_string[0];
  2023. for (;*src && *tgt;tgt++) {
  2024. bool match = false;
  2025. if (case_insensitive) {
  2026. CharType srcc = _find_lower(*src);
  2027. CharType tgtc = _find_lower(*tgt);
  2028. match = srcc == tgtc;
  2029. } else {
  2030. match = *src == *tgt;
  2031. }
  2032. if (match) {
  2033. src++;
  2034. if(!*src) {
  2035. return true;
  2036. }
  2037. }
  2038. }
  2039. return false;
  2040. }
  2041. Vector<String> String::bigrams() const {
  2042. int n_pairs = length() - 1;
  2043. Vector<String> b;
  2044. if(n_pairs <= 0) {
  2045. return b;
  2046. }
  2047. b.resize(n_pairs);
  2048. for(int i = 0; i < n_pairs; i++) {
  2049. b[i] = substr(i,2);
  2050. }
  2051. return b;
  2052. }
  2053. // Similarity according to Sorensen-Dice coefficient
  2054. float String::similarity(const String& p_string) const {
  2055. if(operator==(p_string)) {
  2056. // Equal strings are totally similar
  2057. return 1.0f;
  2058. }
  2059. if (length() < 2 || p_string.length() < 2) {
  2060. // No way to calculate similarity without a single bigram
  2061. return 0.0f;
  2062. }
  2063. Vector<String> src_bigrams = bigrams();
  2064. Vector<String> tgt_bigrams = p_string.bigrams();
  2065. int src_size = src_bigrams.size();
  2066. int tgt_size = tgt_bigrams.size();
  2067. float sum = src_size + tgt_size;
  2068. float inter = 0;
  2069. for (int i = 0; i < src_size; i++) {
  2070. for (int j = 0; j < tgt_size; j++) {
  2071. if (src_bigrams[i] == tgt_bigrams[j]) {
  2072. inter++;
  2073. break;
  2074. }
  2075. }
  2076. }
  2077. return (2.0f * inter)/sum;
  2078. }
  2079. static bool _wildcard_match(const CharType* p_pattern, const CharType* p_string,bool p_case_sensitive) {
  2080. switch (*p_pattern) {
  2081. case '\0':
  2082. return !*p_string;
  2083. case '*' :
  2084. return _wildcard_match(p_pattern+1, p_string,p_case_sensitive) || (*p_string && _wildcard_match(p_pattern, p_string+1,p_case_sensitive));
  2085. case '?' :
  2086. return *p_string && (*p_string != '.') && _wildcard_match(p_pattern+1, p_string+1,p_case_sensitive);
  2087. default :
  2088. 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);
  2089. }
  2090. }
  2091. bool String::match(const String& p_wildcard) const {
  2092. if (!p_wildcard.length() || !length())
  2093. return false;
  2094. return _wildcard_match(p_wildcard.c_str(),c_str(),true);
  2095. }
  2096. bool String::matchn(const String& p_wildcard) const {
  2097. if (!p_wildcard.length() || !length())
  2098. return false;
  2099. return _wildcard_match(p_wildcard.c_str(),c_str(),false);
  2100. }
  2101. String String::replace(String p_key,String p_with) const {
  2102. String new_string;
  2103. int search_from=0;
  2104. int result=0;
  2105. while( (result=find(p_key,search_from))>=0 ) {
  2106. new_string+=substr(search_from,result-search_from);
  2107. new_string+=p_with;
  2108. search_from=result+p_key.length();
  2109. }
  2110. new_string+=substr(search_from,length()-search_from);
  2111. return new_string;
  2112. }
  2113. String String::replace_first(String p_key,String p_with) const {
  2114. String new_string;
  2115. int search_from=0;
  2116. int result=0;
  2117. while( (result=find(p_key,search_from))>=0 ) {
  2118. new_string+=substr(search_from,result-search_from);
  2119. new_string+=p_with;
  2120. search_from=result+p_key.length();
  2121. break;
  2122. }
  2123. new_string+=substr(search_from,length()-search_from);
  2124. return new_string;
  2125. }
  2126. String String::replacen(String p_key,String p_with) const {
  2127. String new_string;
  2128. int search_from=0;
  2129. int result=0;
  2130. while( (result=findn(p_key,search_from))>=0 ) {
  2131. new_string+=substr(search_from,result-search_from);
  2132. new_string+=p_with;
  2133. search_from=result+p_key.length();
  2134. }
  2135. new_string+=substr(search_from,length()-search_from);
  2136. return new_string;
  2137. }
  2138. String String::left(int p_pos) const {
  2139. if (p_pos<=0)
  2140. return "";
  2141. if (p_pos>=length())
  2142. return *this;
  2143. return substr(0,p_pos);
  2144. }
  2145. String String::right(int p_pos) const {
  2146. if (p_pos>=size())
  2147. return *this;
  2148. if (p_pos<0)
  2149. return "";
  2150. return substr(p_pos,(length()-p_pos));
  2151. }
  2152. CharType String::ord_at(int p_idx) const {
  2153. ERR_FAIL_INDEX_V(p_idx, length(), 0);
  2154. return operator[](p_idx);
  2155. }
  2156. String String::strip_edges(bool left, bool right) const {
  2157. int len=length();
  2158. int beg=0,end=len;
  2159. if(left) {
  2160. for (int i=0;i<len;i++) {
  2161. if (operator[](i)<=32)
  2162. beg++;
  2163. else
  2164. break;
  2165. }
  2166. }
  2167. if(right) {
  2168. for (int i=(int)(len-1);i>=0;i--) {
  2169. if (operator[](i)<=32)
  2170. end--;
  2171. else
  2172. break;
  2173. }
  2174. }
  2175. if (beg==0 && end==len)
  2176. return *this;
  2177. return substr(beg,end-beg);
  2178. }
  2179. String String::strip_escapes() const {
  2180. int len=length();
  2181. int beg=0,end=len;
  2182. for (int i=0;i<length();i++) {
  2183. if (operator[](i)<=31)
  2184. beg++;
  2185. else
  2186. break;
  2187. }
  2188. for (int i=(int)(length()-1);i>=0;i--) {
  2189. if (operator[](i)<=31)
  2190. end--;
  2191. else
  2192. break;
  2193. }
  2194. if (beg==0 && end==len)
  2195. return *this;
  2196. return substr(beg,end-beg);
  2197. }
  2198. String String::simplify_path() const {
  2199. String s = *this;
  2200. String drive;
  2201. if (s.begins_with("local://")) {
  2202. drive="local://";
  2203. s=s.substr(8,s.length());
  2204. } else if (s.begins_with("res://")) {
  2205. drive="res://";
  2206. s=s.substr(6,s.length());
  2207. } else if (s.begins_with("user://")) {
  2208. drive="user://";
  2209. s=s.substr(6,s.length());
  2210. } else if (s.begins_with("/") || s.begins_with("\\")) {
  2211. drive=s.substr(0,1);
  2212. s=s.substr(1,s.length()-1);
  2213. } else {
  2214. int p = s.find(":/");
  2215. if (p==-1)
  2216. p=s.find(":\\");
  2217. if (p!=-1 && p < s.find("/")) {
  2218. drive=s.substr(0,p+2);
  2219. s=s.substr(p+2,s.length());
  2220. }
  2221. }
  2222. s =s.replace("\\","/");
  2223. while(true){ // in case of using 2 or more slash
  2224. String compare = s.replace("//","/");
  2225. if (s==compare) break;
  2226. else s=compare;
  2227. }
  2228. Vector<String> dirs = s.split("/",false);
  2229. for(int i=0;i<dirs.size();i++) {
  2230. String d = dirs[i];
  2231. if (d==".") {
  2232. dirs.remove(i);
  2233. i--;
  2234. } else if (d=="..") {
  2235. if (i==0) {
  2236. dirs.remove(i);
  2237. i--;
  2238. } else {
  2239. dirs.remove(i);
  2240. dirs.remove(i-1);
  2241. i-=2;
  2242. }
  2243. }
  2244. }
  2245. s="";
  2246. for(int i=0;i<dirs.size();i++) {
  2247. if (i>0)
  2248. s+="/";
  2249. s+=dirs[i];
  2250. }
  2251. return drive+s;
  2252. }
  2253. static int _humanize_digits(int p_num) {
  2254. if (p_num<10)
  2255. return 2;
  2256. else if (p_num<100)
  2257. return 2;
  2258. else if (p_num<1024)
  2259. return 1;
  2260. else
  2261. return 0;
  2262. }
  2263. String String::humanize_size(size_t p_size) {
  2264. uint64_t _div=1;
  2265. static const char* prefix[]={" Bytes"," KB"," MB"," GB","TB"," PB","HB",""};
  2266. int prefix_idx=0;
  2267. while(p_size>(_div*1024) && prefix[prefix_idx][0]) {
  2268. _div*=1024;
  2269. prefix_idx++;
  2270. }
  2271. int digits=prefix_idx>0?_humanize_digits(p_size/_div):0;
  2272. double divisor = prefix_idx>0?_div:1;
  2273. return String::num(p_size/divisor,digits)+prefix[prefix_idx];
  2274. }
  2275. bool String::is_abs_path() const {
  2276. if (length()>1)
  2277. return (operator[](0)=='/' || operator[](0)=='\\' || find(":/")!=-1 || find(":\\")!=-1);
  2278. else if ((length())==1)
  2279. return (operator[](0)=='/' || operator[](0)=='\\');
  2280. else
  2281. return false;
  2282. }
  2283. bool String::is_valid_identifier() const {
  2284. int len = length();
  2285. if (len==0)
  2286. return false;
  2287. const wchar_t * str = &operator[](0);
  2288. for(int i=0;i<len;i++) {
  2289. if (i==0) {
  2290. if (str[0]>='0' && str[0]<='9')
  2291. return false; // no start with number plz
  2292. }
  2293. bool valid_char = (str[i]>='0' && str[i]<='9') || (str[i]>='a' && str[i]<='z') || (str[i]>='A' && str[i]<='Z') || str[i]=='_';
  2294. if (!valid_char)
  2295. return false;
  2296. }
  2297. return true;
  2298. }
  2299. //kind of poor should be rewritten properly
  2300. String String::word_wrap(int p_chars_per_line) const {
  2301. int from=0;
  2302. int last_space=0;
  2303. String ret;
  2304. for(int i=0;i<length();i++) {
  2305. if (i-from>=p_chars_per_line) {
  2306. if (last_space==-1) {
  2307. ret+=substr(from,i-from+1)+"\n";
  2308. } else {
  2309. ret+=substr(from,last_space-from)+"\n";
  2310. i=last_space; //rewind
  2311. }
  2312. from=i+1;
  2313. last_space=-1;
  2314. } else if (operator[](i)==' ' || operator[](i)=='\t') {
  2315. last_space=i;
  2316. } else if (operator[](i)=='\n') {
  2317. ret+=substr(from,i-from)+"\n";
  2318. from=i+1;
  2319. last_space=-1;
  2320. }
  2321. }
  2322. if (from<length()) {
  2323. ret+=substr(from,length());
  2324. }
  2325. return ret;
  2326. }
  2327. String String::http_escape() const {
  2328. const CharString temp = utf8();
  2329. String res;
  2330. for (int i = 0; i < length(); ++i) {
  2331. CharType ord = temp[i];
  2332. if (ord == '.' || ord == '-' || ord == '_' || ord == '~' ||
  2333. (ord >= 'a' && ord <= 'z') ||
  2334. (ord >= 'A' && ord <= 'Z') ||
  2335. (ord >= '0' && ord <= '9')) {
  2336. res += ord;
  2337. } else {
  2338. char h_Val[3];
  2339. #if defined(__GNUC__) || defined(_MSC_VER)
  2340. snprintf(h_Val, 3, "%.2X", ord);
  2341. #else
  2342. sprintf(h_Val, "%.2X", ord);
  2343. #endif
  2344. res += "%";
  2345. res += h_Val;
  2346. }
  2347. }
  2348. return res;
  2349. }
  2350. String String::http_unescape() const {
  2351. String res;
  2352. for (int i = 0; i < length(); ++i) {
  2353. if (ord_at(i) == '%' && i+2 < length()) {
  2354. CharType ord1 = ord_at(i+1);
  2355. if ((ord1 >= '0' && ord1 <= '9') || (ord1 >= 'A' && ord1 <= 'Z')) {
  2356. CharType ord2 = ord_at(i+2);
  2357. if ((ord2 >= '0' && ord2 <= '9') || (ord2 >= 'A' && ord2 <= 'Z')) {
  2358. char bytes[2] = {ord1, ord2};
  2359. res += (char)strtol(bytes, NULL, 16);
  2360. i+=2;
  2361. }
  2362. } else {
  2363. res += ord_at(i);
  2364. }
  2365. } else {
  2366. res += ord_at(i);
  2367. }
  2368. }
  2369. return String::utf8(res.ascii());
  2370. }
  2371. String String::c_unescape() const {
  2372. String escaped=*this;
  2373. escaped=escaped.replace("\\a","\a");
  2374. escaped=escaped.replace("\\b","\b");
  2375. escaped=escaped.replace("\\f","\f");
  2376. escaped=escaped.replace("\\n","\n");
  2377. escaped=escaped.replace("\\r","\r");
  2378. escaped=escaped.replace("\\t","\t");
  2379. escaped=escaped.replace("\\v","\v");
  2380. escaped=escaped.replace("\\'","\'");
  2381. escaped=escaped.replace("\\\"","\"");
  2382. escaped=escaped.replace("\\?","\?");
  2383. escaped=escaped.replace("\\\\","\\");
  2384. return escaped;
  2385. }
  2386. String String::c_escape() const {
  2387. String escaped=*this;
  2388. escaped=escaped.replace("\\","\\\\");
  2389. escaped=escaped.replace("\a","\\a");
  2390. escaped=escaped.replace("\b","\\b");
  2391. escaped=escaped.replace("\f","\\f");
  2392. escaped=escaped.replace("\n","\\n");
  2393. escaped=escaped.replace("\r","\\r");
  2394. escaped=escaped.replace("\t","\\t");
  2395. escaped=escaped.replace("\v","\\v");
  2396. escaped=escaped.replace("\'","\\'");
  2397. escaped=escaped.replace("\"","\\\"");
  2398. escaped=escaped.replace("\?","\\?");
  2399. return escaped;
  2400. }
  2401. String String::json_escape() const {
  2402. String escaped=*this;
  2403. escaped=escaped.replace("\\","\\\\");
  2404. escaped=escaped.replace("\b","\\b");
  2405. escaped=escaped.replace("\f","\\f");
  2406. escaped=escaped.replace("\n","\\n");
  2407. escaped=escaped.replace("\r","\\r");
  2408. escaped=escaped.replace("\t","\\t");
  2409. escaped=escaped.replace("\v","\\v");
  2410. escaped=escaped.replace("\"","\\\"");
  2411. return escaped;
  2412. }
  2413. String String::xml_escape(bool p_escape_quotes) const {
  2414. String str=*this;
  2415. str=str.replace("&","&amp;");
  2416. str=str.replace("<","&lt;");
  2417. str=str.replace(">","&gt;");
  2418. if (p_escape_quotes) {
  2419. str=str.replace("'","&apos;");
  2420. str=str.replace("\"","&quot;");
  2421. }
  2422. /*
  2423. for (int i=1;i<32;i++) {
  2424. char chr[2]={i,0};
  2425. str=str.replace(chr,"&#"+String::num(i)+";");
  2426. }*/
  2427. return str;
  2428. }
  2429. static _FORCE_INLINE_ int _xml_unescape(const CharType *p_src,int p_src_len,CharType *p_dst) {
  2430. int len=0;
  2431. while(p_src_len) {
  2432. if (*p_src=='&') {
  2433. int eat=0;
  2434. if (p_src_len>=4 && p_src[1]=='#') {
  2435. CharType c=0;
  2436. for(int i=2;i<p_src_len;i++) {
  2437. eat=i+1;
  2438. CharType ct=p_src[i];
  2439. if (ct==';') {
  2440. break;
  2441. } else if (ct>='0' && ct<='9') {
  2442. ct=ct-'0';
  2443. } else if (ct>='a' && ct<='f') {
  2444. ct=(ct-'a')+10;
  2445. } else if (ct>='A' && ct<='F') {
  2446. ct=(ct-'A')+10;
  2447. } else {
  2448. continue;
  2449. }
  2450. c<<=4;
  2451. c|=ct;
  2452. }
  2453. if (p_dst)
  2454. *p_dst=c;
  2455. } else if (p_src_len>=4 && p_src[1]=='g' && p_src[2]=='t' && p_src[3]==';') {
  2456. if (p_dst)
  2457. *p_dst='>';
  2458. eat=4;
  2459. } else if (p_src_len>=4 && p_src[1]=='l' && p_src[2]=='t' && p_src[3]==';') {
  2460. if (p_dst)
  2461. *p_dst='<';
  2462. eat=4;
  2463. } else if (p_src_len>=5 && p_src[1]=='a' && p_src[2]=='m' && p_src[3]=='p' && p_src[4]==';') {
  2464. if (p_dst)
  2465. *p_dst='&';
  2466. eat=5;
  2467. } 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]==';') {
  2468. if (p_dst)
  2469. *p_dst='"';
  2470. eat=6;
  2471. } 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]==';') {
  2472. if (p_dst)
  2473. *p_dst='\'';
  2474. eat=6;
  2475. } else {
  2476. if (p_dst)
  2477. *p_dst=*p_src;
  2478. eat=1;
  2479. }
  2480. if (p_dst)
  2481. p_dst++;
  2482. len++;
  2483. p_src+=eat;
  2484. p_src_len-=eat;
  2485. } else {
  2486. if (p_dst) {
  2487. *p_dst=*p_src;
  2488. p_dst++;
  2489. }
  2490. len++;
  2491. p_src++;
  2492. p_src_len--;
  2493. }
  2494. }
  2495. return len;
  2496. }
  2497. String String::xml_unescape() const {
  2498. String str;
  2499. int l = length();
  2500. int len = _xml_unescape(c_str(),l,NULL);
  2501. if (len==0)
  2502. return String();
  2503. str.resize(len+1);
  2504. _xml_unescape(c_str(),l,&str[0]);
  2505. str[len]=0;
  2506. return str;
  2507. }
  2508. String String::pad_decimals(int p_digits) const {
  2509. String s=*this;
  2510. int c = s.find(".");
  2511. if (c==-1) {
  2512. if (p_digits<=0) {
  2513. return s;
  2514. }
  2515. s+=".";
  2516. c=s.length()-1;
  2517. } else {
  2518. if (p_digits<=0) {
  2519. return s.substr(0,c);
  2520. }
  2521. }
  2522. if (s.length()-(c+1) > p_digits) {
  2523. s=s.substr(0,c+p_digits+1);
  2524. } else {
  2525. while(s.length()-(c+1) < p_digits) {
  2526. s+="0";
  2527. }
  2528. }
  2529. return s;
  2530. }
  2531. String String::pad_zeros(int p_digits) const {
  2532. String s=*this;
  2533. int end = s.find(".");
  2534. if (end==-1) {
  2535. end=s.length();
  2536. }
  2537. if (end==0)
  2538. return s;
  2539. int begin=0;
  2540. while (begin<end && (s[begin]<'0' || s[begin]>'9')) {
  2541. begin++;
  2542. }
  2543. if (begin>=end)
  2544. return s;
  2545. while(end-begin < p_digits) {
  2546. s=s.insert(begin,"0");
  2547. end++;
  2548. }
  2549. return s;
  2550. }
  2551. bool String::is_valid_integer() const {
  2552. int len = length();
  2553. if (len==0)
  2554. return false;
  2555. int from=0;
  2556. if (len!=1 && (operator[](0)=='+' || operator[](0)=='-'))
  2557. from++;
  2558. for(int i=from;i<len;i++) {
  2559. if (operator[](i)<'0' || operator[](i)>'9')
  2560. return false; // no start with number plz
  2561. }
  2562. return true;
  2563. }
  2564. bool String::is_valid_hex_number(bool p_with_prefix) const {
  2565. int from = 0;
  2566. int len = length();
  2567. if (len!=1 && (operator[](0)=='+' || operator[](0)=='-'))
  2568. from++;
  2569. if (p_with_prefix) {
  2570. if (len < 2)
  2571. return false;
  2572. if (operator[](from) != '0' || operator[](from+1) != 'x') {
  2573. return false;
  2574. };
  2575. from += 2;
  2576. };
  2577. for (int i=from; i<len; i++) {
  2578. CharType c = operator[](i);
  2579. if ((c >= '0' && c <= '9') || (c >= 'a' && c <= 'f') || (c >= 'A' && c <= 'F'))
  2580. continue;
  2581. return false;
  2582. };
  2583. return true;
  2584. };
  2585. bool String::is_valid_float() const {
  2586. int len = length();
  2587. if (len==0)
  2588. return false;
  2589. int from=0;
  2590. if (operator[](0)=='+' || operator[](0)=='-') {
  2591. from++;
  2592. }
  2593. //this was pulled out of my ass, i wonder if it's correct...
  2594. bool exponent_found=false;
  2595. bool period_found=false;
  2596. bool sign_found=false;
  2597. bool exponent_values_found=false;
  2598. bool numbers_found=false;
  2599. for(int i=from;i<len;i++) {
  2600. if (operator[](i)>='0' && operator[](i)<='9') {
  2601. if (exponent_found)
  2602. exponent_values_found=true;
  2603. else
  2604. numbers_found=true;
  2605. } else if (numbers_found && !exponent_found && operator[](i)=='e') {
  2606. exponent_found=true;
  2607. } else if (!period_found && !exponent_found && operator[](i)=='.') {
  2608. period_found=true;
  2609. } else if ((operator[](i)=='-' || operator[](i)=='+') && exponent_found && !exponent_values_found && !sign_found) {
  2610. sign_found=true;
  2611. } else
  2612. return false; // no start with number plz
  2613. }
  2614. return numbers_found;
  2615. }
  2616. String String::path_to_file(const String& p_path) const {
  2617. String src=this->replace("\\","/").get_base_dir();
  2618. String dst=p_path.replace("\\","/").get_base_dir();
  2619. String rel = src.path_to(dst);
  2620. if (rel==dst) // failed
  2621. return p_path;
  2622. else
  2623. return rel+p_path.get_file();
  2624. }
  2625. String String::path_to(const String& p_path) const {
  2626. String src=this->replace("\\","/");
  2627. String dst=p_path.replace("\\","/");
  2628. if (!src.ends_with("/"))
  2629. src+="/";
  2630. if (!dst.ends_with("/"))
  2631. dst+="/";
  2632. String base;
  2633. if (src.begins_with("res://") && dst.begins_with("res://")) {
  2634. base="res:/";
  2635. src=src.replace("res://","/");
  2636. dst=dst.replace("res://","/");
  2637. } else if (src.begins_with("user://") && dst.begins_with("user://")) {
  2638. base="user:/";
  2639. src=src.replace("user://","/");
  2640. dst=dst.replace("user://","/");
  2641. } else if (src.begins_with("/") && dst.begins_with("/")) {
  2642. //nothing
  2643. } else {
  2644. //dos style
  2645. String src_begin=src.get_slicec('/',0);
  2646. String dst_begin=dst.get_slicec('/',0);
  2647. if (src_begin!=dst_begin)
  2648. return p_path; //impossible to do this
  2649. base=src_begin;
  2650. src=src.substr(src_begin.length(),src.length());
  2651. dst=dst.substr(dst_begin.length(),dst.length());
  2652. }
  2653. //remove leading and trailing slash and split
  2654. Vector<String> src_dirs=src.substr(1,src.length()-2).split("/");
  2655. Vector<String> dst_dirs=dst.substr(1,dst.length()-2).split("/");
  2656. //find common parent
  2657. int common_parent=0;
  2658. while(true) {
  2659. if (src_dirs.size()==common_parent)
  2660. break;
  2661. if (dst_dirs.size()==common_parent)
  2662. break;
  2663. if (src_dirs[common_parent]!=dst_dirs[common_parent])
  2664. break;
  2665. common_parent++;
  2666. }
  2667. common_parent--;
  2668. String dir;
  2669. for(int i=src_dirs.size()-1;i>common_parent;i--) {
  2670. dir+="../";
  2671. }
  2672. for(int i=common_parent+1;i<dst_dirs.size();i++) {
  2673. dir+=dst_dirs[i]+"/";
  2674. }
  2675. if (dir.length()==0)
  2676. dir="./";
  2677. return dir;
  2678. }
  2679. bool String::is_valid_html_color() const {
  2680. return Color::html_is_valid(*this);
  2681. }
  2682. bool String::is_valid_ip_address() const {
  2683. if (find(":") >= 0) {
  2684. Vector<String> ip = split(":");
  2685. for (int i=0; i<ip.size(); i++) {
  2686. String n = ip[i];
  2687. if (n.empty())
  2688. continue;
  2689. if (n.is_valid_hex_number(false)) {
  2690. int nint = n.hex_to_int(false);
  2691. if (nint < 0 || nint > 0xffff)
  2692. return false;
  2693. continue;
  2694. };
  2695. if (!n.is_valid_ip_address())
  2696. return false;
  2697. };
  2698. } else {
  2699. Vector<String> ip = split(".");
  2700. if (ip.size()!=4)
  2701. return false;
  2702. for(int i=0;i<ip.size();i++) {
  2703. String n = ip[i];
  2704. if (!n.is_valid_integer())
  2705. return false;
  2706. int val = n.to_int();
  2707. if (val<0 || val>255)
  2708. return false;
  2709. }
  2710. };
  2711. return true;
  2712. }
  2713. bool String::is_resource_file() const {
  2714. return begins_with("res://") && find("::")==-1;
  2715. }
  2716. bool String::is_rel_path() const {
  2717. return !is_abs_path();
  2718. }
  2719. String String::get_base_dir() const {
  2720. int basepos = find("://");
  2721. String rs;
  2722. String base;
  2723. if (basepos!=-1) {
  2724. int end = basepos+3;
  2725. rs = substr(end,length());
  2726. base = substr(0,end);
  2727. } else {
  2728. if (begins_with("/")) {
  2729. rs=substr(1,length());
  2730. base="/";
  2731. } else {
  2732. rs=*this;
  2733. }
  2734. }
  2735. int sep = MAX( rs.find_last("/"), rs.find_last("\\") );
  2736. if (sep==-1)
  2737. return base;
  2738. return base+rs.substr(0,sep);
  2739. }
  2740. String String::get_file() const {
  2741. int sep = MAX( find_last("/"), find_last("\\") );
  2742. if (sep==-1)
  2743. return *this;
  2744. return substr(sep+1,length());
  2745. }
  2746. String String::extension() const {
  2747. int pos = find_last(".");
  2748. if (pos<0)
  2749. return *this;
  2750. return substr( pos+1, length() );
  2751. }
  2752. String String::plus_file(const String& p_file) const {
  2753. if (length()>0 && operator [](length()-1)=='/')
  2754. return *this+p_file;
  2755. else
  2756. return *this+"/"+p_file;
  2757. }
  2758. String String::percent_encode() const {
  2759. CharString cs = utf8();
  2760. String encoded;
  2761. for(int i=0;i<cs.length();i++) {
  2762. uint8_t c = cs[i];
  2763. if ( (c>='A' && c<='Z') || (c>='a' && c<='z') || (c>='0' && c<='9') || c=='-' || c=='_' || c=='~' || c=='.') {
  2764. char p[2]={(char)c,0};
  2765. encoded+=p;
  2766. } else {
  2767. char p[4]={'%',0,0,0};
  2768. static const char hex[16]={'0','1','2','3','4','5','6','7','8','9','a','b','c','d','e','f'};
  2769. p[1]=hex[c>>4];
  2770. p[2]=hex[c&0xF];
  2771. encoded+=p;
  2772. }
  2773. }
  2774. return encoded;
  2775. }
  2776. String String::percent_decode() const {
  2777. CharString pe;
  2778. CharString cs = utf8();
  2779. for(int i=0;i<cs.length();i++) {
  2780. uint8_t c = cs[i];
  2781. if (c=='%' && i<length()-2) {
  2782. uint8_t a = LOWERCASE(cs[i+1]);
  2783. uint8_t b = LOWERCASE(cs[i+2]);
  2784. c=0;
  2785. if (a>='0' && a<='9')
  2786. c=(a-'0')<<4;
  2787. else if (a>='a' && a<='f')
  2788. c=(a-'a'+10)<<4;
  2789. else
  2790. continue;
  2791. uint8_t d=0;
  2792. if (b>='0' && b<='9')
  2793. d=(b-'0');
  2794. else if (b>='a' && b<='f')
  2795. d=(b-'a'+10);
  2796. else
  2797. continue;
  2798. c+=d;
  2799. i+=2;
  2800. }
  2801. pe.push_back(c);
  2802. }
  2803. pe.push_back(0);
  2804. return String::utf8(pe.ptr());
  2805. }
  2806. String String::basename() const {
  2807. int pos = find_last(".");
  2808. if (pos<0)
  2809. return *this;
  2810. return substr( 0, pos );
  2811. }
  2812. String itos(int64_t p_val) {
  2813. return String::num_int64(p_val);
  2814. }
  2815. String rtos(double p_val) {
  2816. return String::num(p_val);
  2817. }
  2818. String rtoss(double p_val) {
  2819. return String::num_scientific(p_val);
  2820. }
  2821. // Right-pad with a character.
  2822. String String::rpad(int min_length, const String& character) const {
  2823. String s = *this;
  2824. int padding = min_length - s.length();
  2825. if (padding > 0) {
  2826. for (int i = 0; i < padding; i++) s = s + character;
  2827. }
  2828. return s;
  2829. }
  2830. // Left-pad with a character.
  2831. String String::lpad(int min_length, const String& character) const {
  2832. String s = *this;
  2833. int padding = min_length - s.length();
  2834. if (padding > 0) {
  2835. for (int i = 0; i < padding; i++) s = character + s;
  2836. }
  2837. return s;
  2838. }
  2839. // sprintf is implemented in GDScript via:
  2840. // "fish %s pie" % "frog"
  2841. // "fish %s %d pie" % ["frog", 12]
  2842. // In case of an error, the string returned is the error description and "error" is true.
  2843. String String::sprintf(const Array& values, bool* error) const {
  2844. String formatted;
  2845. CharType* self = (CharType*)c_str();
  2846. bool in_format = false;
  2847. int value_index = 0;
  2848. int min_chars;
  2849. int min_decimals;
  2850. bool in_decimals;
  2851. bool pad_with_zeroes;
  2852. bool left_justified;
  2853. bool show_sign;
  2854. *error = true;
  2855. for (; *self; self++) {
  2856. const CharType c = *self;
  2857. if (in_format) { // We have % - lets see what else we get.
  2858. switch (c) {
  2859. case '%': { // Replace %% with %
  2860. formatted += chr(c);
  2861. in_format = false;
  2862. break;
  2863. }
  2864. case 'd': // Integer (signed)
  2865. case 'o': // Octal
  2866. case 'x': // Hexadecimal (lowercase)
  2867. case 'X': { // Hexadecimal (uppercase)
  2868. if (value_index >= values.size()) {
  2869. return "not enough arguments for format string";
  2870. }
  2871. if (!values[value_index].is_num()) {
  2872. return "a number is required";
  2873. }
  2874. int64_t value = values[value_index];
  2875. int base;
  2876. bool capitalize = false;
  2877. switch (c) {
  2878. case 'd': base = 10; break;
  2879. case 'o': base = 8; break;
  2880. case 'x': base = 16; break;
  2881. case 'X': base = 16; capitalize = true; break;
  2882. }
  2883. // Get basic number.
  2884. String str = String::num_int64(value, base, capitalize);
  2885. // Sign.
  2886. if (show_sign && value >= 0) {
  2887. str = str.insert(0, "+");
  2888. }
  2889. // Padding.
  2890. String pad_char = pad_with_zeroes ? String("0") : String(" ");
  2891. if (left_justified) {
  2892. str = str.rpad(min_chars, pad_char);
  2893. } else {
  2894. str = str.lpad(min_chars, pad_char);
  2895. }
  2896. formatted += str;
  2897. ++value_index;
  2898. in_format = false;
  2899. break;
  2900. }
  2901. case 'f': { // Float
  2902. if (value_index >= values.size()) {
  2903. return "not enough arguments for format string";
  2904. }
  2905. if (!values[value_index].is_num()) {
  2906. return "a number is required";
  2907. }
  2908. double value = values[value_index];
  2909. String str = String::num(value, min_decimals);
  2910. // Pad decimals out.
  2911. str = str.pad_decimals(min_decimals);
  2912. // Show sign
  2913. if (show_sign && value >= 0) {
  2914. str = str.insert(0, "+");
  2915. }
  2916. // Padding
  2917. if (left_justified) {
  2918. str = str.rpad(min_chars);
  2919. } else {
  2920. str = str.lpad(min_chars);
  2921. }
  2922. formatted += str;
  2923. ++value_index;
  2924. in_format = false;
  2925. break;
  2926. }
  2927. case 's': { // String
  2928. if (value_index >= values.size()) {
  2929. return "not enough arguments for format string";
  2930. }
  2931. String str = values[value_index];
  2932. // Padding.
  2933. if (left_justified) {
  2934. str = str.rpad(min_chars);
  2935. } else {
  2936. str = str.lpad(min_chars);
  2937. }
  2938. formatted += str;
  2939. ++value_index;
  2940. in_format = false;
  2941. break;
  2942. }
  2943. case 'c': {
  2944. if (value_index >= values.size()) {
  2945. return "not enough arguments for format string";
  2946. }
  2947. // Convert to character.
  2948. String str;
  2949. if (values[value_index].is_num()) {
  2950. int value = values[value_index];
  2951. if (value < 0) {
  2952. return "unsigned byte integer is lower than maximum";
  2953. } else if (value > 255) {
  2954. return "unsigned byte integer is greater than maximum";
  2955. }
  2956. str = chr(values[value_index]);
  2957. } else if (values[value_index].get_type() == Variant::STRING) {
  2958. str = values[value_index];
  2959. if (str.length() != 1) {
  2960. return "%c requires number or single-character string";
  2961. }
  2962. } else {
  2963. return "%c requires number or single-character string";
  2964. }
  2965. // Padding.
  2966. if (left_justified) {
  2967. str = str.rpad(min_chars);
  2968. } else {
  2969. str = str.lpad(min_chars);
  2970. }
  2971. formatted += str;
  2972. ++value_index;
  2973. in_format = false;
  2974. break;
  2975. }
  2976. case '-': { // Left justify
  2977. left_justified = true;
  2978. break;
  2979. }
  2980. case '+': { // Show + if positive.
  2981. show_sign = true;
  2982. break;
  2983. }
  2984. case '0': case '1': case '2': case '3': case '4':
  2985. case '5': case '6': case '7': case '8': case '9': {
  2986. int n = c - '0';
  2987. if (in_decimals) {
  2988. min_decimals *= 10;
  2989. min_decimals += n;
  2990. } else {
  2991. if (c == '0' && min_chars == 0) {
  2992. pad_with_zeroes = true;
  2993. } else {
  2994. min_chars *= 10;
  2995. min_chars += n;
  2996. }
  2997. }
  2998. break;
  2999. }
  3000. case '.': { // Float separtor.
  3001. if (in_decimals) {
  3002. return "too many decimal points in format";
  3003. }
  3004. in_decimals = true;
  3005. min_decimals = 0; // We want to add the value manually.
  3006. break;
  3007. }
  3008. case '*': { // Dyanmic width, based on value.
  3009. if (value_index >= values.size()) {
  3010. return "not enough arguments for format string";
  3011. }
  3012. if (!values[value_index].is_num()) {
  3013. return "* wants number";
  3014. }
  3015. int size = values[value_index];
  3016. if (in_decimals) {
  3017. min_decimals = size;
  3018. } else {
  3019. min_chars = size;
  3020. }
  3021. ++value_index;
  3022. break;
  3023. }
  3024. default: {
  3025. return "unsupported format character";
  3026. }
  3027. }
  3028. } else { // Not in format string.
  3029. switch (c) {
  3030. case '%':
  3031. in_format = true;
  3032. // Back to defaults:
  3033. min_chars = 0;
  3034. min_decimals = 6;
  3035. pad_with_zeroes = false;
  3036. left_justified = false;
  3037. show_sign = false;
  3038. in_decimals = false;
  3039. break;
  3040. default:
  3041. formatted += chr(c);
  3042. }
  3043. }
  3044. }
  3045. if (in_format) {
  3046. return "incomplete format";
  3047. }
  3048. if (value_index != values.size()) {
  3049. return "not all arguments converted during string formatting";
  3050. }
  3051. *error = false;
  3052. return formatted;
  3053. }
  3054. #include "translation.h"
  3055. #ifdef TOOLS_ENABLED
  3056. String TTR(const String& p_text) {
  3057. if (TranslationServer::get_singleton()) {
  3058. return TranslationServer::get_singleton()->tool_translate(p_text);
  3059. }
  3060. return p_text;
  3061. }
  3062. #endif
  3063. String RTR(const String& p_text) {
  3064. if (TranslationServer::get_singleton()) {
  3065. String rtr = TranslationServer::get_singleton()->tool_translate(p_text);
  3066. if (rtr==String() || rtr==p_text) {
  3067. return TranslationServer::get_singleton()->translate(p_text);
  3068. } else {
  3069. return rtr;
  3070. }
  3071. }
  3072. return p_text;
  3073. }