ustring.cpp 81 KB

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