ustring.cpp 78 KB

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