ustring.cpp 81 KB

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