*/}}

la_util.c 80 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673
  1. /*
  2. * LaGUI: A graphical application framework.
  3. * Copyright (C) 2022-2023 Wu Yiming
  4. *
  5. * This program is free software: you can redistribute it and/or modify
  6. * it under the terms of the GNU General Public License as published by
  7. * the Free Software Foundation, either version 3 of the License, or
  8. * (at your option) any later version.
  9. *
  10. * This program is distributed in the hope that it will be useful,
  11. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  12. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  13. * GNU General Public License for more details.
  14. *
  15. * You should have received a copy of the GNU General Public License
  16. * along with this program. If not, see <http://www.gnu.org/licenses/>.
  17. */
  18. #define _CRT_SEQURE_NO_WARNINGS
  19. #include "la_util.h"
  20. #include "la_interface.h"
  21. #include <stdio.h>
  22. #include <stdlib.h>
  23. laSafeStringCollection SSC;
  24. extern LA MAIN;
  25. #define BYTE unsigned char
  26. uint32_t laToUnicode(const unsigned char* ch, int* advance){
  27. if((*ch)<0x80) { *advance=1; return *ch; }
  28. uint32_t u=0;
  29. if(((*ch)>>5)==0x06){ *advance=2; u|=((*(ch+1))&0x3f)|((*(ch)&0x1f)<<6); return u; }
  30. if(((*ch)>>4)==0x0e){ *advance=3; u|=((*(ch+2))&0x3f)|((*(ch+1)&0x3f)<<6)|((*(ch)&0x0f)<<12); return u; }
  31. if(((*ch)>>3)==0x1e){ *advance=4; u|=((*(ch+3))&0x3f)|((*(ch+2)&0x3f)<<6)|((*(ch+1)&0x3f)<<12)|((*(ch)&0x07)<<18); return u; }
  32. *advance=1; return '?';
  33. }
  34. int laToUTF8(const uint32_t ch, unsigned char* out, unsigned char** next){
  35. if(ch>=0x10000){ out[0]=0xf0|(ch>>18); out[1]=0x80|(0x3f&(ch>>12)); out[2]=0x80|(0x3f&(ch>>6)); out[3]=0x80|(0x3f&ch); (*next)+=4;}
  36. elif(ch>=0x800){ out[0]=0xe0|(ch>>12); out[1]=0x80|(0x3f&(ch>>6)); out[2]=0x80|(0x3f&ch); (*next)+=3;}
  37. elif(ch>=0x80){ out[0]=0xc0|(ch>>6); out[1]=0x80|(0x3f&ch); (*next)+=2;}
  38. else { if(!ch){return 0;} out[0]=ch&0x7f; (*next)++;} return 1;
  39. }
  40. int strToUnicode(uint32_t* target, unsigned char* const src){
  41. uint32_t UC,adv,i=0; unsigned char* source=src; while(target[i]=laToUnicode(source, &adv)) { source+=adv; i++; } target[i]=0; return i;
  42. }
  43. int strToUTF8Lim(unsigned char* target, uint32_t* const src, int count){
  44. uint32_t* source=src; unsigned char* out=target; int i=0; while(laToUTF8(*source, out, &out)){ source++; i++; if(i>=count) break; } *out=0; return out-target;
  45. }
  46. int strToUTF8(unsigned char* target, uint32_t* const src){
  47. strToUTF8Lim(target,src,INT_MAX);
  48. }
  49. int strlenU(uint32_t* str){ int i=0; while(str[i]!=0) i++; return i; }
  50. int strcpyU(uint32_t* target, uint32_t* const source ){ int i=0; while(source[i]!=0){ target[i]=source[i]; i++; } target[i]=0; }
  51. int strcatU(uint32_t* target, uint32_t* const source ){ int i=0,tl=strlenU(target); while(source[i]!=0){ target[i+tl]=source[i]; i++; } target[i+tl]=0; }
  52. struct tm *laGetFullTime(){
  53. time_t t = time(0);
  54. return localtime(&t);
  55. }
  56. void laRecordTime(laTimeRecorder *tr){
  57. #ifdef __linux__
  58. clock_gettime(CLOCK_REALTIME, &tr->ts);
  59. #endif
  60. #ifdef _WIN32
  61. QueryPerformanceCounter(&tr->tm);
  62. #endif
  63. }
  64. real laTimeElapsedSecondsf(laTimeRecorder *End, laTimeRecorder *Begin){
  65. #ifdef __linux__
  66. real sec=End->ts.tv_sec-Begin->ts.tv_sec; sec+=((End->ts.tv_nsec-Begin->ts.tv_nsec)/1e9);
  67. #endif
  68. #ifdef _WIN32
  69. LARGE_INTEGER perfCnt; QueryPerformanceFrequency(&perfCnt);
  70. real sec = ((real)(End->tm.QuadPart - Begin->tm.QuadPart))/ perfCnt.QuadPart;
  71. #endif
  72. return sec;
  73. }
  74. void laSetAuthorInfo(char *Name, char *CopyrightString){
  75. strSafeSet(&MAIN.Author.Name, Name);
  76. strSafeSet(&MAIN.Author.CopyrightString, CopyrightString);
  77. }
  78. void memCreateNUID(char* buf,laMemNodeHyper* Hyper){
  79. sprintf(buf, "%08X-%hd%02hd%02hd%02hd%02hd%02hd", Hyper, LA_HYPER_CREATED_TIME(Hyper));
  80. }
  81. void memHyperInfo(laPropPack* pp, char* buf){
  82. int level=0;void* head=0;
  83. laMemNodeHyper* hi; laMemNode* mn;
  84. int a=0, count=0, pc;
  85. laProp* p=pp->LastPs->p;
  86. laPropContainer* c=p->Container;
  87. if(c->OtherAlloc){
  88. count=lstCountElements(&c->LocalUsers);
  89. }else{
  90. head=memGetHead(pp->LastPs->UseInstance, &level);
  91. if(!level){
  92. sprintf(buf,"Not HyperData.\n");
  93. }elif(level==1){
  94. mn=head; count=lstCountElements(&mn->Users);
  95. }elif(level==2){
  96. hi=head; count=lstCountElements(&hi->Users);
  97. }
  98. }
  99. a=sprintf(buf,"HyperData:\n\tProperty:%s\n\tContainer:%s (%d users)\n",
  100. pp->LastPs->p->Identifier, pp->LastPs->p->Container->Identifier, count);
  101. if(level==2){
  102. sprintf(buf+a,"\tCreated:%hd-%02hd-%02hd %02hd:%02hd:%02hd\n",LA_HYPER_CREATED_TIME(hi));
  103. }
  104. }
  105. void memMakeHyperData(laMemNodeHyper* hi){
  106. struct tm *time;
  107. hi->Modified = 1;
  108. time = laGetFullTime();
  109. //hi->CreatedBy = &MAIN.Author;
  110. hi->TimeCreated.Year = time->tm_year + 1900;
  111. hi->TimeCreated.Month = time->tm_mon + 1;
  112. hi->TimeCreated.Day = time->tm_mday;
  113. hi->TimeCreated.Hour = time->tm_hour;
  114. hi->TimeCreated.Minute = time->tm_min;
  115. hi->TimeCreated.Second = time->tm_sec;
  116. //memcpy(&hi->TimeModified, &hi->TimeCreated, sizeof(laTimeInfo));
  117. memCreateNUID(hi->NUID.String,hi);
  118. }
  119. void memMarkClean(void* HyperUserMem){
  120. int Hyper=0;
  121. laMemNodeHyper* h = memGetHead(HyperUserMem, &Hyper);
  122. if(Hyper!=2) return;
  123. h->Modified=0;
  124. }
  125. void nutFreeMem(void **ptr){
  126. //free_total+=1;
  127. if (!*ptr) return;
  128. free(*ptr);
  129. *ptr = 0;
  130. }
  131. int nutFloatCompare(real l, real r){
  132. return (l > r - 0.00005 && l < r + 0.00005);
  133. }
  134. int nutSameAddress(void *l, void *r){
  135. return (l == r);
  136. }
  137. //===================================================================[barray]
  138. #ifdef _MSC_VER
  139. # include <intrin.h>
  140. # define __builtin_popcountll __popcnt64
  141. static inline int __builtin_ctzl(u64bit x)
  142. {
  143. #ifdef _WIN64
  144. return (int)_tzcnt_u64(x);
  145. #else
  146. return !!unsigned(x) ? __builtin_ctz((unsigned)x) : 32 + __builtin_ctz((unsigned)(x >> 32));
  147. #endif
  148. }
  149. #endif
  150. barray_t *barray_init(size_t num_bits)
  151. {
  152. size_t num_longs = BITS_TO_LONGS(num_bits);
  153. barray_t *barray = calloc(1,sizeof(u64bit) * num_longs + sizeof(barray_t));
  154. barray->num_bits = num_bits;
  155. barray->num_longs = num_longs;
  156. return barray;
  157. }
  158. void barray_free(barray_t *barray)
  159. {
  160. free(barray);
  161. }
  162. u64bit *barray_data(barray_t *barray)
  163. {
  164. return barray->data;
  165. }
  166. size_t barray_count_set(barray_t *barray)
  167. {
  168. size_t count = 0;
  169. for (int i = 0; i < barray->num_longs; i++)
  170. count += __builtin_popcountll(barray->data[i]);
  171. return count;
  172. }
  173. void barray_set(barray_t *barray, bit_t bit)
  174. {
  175. if (bit >= barray->num_bits)
  176. return;
  177. int index = bit / BITS_PER_LONG;
  178. int shift = bit % BITS_PER_LONG;
  179. barray->data[index] |= ((u64bit)1 << shift);
  180. }
  181. void barray_clear(barray_t *barray, bit_t bit)
  182. {
  183. if (bit >= barray->num_bits)
  184. return;
  185. int index = bit / BITS_PER_LONG;
  186. int shift = bit % BITS_PER_LONG;
  187. barray->data[index] &= ~((u64bit)1 << shift);
  188. }
  189. bool barray_is_set(barray_t *barray, bit_t bit)
  190. {
  191. if (bit >= barray->num_bits)
  192. return false;
  193. int index = bit / BITS_PER_LONG;
  194. int shift = bit % BITS_PER_LONG;
  195. return (barray->data[index] & ((u64bit)1 << shift)) != 0;
  196. }
  197. void barray_foreach_set(barray_t *barray, barray_callback_t callback, void *arg)
  198. {
  199. for (int i = 0; i < barray->num_longs; i++)
  200. {
  201. u64bit bits = barray->data[i];
  202. while (bits != 0)
  203. {
  204. callback(i * BITS_PER_LONG + __builtin_ctzl(bits), arg);
  205. bits ^= (bits & -bits);
  206. }
  207. }
  208. }
  209. //===================================================================[md5]
  210. #define A 0x67452301
  211. #define B 0xefcdab89
  212. #define C 0x98badcfe
  213. #define D 0x10325476
  214. static uint32_t S[] = {7, 12, 17, 22, 7, 12, 17, 22, 7, 12, 17, 22, 7, 12, 17, 22,
  215. 5, 9, 14, 20, 5, 9, 14, 20, 5, 9, 14, 20, 5, 9, 14, 20,
  216. 4, 11, 16, 23, 4, 11, 16, 23, 4, 11, 16, 23, 4, 11, 16, 23,
  217. 6, 10, 15, 21, 6, 10, 15, 21, 6, 10, 15, 21, 6, 10, 15, 21};
  218. static uint32_t K[] = {0xd76aa478, 0xe8c7b756, 0x242070db, 0xc1bdceee,
  219. 0xf57c0faf, 0x4787c62a, 0xa8304613, 0xfd469501,
  220. 0x698098d8, 0x8b44f7af, 0xffff5bb1, 0x895cd7be,
  221. 0x6b901122, 0xfd987193, 0xa679438e, 0x49b40821,
  222. 0xf61e2562, 0xc040b340, 0x265e5a51, 0xe9b6c7aa,
  223. 0xd62f105d, 0x02441453, 0xd8a1e681, 0xe7d3fbc8,
  224. 0x21e1cde6, 0xc33707d6, 0xf4d50d87, 0x455a14ed,
  225. 0xa9e3e905, 0xfcefa3f8, 0x676f02d9, 0x8d2a4c8a,
  226. 0xfffa3942, 0x8771f681, 0x6d9d6122, 0xfde5380c,
  227. 0xa4beea44, 0x4bdecfa9, 0xf6bb4b60, 0xbebfbc70,
  228. 0x289b7ec6, 0xeaa127fa, 0xd4ef3085, 0x04881d05,
  229. 0xd9d4d039, 0xe6db99e5, 0x1fa27cf8, 0xc4ac5665,
  230. 0xf4292244, 0x432aff97, 0xab9423a7, 0xfc93a039,
  231. 0x655b59c3, 0x8f0ccc92, 0xffeff47d, 0x85845dd1,
  232. 0x6fa87e4f, 0xfe2ce6e0, 0xa3014314, 0x4e0811a1,
  233. 0xf7537e82, 0xbd3af235, 0x2ad7d2bb, 0xeb86d391};
  234. static uint8_t PADDING[] = {0x80, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
  235. 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
  236. 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
  237. 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
  238. 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
  239. 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
  240. 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
  241. 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00};
  242. #define F(X, Y, Z) ((X & Y) | (~X & Z))
  243. #define G(X, Y, Z) ((X & Z) | (Y & ~Z))
  244. #define H(X, Y, Z) (X ^ Y ^ Z)
  245. #define I(X, Y, Z) (Y ^ (X | ~Z))
  246. uint32_t rotateLeft(uint32_t x, uint32_t n){
  247. return (x << n) | (x >> (32 - n));
  248. }
  249. void md5Init(MD5Context *ctx){
  250. ctx->size = (uint64_t)0;
  251. ctx->buffer[0] = (uint32_t)A;
  252. ctx->buffer[1] = (uint32_t)B;
  253. ctx->buffer[2] = (uint32_t)C;
  254. ctx->buffer[3] = (uint32_t)D;
  255. }
  256. void md5Update(MD5Context *ctx, uint8_t *input_buffer, size_t input_len){
  257. uint32_t input[16];
  258. unsigned int offset = ctx->size % 64;
  259. ctx->size += (uint64_t)input_len;
  260. // Copy each byte in input_buffer into the next space in our context input
  261. for(unsigned int i = 0; i < input_len; ++i){
  262. ctx->input[offset++] = (uint8_t)*(input_buffer + i);
  263. // If we've filled our context input, copy it into our local array input
  264. // then reset the offset to 0 and fill in a new buffer.
  265. // Every time we fill out a chunk, we run it through the algorithm
  266. // to enable some back and forth between cpu and i/o
  267. if(offset % 64 == 0){
  268. for(unsigned int j = 0; j < 16; ++j){
  269. // Convert to little-endian
  270. // The local variable `input` our 512-bit chunk separated into 32-bit words
  271. // we can use in calculations
  272. input[j] = (uint32_t)(ctx->input[(j * 4) + 3]) << 24 |
  273. (uint32_t)(ctx->input[(j * 4) + 2]) << 16 |
  274. (uint32_t)(ctx->input[(j * 4) + 1]) << 8 |
  275. (uint32_t)(ctx->input[(j * 4)]);
  276. }
  277. md5Step(ctx->buffer, input);
  278. offset = 0;
  279. }
  280. }
  281. }
  282. void md5Finalize(MD5Context *ctx){
  283. uint32_t input[16];
  284. unsigned int offset = ctx->size % 64;
  285. unsigned int padding_length = offset < 56 ? 56 - offset : (56 + 64) - offset;
  286. // Fill in the padding and undo the changes to size that resulted from the update
  287. md5Update(ctx, PADDING, padding_length);
  288. ctx->size -= (uint64_t)padding_length;
  289. // Do a final update (internal to this function)
  290. // Last two 32-bit words are the two halves of the size (converted from bytes to bits)
  291. for(unsigned int j = 0; j < 14; ++j){
  292. input[j] = (uint32_t)(ctx->input[(j * 4) + 3]) << 24 |
  293. (uint32_t)(ctx->input[(j * 4) + 2]) << 16 |
  294. (uint32_t)(ctx->input[(j * 4) + 1]) << 8 |
  295. (uint32_t)(ctx->input[(j * 4)]);
  296. }
  297. input[14] = (uint32_t)(ctx->size * 8);
  298. input[15] = (uint32_t)((ctx->size * 8) >> 32);
  299. md5Step(ctx->buffer, input);
  300. // Move the result into digest (convert from little-endian)
  301. for(unsigned int i = 0; i < 4; ++i){
  302. ctx->digest[(i * 4) + 0] = (uint8_t)((ctx->buffer[i] & 0x000000FF));
  303. ctx->digest[(i * 4) + 1] = (uint8_t)((ctx->buffer[i] & 0x0000FF00) >> 8);
  304. ctx->digest[(i * 4) + 2] = (uint8_t)((ctx->buffer[i] & 0x00FF0000) >> 16);
  305. ctx->digest[(i * 4) + 3] = (uint8_t)((ctx->buffer[i] & 0xFF000000) >> 24);
  306. }
  307. }
  308. void md5Step(uint32_t *buffer, uint32_t *input){
  309. uint32_t AA = buffer[0];
  310. uint32_t BB = buffer[1];
  311. uint32_t CC = buffer[2];
  312. uint32_t DD = buffer[3];
  313. uint32_t E;
  314. unsigned int j;
  315. for(unsigned int i = 0; i < 64; ++i){
  316. switch(i / 16){
  317. case 0:
  318. E = F(BB, CC, DD);
  319. j = i;
  320. break;
  321. case 1:
  322. E = G(BB, CC, DD);
  323. j = ((i * 5) + 1) % 16;
  324. break;
  325. case 2:
  326. E = H(BB, CC, DD);
  327. j = ((i * 3) + 5) % 16;
  328. break;
  329. default:
  330. E = I(BB, CC, DD);
  331. j = (i * 7) % 16;
  332. break;
  333. }
  334. uint32_t temp = DD;
  335. DD = CC;
  336. CC = BB;
  337. BB = BB + rotateLeft(AA + E + K[i] + input[j], S[i]);
  338. AA = temp;
  339. }
  340. buffer[0] += AA;
  341. buffer[1] += BB;
  342. buffer[2] += CC;
  343. buffer[3] += DD;
  344. }
  345. void md5String(char *input, uint8_t *result){
  346. MD5Context ctx;
  347. md5Init(&ctx);
  348. md5Update(&ctx, (uint8_t *)input, strlen(input));
  349. md5Finalize(&ctx);
  350. memcpy(result, ctx.digest, 16);
  351. }
  352. void md5File(FILE *file, uint8_t *result){
  353. char *input_buffer = malloc(1024);
  354. size_t input_size = 0;
  355. MD5Context ctx;
  356. md5Init(&ctx);
  357. while((input_size = fread(input_buffer, 1, 1024, file)) > 0){
  358. md5Update(&ctx, (uint8_t *)input_buffer, input_size);
  359. }
  360. md5Finalize(&ctx);
  361. free(input_buffer);
  362. memcpy(result, ctx.digest, 16);
  363. }
  364. void toHexString(char* text, char* hex){
  365. int len = strlen(text);
  366. for (int i = 0, j = 0; i < len; ++i, j += 2)
  367. sprintf(hex + j, "%02x", text[i] & 0xff);
  368. }
  369. #undef A
  370. #undef B
  371. #undef C
  372. #undef D
  373. //===================================================================[list]
  374. void* arrElement(void* head, int i, int size){
  375. return ((char*)head+size*i);
  376. }
  377. int arrEnsureLength(void** head, int next, int* max, size_t ElementSize){
  378. int UseMax=*max; int nocopy=(!UseMax);
  379. if(next>=UseMax){
  380. if(!UseMax){ UseMax=50; }
  381. int AllocMax=next>(UseMax*2)?(next+16):(UseMax*2);
  382. void* data = CreateNew_Size(ElementSize* AllocMax);
  383. if(((*head) || next)&&(!nocopy)){ memcpy(data, *head, ElementSize*UseMax); }
  384. if(*head) free(*head);
  385. *head=data;
  386. *max=AllocMax;
  387. return 1;
  388. }
  389. return 0;
  390. }
  391. int arrInitLength(void** head, int max, int* pmax, size_t ElementSize){
  392. if(*head){ free(head); }
  393. *head=CreateNew_Size(ElementSize*max);
  394. *pmax=max;
  395. }
  396. void arrFree(void** head, int* max){ free(*head); *head=0; *max=0; }
  397. void lstPushSingle(void **Head, laListSingle *Item){
  398. Item->pNext = *Head;
  399. *Head = Item;
  400. }
  401. void *lstPopSingle(void **Head, laListSingle *Item){
  402. *Head = ((laListSingle *)(*Head))->pNext;
  403. Item->pNext = 0;
  404. return *Head;
  405. }
  406. int lstCountElements(laListHandle* Handle){
  407. int count=0; if(!Handle) return 0;
  408. for(laListItem* i=Handle->pFirst;i;i=i->pNext){count++;}
  409. return count;
  410. }
  411. void lstAppendItem(laListHandle* Handle, void* Item){
  412. laListItem* li = Item;
  413. li->pNext = li->pPrev = 0;
  414. if (!Handle->pFirst) Handle->pFirst = Item;
  415. if (Handle->pLast) ((laListItem*)Handle->pLast)->pNext = li;
  416. li->pPrev = Handle->pLast;
  417. li->pNext = 0;
  418. Handle->pLast = li;
  419. };
  420. void lstPushItem(laListHandle* Handle, void* Item){
  421. laListItem* li = Item;
  422. li->pNext = li->pPrev = 0;
  423. if (!Handle->pLast) Handle->pLast = Item;
  424. li->pNext = Handle->pFirst;
  425. if (Handle->pFirst) ((laListItem*)Handle->pFirst)->pPrev = Item;
  426. Handle->pFirst = li;
  427. };
  428. void* lstPopItem(laListHandle* Handle){
  429. laListItem* popitem;
  430. laListItem* next;
  431. if (!Handle->pFirst) return 0;
  432. popitem = Handle->pFirst;
  433. next = ((laListItem*)Handle->pFirst)->pNext;
  434. if (!next){
  435. Handle->pFirst = 0;
  436. Handle->pLast = 0;
  437. }else{
  438. Handle->pFirst = next;
  439. if (next) next->pPrev = 0;
  440. };
  441. popitem->pNext=popitem->pPrev=0;
  442. return popitem;
  443. };
  444. int lstHaveItemInList(laListHandle *Handle){
  445. if (Handle->pFirst) return 1;
  446. return 0;
  447. };
  448. void lstAppendItem2(laListHandle *Handle, void *Item){
  449. laListItem2 *li = Item;
  450. li->pNext = li->pPrev = 0;
  451. if (!Handle->pFirst) Handle->pFirst = Item;
  452. if (Handle->pLast) ((laListItem2 *)Handle->pLast)->pNext = li;
  453. li->pPrev = Handle->pLast;
  454. li->pNext = 0;
  455. Handle->pLast = li;
  456. };
  457. void lstPushItem2(laListHandle *Handle, void *Item){
  458. laListItem2 *li = Item;
  459. li->pNext = li->pPrev = 0;
  460. if (!Handle->pLast) Handle->pLast = Item;
  461. li->pNext = Handle->pFirst;
  462. if (Handle->pFirst) ((laListItem2 *)Handle->pFirst)->pPrev = Item;
  463. Handle->pFirst = li;
  464. };
  465. void *lstPopItem2(laListHandle *Handle){
  466. void *popitem;
  467. laListItem2 *next;
  468. if (!Handle->pFirst) return 0;
  469. popitem = Handle->pFirst;
  470. next = ((laListItem2 *)Handle->pFirst)->pNext;
  471. if (!next){
  472. Handle->pFirst = 0;
  473. Handle->pLast = 0;
  474. }else{
  475. Handle->pFirst = next;
  476. if (next) next->pPrev = 0;
  477. };
  478. return popitem;
  479. };
  480. void lstAppendItem3(laListHandle *Handle, void *Item){
  481. laListItem3 *li = Item;
  482. li->pNext = li->pPrev = 0;
  483. if (!Handle->pFirst) Handle->pFirst = Item;
  484. if (Handle->pLast) ((laListItem3 *)Handle->pLast)->pNext = li;
  485. li->pPrev = Handle->pLast;
  486. li->pNext = 0;
  487. Handle->pLast = li;
  488. };
  489. void lstPushItem3(laListHandle *Handle, void *Item){
  490. laListItem3 *li = Item;
  491. li->pNext = li->pPrev = 0;
  492. if (!Handle->pLast) Handle->pLast = Item;
  493. li->pNext = Handle->pFirst;
  494. if (Handle->pFirst) ((laListItem3 *)Handle->pFirst)->pPrev = Item;
  495. Handle->pFirst = li;
  496. };
  497. void *lstPopItem3(laListHandle *Handle){
  498. void *popitem;
  499. laListItem3 *next;
  500. if (!Handle->pFirst) return 0;
  501. popitem = Handle->pFirst;
  502. next = ((laListItem3 *)Handle->pFirst)->pNext;
  503. if (!next){
  504. Handle->pFirst = 0;
  505. Handle->pLast = 0;
  506. }else{
  507. Handle->pFirst = next;
  508. if (next) next->pPrev = 0;
  509. };
  510. return popitem;
  511. };
  512. void *lstGetTop(laListHandle *Handle){
  513. return Handle->pFirst;
  514. };
  515. int lstRemoveItem(laListHandle* Handle, laListItem* li) {
  516. if (!li->pPrev && Handle->pFirst != li) return 0;
  517. if (!li->pPrev) Handle->pFirst = li->pNext;
  518. else
  519. ((laListItem*)li->pPrev)->pNext = li->pNext;
  520. if (!li->pNext) Handle->pLast = li->pPrev;
  521. else
  522. ((laListItem*)li->pNext)->pPrev = li->pPrev;
  523. li->pNext = li->pPrev = 0;
  524. }
  525. int lstRemoveItem2(laListHandle *Handle, laListItem2 *li){
  526. if (!li->pPrev) Handle->pFirst = li->pNext;
  527. else
  528. ((laListItem2 *)li->pPrev)->pNext = li->pNext;
  529. if (!li->pNext) Handle->pLast = li->pPrev;
  530. else
  531. ((laListItem2 *)li->pNext)->pPrev = li->pPrev;
  532. li->pNext = li->pPrev = 0;
  533. };
  534. int lstRemoveItem3(laListHandle *Handle, laListItem2 *li){
  535. if (!li->pPrev) Handle->pFirst = li->pNext;
  536. else
  537. ((laListItem3 *)li->pPrev)->pNext = li->pNext;
  538. if (!li->pNext) Handle->pLast = li->pPrev;
  539. else
  540. ((laListItem3 *)li->pNext)->pPrev = li->pPrev;
  541. li->pNext = li->pPrev = 0;
  542. };
  543. int lstRemoveSegment(laListHandle *Handle, laListItem *Begin, laListItem *End){
  544. if (!Begin->pPrev) Handle->pFirst = End->pNext;
  545. else
  546. ((laListItem *)Begin->pPrev)->pNext = End->pNext;
  547. if (!End->pNext) Handle->pLast = Begin->pPrev;
  548. else
  549. ((laListItem *)End->pNext)->pPrev = Begin->pPrev;
  550. End->pNext = Begin->pPrev = 0;
  551. };
  552. void lstInsertItemBefore(laListHandle *Handle, laListItem *toIns, laListItem *pivot){
  553. if (!pivot){
  554. lstPushItem(Handle, toIns);
  555. return;
  556. }
  557. if (pivot->pPrev){
  558. ((laListItem *)pivot->pPrev)->pNext = toIns;
  559. toIns->pPrev = pivot->pPrev;
  560. }else{
  561. Handle->pFirst = toIns;
  562. }
  563. toIns->pNext = pivot;
  564. pivot->pPrev = toIns;
  565. };
  566. void lstInsertItemAfter(laListHandle *Handle, laListItem *toIns, laListItem *pivot){
  567. if (!pivot){
  568. lstAppendItem(Handle, toIns);
  569. return;
  570. }
  571. if (pivot->pNext){
  572. ((laListItem *)pivot->pNext)->pPrev = toIns;
  573. toIns->pNext = pivot->pNext;
  574. }else{
  575. Handle->pLast = toIns;
  576. }
  577. toIns->pPrev = pivot;
  578. pivot->pNext = toIns;
  579. }
  580. void lstInsertSegmentBefore(laListHandle *Handle, laListItem *Begin, laListItem *End, laListItem *pivot){
  581. if (pivot->pPrev){
  582. ((laListItem *)pivot->pPrev)->pNext = Begin;
  583. Begin->pPrev = pivot->pPrev;
  584. }else{
  585. Handle->pFirst = Begin;
  586. }
  587. End->pNext = pivot;
  588. pivot->pPrev = End;
  589. };
  590. void lstInsertSegmentAfter(laListHandle *Handle, laListItem *Begin, laListItem *End, laListItem *pivot){
  591. if (pivot->pNext){
  592. ((laListItem *)pivot->pNext)->pPrev = End;
  593. End->pNext = pivot->pNext;
  594. }else{
  595. Handle->pLast = End;
  596. }
  597. Begin->pPrev = pivot;
  598. pivot->pNext = Begin;
  599. }
  600. void *lstAppendPointerOnly(laListHandle *h, void *p){
  601. laListItemPointer *lip;
  602. if (!h) return 0;
  603. lip = CreateNew(laListItemPointer);
  604. lip->p = p;
  605. lstAppendItem(h, lip);
  606. return lip;
  607. }
  608. void *lstAppendPointerSizedOnly(laListHandle *h, void *p, int size){
  609. laListItemPointer *lip;
  610. if (!h) return 0;
  611. lip = calloc(1, size);
  612. lip->p = p;
  613. lstAppendItem(h, lip);
  614. return lip;
  615. }
  616. void *lstPushPointerOnly(laListHandle *h, void *p){
  617. laListItemPointer *lip = 0;
  618. if (!h) return 0;
  619. lip = CreateNew(laListItemPointer);
  620. lip->p = p;
  621. lstPushItem(h, lip);
  622. return lip;
  623. }
  624. void *lstPushPointerSizedOnly(laListHandle *h, void *p, int size){
  625. laListItemPointer *lip = 0;
  626. if (!h) return 0;
  627. lip = calloc(1, size);
  628. lip->p = p;
  629. lstPushItem(h, lip);
  630. return lip;
  631. }
  632. void lstReverse(laListHandle* h){
  633. laListHandle l={0}; void* i; while(i=lstPopItem(h)){ lstPushItem(&l,i); }
  634. memcpy(h,&l,sizeof(laListHandle));
  635. }
  636. int lstHasPointer(laListHandle* h, void *p){
  637. laListItemPointer *i; for (i = h->pFirst; i; i = i->pNext){
  638. if (i->p == p){return 1;}
  639. } return 0;
  640. }
  641. void *lstAppendPointer(laListHandle *h, void *p){
  642. laListItemPointer *lip;
  643. if (!h) return 0;
  644. lip = memAcquireSimple(sizeof(laListItemPointer));
  645. lip->p = p;
  646. lstAppendItem(h, lip);
  647. return lip;
  648. }
  649. void *lstAppendPointerSized(laListHandle *h, void *p, int size){
  650. laListItemPointer *lip;
  651. if (!h) return 0;
  652. lip = memAcquireSimple(size);
  653. lip->p = p;
  654. lstAppendItem(h, lip);
  655. return lip;
  656. }
  657. void *lstPushPointer(laListHandle *h, void *p){
  658. laListItemPointer *lip = 0;
  659. if (!h) return 0;
  660. lip = memAcquireSimple(sizeof(laListItemPointer));
  661. lip->p = p;
  662. lstPushItem(h, lip);
  663. return lip;
  664. }
  665. void *lstPushPointerSized(laListHandle *h, void *p, int size){
  666. laListItemPointer *lip = 0;
  667. if (!h) return 0;
  668. lip = memAcquireSimple(size);
  669. lip->p = p;
  670. lstPushItem(h, lip);
  671. return lip;
  672. }
  673. void *lstAppendPointerStatic(laListHandle *h, laStaticMemoryPool *smp, void *p){
  674. laListItemPointer *lip;
  675. if (!h) return 0;
  676. lip = memStaticAcquire(smp, sizeof(laListItemPointer));
  677. lip->p = p;
  678. lstAppendItem(h, lip);
  679. return lip;
  680. }
  681. void *lstAppendPointerStaticSized(laListHandle *h, laStaticMemoryPool *smp, void *p, int size){
  682. laListItemPointer *lip;
  683. if (!h) return 0;
  684. lip = memStaticAcquire(smp, size);
  685. lip->p = p;
  686. lstAppendItem(h, lip);
  687. return lip;
  688. }
  689. void *lstPushPointerStatic(laListHandle *h, laStaticMemoryPool *smp, void *p){
  690. laListItemPointer *lip = 0;
  691. if (!h) return 0;
  692. lip = memStaticAcquire(smp, sizeof(laListItemPointer));
  693. lip->p = p;
  694. lstPushItem(h, lip);
  695. return lip;
  696. }
  697. void *lstPushPointerStaticSized(laListHandle *h, laStaticMemoryPool *smp, void *p, int size){
  698. laListItemPointer *lip = 0;
  699. if (!h) return 0;
  700. lip = memStaticAcquire(smp, size);
  701. lip->p = p;
  702. lstPushItem(h, lip);
  703. return lip;
  704. }
  705. void *lstPopPointerOnly(laListHandle *h){
  706. laListItemPointer *lip;
  707. void *rev = 0;
  708. if (!h) return 0;
  709. lip = lstPopItem(h);
  710. rev = lip ? lip->p : 0;
  711. FreeMem(lip);
  712. return rev;
  713. }
  714. void lstRemovePointerItemOnly(laListHandle *h, laListItemPointer *lip){
  715. lstRemoveItem(h, lip);
  716. FreeMem(lip);
  717. }
  718. void lstRemovePointerOnly(laListHandle *h, void *p){
  719. laListItemPointer *i;
  720. for (i = h->pFirst; i; i = i->pNext){
  721. if (i->p == p){
  722. lstRemovePointerItem(h, i);
  723. break;
  724. }
  725. }
  726. }
  727. void lstClearPointerOnly(laListHandle *h){
  728. laListItemPointer *i;
  729. while (h && h->pFirst){
  730. lstPopPointer(h);
  731. }
  732. }
  733. void lstGeneratePointerListOnly(laListHandle *from1, laListHandle *from2, laListHandle *to){
  734. laListItemPointer *lip = from2 ? from2->pLast : 0;
  735. while (lip){
  736. lstPushPointer(to, lip->p);
  737. lip = lip->pPrev;
  738. }
  739. lip = from1 ? from1->pLast : 0;
  740. while (lip){
  741. lstPushPointer(to, lip->p);
  742. lip = lip->pPrev;
  743. }
  744. }
  745. void *lstPopPointer(laListHandle *h){
  746. laListItemPointer *lip;
  747. void *rev = 0;
  748. if (!h) return 0;
  749. lip = lstPopItem(h);
  750. rev = lip ? lip->p : 0;
  751. memFree(lip);
  752. return rev;
  753. }
  754. void lstRemovePointerItem(laListHandle *h, laListItemPointer *lip){
  755. lstRemoveItem(h, lip);
  756. memFree(lip);
  757. }
  758. void lstRemovePointer(laListHandle *h, void *p){
  759. laListItemPointer *i;
  760. for (i = h->pFirst; i; i = i->pNext){
  761. if (i->p == p){ lstRemovePointerItem(h, i); break; }
  762. }
  763. }
  764. void lstRemovePointerLeave(laListHandle *h, void *p){
  765. laListItemPointer *i;
  766. for (i = h->pFirst; i; i = i->pNext){
  767. if (i->p == p){ lstRemoveItem(h, i); memLeave(i); break; }
  768. }
  769. }
  770. void lstClearPointer(laListHandle *h){
  771. laListItemPointer *i;
  772. while (h && h->pFirst){
  773. lstPopPointer(h);
  774. }
  775. }
  776. void lstGeneratePointerList(laListHandle *from1, laListHandle *from2, laListHandle *to){
  777. laListItemPointer *lip = from2 ? from2->pLast : 0;
  778. while (lip){
  779. lstPushPointer(to, lip->p);
  780. lip = lip->pPrev;
  781. }
  782. lip = from1 ? from1->pLast : 0;
  783. while (lip){
  784. lstPushPointer(to, lip->p);
  785. lip = lip->pPrev;
  786. }
  787. }
  788. void *lstAppendPointerStaticPool(laStaticMemoryPool *mph, laListHandle *h, void *p){
  789. laListItemPointer *lip;
  790. if (!h) return 0;
  791. lip = memStaticAcquire(mph, sizeof(laListItemPointer));
  792. lip->p = p;
  793. lstAppendItem(h, lip);
  794. return lip;
  795. }
  796. void *lstPopPointerLeave(laListHandle *h){
  797. laListItemPointer *lip;
  798. void *rev = 0;
  799. if (!h) return 0;
  800. lip = lstPopItem(h); memLeave(lip);
  801. rev = lip ? lip->p : 0;
  802. return rev;
  803. }
  804. void lstRemovePointerItemNoFree(laListHandle *h, laListItemPointer *lip){
  805. lstRemoveItem(h, lip);
  806. }
  807. void lstCopyHandle(laListHandle *target, laListHandle *src){
  808. target->pFirst = src->pFirst;
  809. target->pLast = src->pLast;
  810. };
  811. void lstClearHandle(laListHandle *h){
  812. h->pFirst = 0;
  813. h->pLast = 0;
  814. }
  815. void lstClearPrevNext(laListItem *li){
  816. li->pNext = 0;
  817. li->pPrev = 0;
  818. }
  819. void lstMoveUp(laListHandle *h, laListItem *li){
  820. void *pprev = li->pPrev ? ((laListItem *)li->pPrev)->pPrev : 0;
  821. if (!h || !li) return;
  822. if (li == h->pFirst) return;
  823. else{
  824. if (li == h->pLast) h->pLast = li->pPrev;
  825. ((laListItem *)li->pPrev)->pNext = li->pNext;
  826. ((laListItem *)li->pPrev)->pPrev = li;
  827. if (li->pNext) ((laListItem *)li->pNext)->pPrev = li->pPrev;
  828. li->pNext = li->pPrev;
  829. li->pPrev = pprev;
  830. if (pprev) ((laListItem *)pprev)->pNext = li;
  831. }
  832. if (!li->pPrev) h->pFirst = li;
  833. }
  834. void lstMoveDown(laListHandle *h, laListItem *li){
  835. void *ppnext = li->pNext ? ((laListItem *)li->pNext)->pNext : 0;
  836. if (!h || !li) return;
  837. if (li == h->pLast) return;
  838. else{
  839. if (li == h->pFirst) h->pFirst = li->pNext;
  840. ((laListItem *)li->pNext)->pPrev = li->pPrev;
  841. ((laListItem *)li->pNext)->pNext = li;
  842. if (li->pPrev) ((laListItem *)li->pPrev)->pNext = li->pNext;
  843. li->pPrev = li->pNext;
  844. li->pNext = ppnext;
  845. if (ppnext) ((laListItem *)ppnext)->pPrev = li;
  846. }
  847. if (!li->pNext) h->pLast = li;
  848. }
  849. void lstForAllItemsDo(laListDoFunc func, laListHandle *hList){
  850. laListItem *it = hList->pFirst;
  851. for (; it; it = it->pNext){
  852. func(it);
  853. }
  854. };
  855. void lstForAllItemsDoLNRR(laListNonRecursiveDoFunc func, laListHandle *hList){
  856. laListItem *it = hList->pFirst;
  857. for (; it; it = it->pNext){
  858. func(0, it, 0);
  859. }
  860. };
  861. void lstForAllItemsDo_DirectFree(laListDoFunc func, laListHandle *hList){
  862. laListItem *it;
  863. while (it = lstPopItem(hList)){
  864. if (func) func(it);
  865. FreeMem(it);
  866. }
  867. };
  868. void lstForAllItemsDo_arg_ptr(laListDoFuncArgp func, laListHandle *hList, void *arg){
  869. laListItem *it = hList->pFirst;
  870. for (; it; it = it->pNext){
  871. func(it, arg);
  872. };
  873. };
  874. void lstForAllItemsDo_NonRecursive_Root(laListHandle *FirstHandle, laListNonRecursiveDoFunc func, int bFreeItem, void *custom_data, laListCustomDataRemover remover){
  875. laListItem *li = 0, *NextLi;
  876. laListNonRecursiveRoot root = {0};
  877. laListNonRecursiveItem *nrItem = CreateNew(laListNonRecursiveItem);
  878. nrItem->bFreeList = bFreeItem;
  879. nrItem->func = func;
  880. nrItem->CustomData = custom_data;
  881. nrItem->remover = remover;
  882. lstCopyHandle(&nrItem->handle, FirstHandle);
  883. lstAppendItem(&root.NSItems, nrItem);
  884. while (lstHaveItemInList(&root.NSItems)){
  885. nrItem = lstPopItem(&root.NSItems);
  886. for (li = nrItem->handle.pFirst; li /*!=nrItem->handle.pLast*/; li = NextLi){
  887. if (nrItem->func) nrItem->func(&root, li, custom_data);
  888. NextLi = li->pNext;
  889. if (nrItem->bFreeList){
  890. laListItem *fli = li;
  891. FreeMem(fli);
  892. }
  893. if (li == nrItem->handle.pLast) break;
  894. }
  895. if (nrItem->remover) nrItem->remover(nrItem->CustomData);
  896. FreeMem(nrItem);
  897. }
  898. };
  899. void lstAddNonRecursiveListHandle(laListNonRecursiveRoot *root, laListHandle *newHandle, laListNonRecursiveDoFunc nrFunc, int bFreeList, void *custom_data, laListCustomDataRemover remover){
  900. laListNonRecursiveItem *nrItem = CreateNew(laListNonRecursiveItem);
  901. nrItem->bFreeList = bFreeList;
  902. nrItem->func = nrFunc;
  903. nrItem->CustomData = custom_data;
  904. nrItem->remover = remover;
  905. lstCopyHandle(&nrItem->handle, newHandle);
  906. lstAppendItem(&root->NSItems, nrItem);
  907. };
  908. void lstCopy_NonRecursive_Root(laListHandle *FromHandle, laListHandle *ToHandle, int SizeEachNode, laListNonRecursiveCopyFunc func, void *custom_data, laListCustomDataRemover remover){
  909. laListItem *li = 0, *tli = 0;
  910. laListNonRecursiveRoot root = {0};
  911. laListNonRecursiveItem *nrItem = CreateNew(laListNonRecursiveItem);
  912. laListItem *NextLi;
  913. nrItem->CopyFunc = func;
  914. lstCopyHandle(&nrItem->handle, FromHandle);
  915. nrItem->ToHandle = ToHandle; //Pointer
  916. lstClearHandle(ToHandle);
  917. nrItem->CustomData = custom_data;
  918. nrItem->remover = remover;
  919. nrItem->SizeEachNode = SizeEachNode;
  920. lstAppendItem(&root.NSItems, nrItem);
  921. while (lstHaveItemInList(&root.NSItems)){
  922. nrItem = lstPopItem(&root.NSItems);
  923. if (nrItem->CopyFunc){
  924. for (li = nrItem->handle.pFirst; li; li = li->pNext){
  925. tli = CreateNew_Size(nrItem->SizeEachNode);
  926. nrItem->CopyFunc(&root, li, tli, nrItem->CustomData);
  927. lstClearPrevNext(tli);
  928. lstAppendItem(nrItem->ToHandle, tli);
  929. }
  930. if (nrItem->remover) nrItem->remover(nrItem->CustomData);
  931. }else if (nrItem->func){
  932. for (li = nrItem->handle.pFirst; li /*!=nrItem->handle.pLast*/; li = NextLi){
  933. if (nrItem->func) nrItem->func(&root, li, custom_data);
  934. NextLi = li->pNext;
  935. if (nrItem->bFreeList){
  936. laListItem *fli = li;
  937. FreeMem(fli);
  938. }
  939. if (li == nrItem->handle.pLast) break;
  940. }
  941. if (nrItem->remover) nrItem->remover(nrItem->CustomData);
  942. }
  943. FreeMem(nrItem);
  944. }
  945. };
  946. void lstAddNonRecursiveListCopier(laListNonRecursiveRoot *root, laListHandle *oldHandle, laListHandle *newHandle, int sizeEach, laListNonRecursiveCopyFunc nrCpyFunc, void *custom_data, laListCustomDataRemover remover){
  947. laListNonRecursiveItem *nrItem = CreateNew(laListNonRecursiveItem);
  948. nrItem->CopyFunc = nrCpyFunc;
  949. lstCopyHandle(&nrItem->handle, oldHandle);
  950. nrItem->ToHandle = newHandle;
  951. nrItem->CustomData = custom_data;
  952. nrItem->remover = remover;
  953. nrItem->SizeEachNode = sizeEach;
  954. lstAppendItem(&root->NSItems, nrItem);
  955. };
  956. void *lstFindItem(void *CmpData, laCompareFunc func, laListHandle *hList){
  957. laListItem *it;
  958. if (!CmpData || !hList) return 0;
  959. it = hList->pFirst;
  960. for (; it; it = it->pNext){
  961. if (func(it, CmpData)) return it;
  962. };
  963. return 0;
  964. };
  965. void lstCombineLists(laListHandle *dest, laListHandle *src){
  966. if ((!dest) || (!src)) return;
  967. if ((!dest->pFirst) && (!dest->pLast)){
  968. dest->pFirst = src->pFirst;
  969. dest->pLast = src->pLast;
  970. }else{
  971. if (src->pLast){
  972. ((laListItem *)src->pFirst)->pPrev = dest->pLast;
  973. ((laListItem *)dest->pLast)->pNext = src->pFirst;
  974. dest->pLast = src->pLast;
  975. }
  976. }
  977. src->pFirst = 0;
  978. src->pLast = 0;
  979. }
  980. void lstDestroyList(laListHandle *hlst){
  981. laListItem *li, *nextli;
  982. for (li = hlst->pFirst; li; li = nextli){
  983. nextli = li->pNext;
  984. memFree(li);
  985. }
  986. }
  987. void lstDestroyListA(laListHandle *hlst){
  988. laListItem *li, *nextli;
  989. for (li = hlst->pFirst; li; li = nextli){
  990. nextli = li->pNext;
  991. FreeMem(li);
  992. }
  993. }
  994. void lstDestroyList_User(laListHandle *hlst, laListDoFunc func){
  995. laListItem *it = hlst->pFirst;
  996. for (; it; it = it->pNext){
  997. func(it);
  998. FreeMem(it);
  999. }
  1000. };
  1001. void lstCopyList(laListHandle *hOldlst, laListHandle *hNewList, int SizeEachNode, laCopyListFunc func){
  1002. laListItem *li, *nextli, *newli;
  1003. for (li = hOldlst->pFirst; li; li = nextli){
  1004. newli = (laListItem *)CreateNew_Size(SizeEachNode);
  1005. func(li, newli);
  1006. lstAppendItem(hNewList, newli);
  1007. nextli = li->pNext;
  1008. }
  1009. }
  1010. void *lstReMatch(laListHandle *SearchHandle, laListHandle *CurrentHandle, void *ItemToFind){
  1011. laListItem *sl = 0, *rl = 0;
  1012. if (!SearchHandle || !CurrentHandle || !ItemToFind) return 0;
  1013. sl = SearchHandle->pFirst;
  1014. rl = CurrentHandle->pFirst;
  1015. while (sl && rl){
  1016. if (ItemToFind == sl){
  1017. return rl;
  1018. }else{
  1019. sl = sl->pNext;
  1020. rl = rl->pNext;
  1021. }
  1022. }
  1023. return 0;
  1024. }
  1025. //void* lstReMatchEx(laListHandle* SearchHandle, laListHandle* CurrentHandle, void* ItemToFind, MatcherFunc func){
  1026. // laListItem* sl = 0, *rl = 0;
  1027. //
  1028. // if (!SearchHandle || !CurrentHandle || !ItemToFind) return 0;
  1029. //
  1030. // sl = SearchHandle->pFirst; rl = CurrentHandle->pFirst;
  1031. //
  1032. // while (sl && rl){
  1033. // if (func(ItemToFind, sl)){
  1034. // return rl;
  1035. // }
  1036. // else{
  1037. // sl = sl->pNext;
  1038. // rl = rl->pNext;
  1039. // }
  1040. // }
  1041. // return 0;
  1042. //}
  1043. void lstAddElement(laListHandle *hlst, void *ext){
  1044. laElementListItem *eli = CreateNew(laElementListItem);
  1045. eli->Ext = ext;
  1046. lstAppendItem(hlst, eli);
  1047. }
  1048. void lstDestroyElementList(laListHandle *hlst){
  1049. laElementListItem *eli, *NextEli;
  1050. for (eli = hlst->pFirst; eli; eli = NextEli){
  1051. lstRemoveItem(hlst, eli);
  1052. NextEli = eli->Item.pNext;
  1053. FreeMem(eli);
  1054. }
  1055. }
  1056. uint16_t BKDRHash16bit(char* str){
  1057. unsigned int seed = 131, hash = 0;
  1058. while (*str) { hash = hash * seed + (*str++); }
  1059. return (hash & 0xFFFF);
  1060. }
  1061. void hsh65536Init(laHash65536** h){
  1062. if(!h) return; *h=calloc(1,sizeof(laHash65536));
  1063. }
  1064. void hshFree(laHash65536** h){
  1065. if(!h || !*h) return; free(*h); *h=0;
  1066. }
  1067. laListHandle* hsh65536DoHashLongPtr(laHash65536* hash, u64bit buckle) {
  1068. return &hash->Entries[(unsigned short)(buckle*13)];
  1069. }
  1070. laListHandle* hsh65536DoHashNUID(laHash65536* hash, char * NUID) {
  1071. u64bit Hash;
  1072. return &hash->Entries[BKDRHash16bit(NUID)];
  1073. }
  1074. unsigned char hsh256DoHashSTR(char *buckle){
  1075. int i, len = 0;
  1076. unsigned char rev = 0;
  1077. if (buckle) len = strlen(buckle);
  1078. for (i = 0; i < len; i++){
  1079. rev = rev * 31 + (unsigned char)buckle[i];
  1080. }
  1081. return (unsigned char)rev;
  1082. }
  1083. void hsh256InsertItemCSTR(laHash256 *hash, laListItem *li, char *buckle){
  1084. unsigned char a = hsh256DoHashSTR(buckle);
  1085. lstAppendItem(&hash->Entries[a], li);
  1086. };
  1087. void hsh256InsertItem(laHash256 *hash, laListItem *li, char buckle){
  1088. lstAppendItem(&hash->Entries[(unsigned char)buckle], li);
  1089. };
  1090. void hsh65536InsertItem(laHash65536 *hash, laListItem *li, long buckle){
  1091. lstAppendItem(&hash->Entries[(unsigned short)((buckle >> 10))], li);
  1092. //hsh256InsertItem(&hash->HashHandles[(char)((buckle >> 8) / 8)], li, (char)(buckle/8));
  1093. //printf("%d %d\n", (char)(buckle >> 5), (char)(buckle >> 6));
  1094. };
  1095. laListItem *hsh256FindItemSTR(laHash256 *hash, laCompareFunc func, char *buckle){
  1096. unsigned char hsh;
  1097. hsh = hsh256DoHashSTR(buckle);
  1098. //if(hash->Entries[hsh].pFirst == hash->Entries[hsh].pLast)
  1099. // return hash->Entries[hsh].pFirst;
  1100. laListItem* item=lstFindItem(buckle, func, &hash->Entries[hsh]);
  1101. return item;
  1102. }
  1103. //================================================================ [mem]
  1104. void* memGetHead(void* UserMem, int* HyperLevel){
  1105. laMemoryPoolPart **mpp = (laMemoryPoolPart**)(((char*)UserMem)-sizeof(void*));
  1106. if(!(*mpp)) return 0;
  1107. laMemoryPool* mp = (*mpp)->PoolRoot;
  1108. if(HyperLevel) *HyperLevel= mp->Hyperlevel;
  1109. if(mp->Hyperlevel==2) return ((char*)UserMem)-sizeof(laMemNodeHyper);
  1110. if(mp->Hyperlevel==1) return ((char*)UserMem)-sizeof(laMemNode);
  1111. if(mp->Hyperlevel==0) return ((char*)UserMem)-sizeof(laMemNode0);
  1112. return 0;
  1113. }
  1114. laListHandle* memGetUserList(void* UserMem){
  1115. int level; void* head=memGetHead(UserMem, &level);
  1116. if(level==2) return &((laMemNodeHyper*)head)->Users;
  1117. if(level==1) return &((laMemNode*)head)->Users;
  1118. return 0;
  1119. }
  1120. laMemoryPool *memInitPool(int NodeSize, int HyperLevel){
  1121. if (!NodeSize) return 0;
  1122. laMemoryPool *mph = calloc(1, sizeof(laMemoryPool));
  1123. mph->NodeSize = NodeSize;
  1124. mph->NextCount = 1;
  1125. mph->Hyperlevel = HyperLevel;
  1126. u8bit Buckle = NodeSize;
  1127. lstAppendItem(&MAIN.GlobalMemPool.Entries[Buckle], mph);
  1128. return mph;
  1129. }
  1130. laMemoryPoolPart *memNewPoolPart(laMemoryPool *mph){
  1131. if (!mph->NodeSize) return 0;
  1132. int MemNodeSize=(mph->Hyperlevel==0)?sizeof(laMemNode0):((mph->Hyperlevel==1)?sizeof(laMemNode):sizeof(laMemNodeHyper));
  1133. int PoolRefOffset=MemNodeSize-sizeof(void*);
  1134. int RealNodeSize = mph->NodeSize + MemNodeSize;
  1135. int NodeCount = mph->NextCount;
  1136. int TotalSize = sizeof(laMemoryPoolPart) + NodeCount * RealNodeSize;
  1137. laMemoryPoolPart *mp = calloc(1, TotalSize);
  1138. void *BeginMem = ((BYTE *)mp) + sizeof(laMemoryPoolPart);
  1139. mp->PoolRoot = mph;
  1140. mp->FreeMemoryNodes.pFirst = mp->FreeMemoryNodes.pLast = 0;
  1141. for (int i = 0; i < NodeCount; i++){
  1142. void* mpn = ((BYTE *)BeginMem) + RealNodeSize * i;
  1143. void** ref = ((BYTE *)mpn) + PoolRefOffset;
  1144. (*ref)=mp;
  1145. lstAppendItem(&mp->FreeMemoryNodes, mpn);
  1146. }
  1147. lstPushItem(&mph->Pools, mp);
  1148. return mp;
  1149. }
  1150. void *memAcquireH(laMemoryPool *Handle){
  1151. laMemoryPoolPart *mp = Handle->Pools.pFirst;
  1152. laMemNode *mpn;
  1153. if (!mp || !mp->FreeMemoryNodes.pFirst){
  1154. mp = memNewPoolPart(Handle);
  1155. }
  1156. if (!mp) return 0;
  1157. mpn = mp->FreeMemoryNodes.pFirst;
  1158. lstRemoveItem(&mp->FreeMemoryNodes, mpn);
  1159. mp->UsedCount++;
  1160. //lstAppendItem(&mp->MemoryNodes, mpn);
  1161. return mpn;
  1162. }
  1163. void *memAcquire_(int Size, int Hyper){
  1164. laMemoryPool *mp;
  1165. u8bit Buckle = Size;
  1166. laSpinLock(&MAIN.MemLock);
  1167. mp = MAIN.GlobalMemPool.Entries[Buckle].pFirst;
  1168. while (mp && (mp->NodeSize != Size || mp->Hyperlevel!=Hyper))
  1169. mp = mp->Item.pNext;
  1170. if (!mp) mp = memInitPool(Size, Hyper);
  1171. void* ret=memAcquireH(mp);
  1172. laSpinUnlock(&MAIN.MemLock);
  1173. return ret;
  1174. }
  1175. void *memAcquireSimple(int Size){
  1176. void *mpn = memAcquire_(Size, 0);
  1177. return ((char*)mpn)+sizeof(laMemNode0);
  1178. }
  1179. void *memAcquire(int Size){
  1180. laMemNode *mpn = memAcquire_(Size, 1);
  1181. void* mem = ((char*)mpn)+sizeof(laMemNode);
  1182. return mem;
  1183. }
  1184. void *memAcquireHyperNoAppend(int Size){
  1185. laMemNodeHyper *mpn = memAcquire_(Size, 2);
  1186. void* mem = ((char*)mpn)+sizeof(laMemNodeHyper);
  1187. memMakeHyperData(mpn);
  1188. return mem;
  1189. }
  1190. void *memAcquireHyper(int Size){
  1191. laMemNodeHyper *mpn = memAcquire_(Size, 2);
  1192. void* mem = ((char*)mpn)+sizeof(laMemNodeHyper);
  1193. memMakeHyperData(mpn);
  1194. laListHandle* l=hsh65536DoHashNUID(&MAIN.DBInst2,mpn->NUID.String);
  1195. lstAppendItem(l,mpn);
  1196. return mem;
  1197. }
  1198. void memFree(void *Data){
  1199. if (!Data) return;
  1200. int level; void* head = memGetHead(Data, &level);
  1201. laMemoryPoolPart *mp;
  1202. if(level==2) { mp = ((laMemNodeHyper*)head)->InPool; laDataBlockNoLongerExists(Data,&((laMemNodeHyper*)head)->Users);
  1203. laListHandle* l=hsh65536DoHashNUID(&MAIN.DBInst2,((laMemNodeHyper*)head)->NUID.String); lstRemoveItem(l,head);}
  1204. if(level==1) { mp = ((laMemNode*)head)->InPool; laDataBlockNoLongerExists(Data,&((laMemNode*)head)->Users); }
  1205. if(level==0) { mp = ((laMemNode0*)head)->InPool; }
  1206. laMemoryPool *mph = mp->PoolRoot;
  1207. laSpinLock(&MAIN.MemLock);
  1208. //lstRemoveItem(&mp->MemoryNodes, head);
  1209. mp->UsedCount--;
  1210. void* head_except_item = ((char*)head)+sizeof(laListItem);
  1211. //memset(head_except_item, 0, ((level==2)?sizeof(laMemNodeHyper):((level==1)?sizeof(laMemNode):sizeof(laMemNode0)))+mph->NodeSize-sizeof(laListItem));
  1212. lstAppendItem(&mp->FreeMemoryNodes, head);
  1213. memset(Data, 0, mph->NodeSize);
  1214. MAIN.ByteCount -= mph->NodeSize;
  1215. if (!mp->UsedCount){
  1216. lstRemoveItem(&mph->Pools, mp);
  1217. FreeMem(mp);
  1218. }
  1219. laSpinUnlock(&MAIN.MemLock);
  1220. //if (!mph->Pools.pFirst) {
  1221. // mph->CountPerPool = 0;
  1222. // mph->NodeSize = 0;
  1223. //}
  1224. }
  1225. void memDestroyPool(laMemoryPool *mph){
  1226. laMemoryPool *mp;
  1227. while ((mp = lstPopItem(&mph->Pools))){
  1228. FreeMem(mp);
  1229. }
  1230. FreeMem(mph);
  1231. }
  1232. // Leave memory in an temporary place and if when push difference these are still not acquired, free them.
  1233. void memLeave(void *Data){
  1234. laListHandle* l=hsh65536DoHashLongPtr(MAIN.DBInstMemLeft,Data); lstAppendPointer(l,Data);
  1235. }
  1236. void memTake(void *Data){
  1237. laListHandle* l=hsh65536DoHashLongPtr(MAIN.DBInstMemLeft,Data); lstRemovePointer(l,Data);
  1238. }
  1239. void memFreeRemainingLeftNodes(){
  1240. laListHandle* l; void* m;
  1241. for(int i=0;i<65536;i++){
  1242. l=&MAIN.DBInstMemLeft->Entries[i]; while(m=lstPopPointer(l)){ memFree(m);
  1243. #ifdef DEBUG
  1244. printf("left freed %x\n",m);
  1245. #endif
  1246. }
  1247. }
  1248. }
  1249. void memNoLonger(){
  1250. for(int i=0;i<256;i++){
  1251. laMemoryPool* mp; while(mp=lstPopItem(&MAIN.GlobalMemPool.Entries[i])){ memDestroyPool(mp); }
  1252. }
  1253. }
  1254. laStaticMemoryPoolNode *memNewStaticPool(laStaticMemoryPool *smp){
  1255. laStaticMemoryPoolNode *smpn = calloc(1, LA_MEMORY_POOL_128MB);
  1256. smpn->UsedByte = sizeof(laStaticMemoryPoolNode);
  1257. lstPushItem(&smp->Pools, smpn);
  1258. return smpn;
  1259. }
  1260. void *memStaticAcquire(laStaticMemoryPool *smp, int size){
  1261. laStaticMemoryPoolNode *smpn = smp->Pools.pFirst;
  1262. void *ret;
  1263. if (!smpn || (smpn->UsedByte + size) > LA_MEMORY_POOL_128MB) smpn = memNewStaticPool(smp);
  1264. ret = ((BYTE *)smpn) + smpn->UsedByte;
  1265. smpn->UsedByte += size;
  1266. return ret;
  1267. }
  1268. void *memStaticAcquireThread(laStaticMemoryPool *smp, int size){
  1269. laStaticMemoryPoolNode *smpn = smp->Pools.pFirst;
  1270. void *ret;
  1271. //laSpinLock(&smp->csMem);
  1272. if (!smpn || (smpn->UsedByte + size) > LA_MEMORY_POOL_128MB) smpn = memNewStaticPool(smp);
  1273. ret = ((BYTE *)smpn) + smpn->UsedByte;
  1274. smpn->UsedByte += size;
  1275. //laSpinUnlock(&smp->csMem);
  1276. return ret;
  1277. }
  1278. void *memStaticDestroy(laStaticMemoryPool *smp){
  1279. laStaticMemoryPoolNode *smpn;
  1280. void *ret;
  1281. while (smpn = lstPopItem(&smp->Pools)){
  1282. FreeMem(smpn);
  1283. }
  1284. smp->EachSize = 0;
  1285. return ret;
  1286. }
  1287. void la_ReferencedBlockDeleted(void* This, laItemUserLinker* iul){
  1288. void** user=iul->Pointer.p; if(*user==This){ (*user)=0; } laStopUsingDataBlock(iul->Additional, 0, This); // <<< should always remove.
  1289. }
  1290. void la_ReferrerDeleted(void* This, laItemUserLinker* iul){
  1291. void* instance=iul->Pointer.p; if(instance!=This){ laStopUsingDataBlock(instance, 0, This); }
  1292. }
  1293. void memAssignRef(void* This, void** ptr, void* instance){
  1294. laItemUserLinker* iul;
  1295. if((!This)||(!ptr)) return;
  1296. if(instance){
  1297. laItemUserLinker*iul=laUseDataBlock(instance, 0, 0, ptr, la_ReferencedBlockDeleted, 0); if(iul){iul->Additional=This;}
  1298. laUseDataBlock(This, 0, 0, instance, la_ReferrerDeleted, 0);
  1299. }else{
  1300. laStopUsingDataBlock((*ptr), 0, This);
  1301. laStopUsingDataBlock(This, 0, (*ptr));
  1302. }
  1303. (*ptr)=instance;
  1304. }
  1305. void memAssignRefSafe(laSubProp* sp, void* This, void** ptr, void* instance){
  1306. laPropContainer* pc=sp?la_EnsureSubTarget(sp,instance):0;
  1307. if(pc&&!pc->OtherAlloc) memAssignRef(This,ptr,instance);
  1308. else (*ptr)=instance;
  1309. }
  1310. //=======================================================================[str]
  1311. char *strGetNextString(char **pivot, char *NextMark){
  1312. int lenth = 0;
  1313. char *countP = *pivot;
  1314. char *result = 0;
  1315. int FloatArg = 0;
  1316. int i,advance;
  1317. if (**pivot == U'\0') return 0;
  1318. if (*NextMark == U'~') FloatArg = 1;
  1319. // container@identifier=window container#window contianer%
  1320. int UC=1;
  1321. while (!lenth){
  1322. for (countP; *countP != U'.' && *(*pivot) != U'\0' && UC && *countP && *countP != U'@' && *countP != U'=' && *countP != U'#' && *countP != U'$';){
  1323. if((*countP)=='\\'){
  1324. countP++; lenth++; }
  1325. UC = laToUnicode(countP, &advance);
  1326. lenth+=advance;
  1327. countP+=advance;
  1328. }
  1329. if (lenth || (*countP) == 0) break;
  1330. (*pivot)++; countP++;
  1331. }
  1332. *NextMark = (*pivot)[lenth];
  1333. if (!(*NextMark)) *NextMark = U'.';
  1334. if (lenth){
  1335. result = CreateNewBuffer(char, lenth + 1);
  1336. int pi=0; for (i = 0; i < lenth; i++){
  1337. if((*pivot)[i]=='\\'){ continue; }
  1338. result[pi] = (*pivot)[i]; pi++;
  1339. }
  1340. result[pi] = U'\0';
  1341. if ((*pivot)[lenth] == U'\0') *pivot = &((*pivot)[lenth]);
  1342. else
  1343. (*pivot) += lenth + 1;
  1344. return result;
  1345. }else{
  1346. return 0;
  1347. }
  1348. };
  1349. int strGetStringTerminateBy(char *content, char terminator, char *Out){
  1350. int Ofst = 0;
  1351. int Skip = 0;
  1352. int i = 0, advance;
  1353. if ((!content) || (*content == U'\0')) return 0;
  1354. int UC;
  1355. for (Ofst; content[Ofst] != terminator && content[Ofst] != U'\0'; ){
  1356. UC = laToUnicode(&content[Ofst], &advance);
  1357. for(int a=0;a<advance;a++){
  1358. Out[i] = content[Ofst];
  1359. Ofst++; i++;
  1360. }
  1361. }
  1362. Out[i] = 0;
  1363. return i;
  1364. };
  1365. char *strGetNewStringTerminateBy_PivotOver(char *content, char terminator, char **NewPivot, int IgnoreSpace){
  1366. int Ofst = 0;
  1367. int Skip = 0;
  1368. int i = 0;
  1369. char *NewString;
  1370. if (!content || *content == U'\0') return 0;
  1371. if (IgnoreSpace) for (i; content[i] == U' '; i++) ;
  1372. int UC,advance;
  1373. for (Ofst; content[Ofst] != terminator && content[Ofst] != U'\0';){
  1374. UC = laToUnicode(&content[Ofst], &advance);
  1375. Ofst+=advance;
  1376. }
  1377. NewString = CreateNewBuffer(char, Ofst + 1 - i);
  1378. memcpy(NewString, &content[i], sizeof(char) * (Ofst - i));
  1379. NewString[Ofst - i] = U'\0';
  1380. *NewPivot = content[Ofst]?&content[Ofst + 1]:&content[Ofst];
  1381. return NewString;
  1382. };
  1383. int strHeadOfStringMatch(char *Str, char *SubStr){
  1384. int len = strlen(SubStr);
  1385. int i = 0;
  1386. for (i; i < len; i++){
  1387. if (Str[i] != SubStr[i]) return 0;
  1388. }
  1389. return 1;
  1390. }
  1391. int strSkipSegmet(char **pivot, char *content){
  1392. if (!pivot || !(*pivot) || !(*(*pivot)) || !content) return 0;
  1393. if (strHeadOfStringMatch(*pivot, content)){
  1394. (*pivot) += strlen(content);
  1395. return 1;
  1396. }
  1397. return 0;
  1398. }
  1399. char *strGetLastSegment(char *Content, char Seperator){
  1400. char *p = Content;
  1401. char *pn = Content;
  1402. while (1){
  1403. while (*pn != Seperator){
  1404. if (!(*pn)) return p;
  1405. pn++;
  1406. }
  1407. pn++;
  1408. p = pn;
  1409. }
  1410. }
  1411. void strDiscardLastSegmentSeperateBy(char *Content, char Seperator){
  1412. char *p = Content;
  1413. char *pn = Content;
  1414. while (1){
  1415. while (*pn != Seperator){
  1416. if (!(*pn)){
  1417. *p = 0;
  1418. return;
  1419. }
  1420. pn++;
  1421. }
  1422. p = pn;
  1423. pn++;
  1424. }
  1425. }
  1426. void strDiscardSameBeginningSeperatedBy(char *s1, char *s2, char **Result1, char **Result2, char Seperator){
  1427. int i = 0;
  1428. int p = 0;
  1429. while (s1[i] == s2[i]){
  1430. i++;
  1431. if (s1[i] == Seperator) p = i;
  1432. if (!s1[i]){
  1433. p = i;
  1434. break;
  1435. }
  1436. if (!s2[i]){
  1437. p = i;
  1438. break;
  1439. }
  1440. }
  1441. *Result1 = &s1[p];
  1442. *Result2 = &s2[p];
  1443. }
  1444. int strCountSegmentSeperateBy(char *Content, char Seperator){
  1445. char *p = Content;
  1446. char *pn = Content;
  1447. int c = Content[0] ? (Content[0] == Seperator ? 0 : 1) : 0;
  1448. while (1){
  1449. while (*pn != Seperator){
  1450. if (!(*pn)){
  1451. if ((*p) == Seperator) c--;
  1452. return c;
  1453. }
  1454. p = pn;
  1455. pn++;
  1456. }
  1457. c++;
  1458. pn++;
  1459. }
  1460. return c;
  1461. }
  1462. void strMakeDifferentName(char *Target){
  1463. char *p = strGetLastSegment(Target, '.');
  1464. int Temp;
  1465. if (!sscanf(p, "%d", &Temp)){
  1466. int l = strlen(p);
  1467. if (p[l - 1] != U'.') strcat(p, ".");
  1468. strPrintIntAfter(Target, 0, 001);
  1469. }else{
  1470. sprintf(p, "%d", Temp + 1);
  1471. };
  1472. }
  1473. void strReplaceCharacter(char *Str, char Find, char Replace){
  1474. char *p = Str;
  1475. if (!p) return;
  1476. while (*p){
  1477. if (*p == Find) *p = Replace;
  1478. p++;
  1479. }
  1480. }
  1481. void strToUpper(char *Str){
  1482. char *p = Str; if (!p) return;
  1483. while (*p){
  1484. if (*p >= 'a' && *p <= 'z') *p += 'A' - 'a';
  1485. p++;
  1486. }
  1487. }
  1488. void strToLower(char *Str){
  1489. char *p = Str; if (!p) return;
  1490. while (*p){
  1491. if (*p >= 'A' && *p <= 'Z') *p -= 'A' - 'a';
  1492. p++;
  1493. }
  1494. }
  1495. int tolowerGuarded(int a) {
  1496. if (a >= 'A' && a <= 'Z') a -= 'A' - 'a';
  1497. return a;
  1498. }
  1499. laStringSplitor *strSplitPath(char *path,char terminator){
  1500. laStringPart *sp;
  1501. laStringSplitor *ss;
  1502. char *pivot = path;
  1503. char *temp_result;
  1504. char Type = terminator?terminator:'.';
  1505. char NextType = '.';
  1506. if (!path || !path[0]) return 0;
  1507. ss = memAcquireSimple(sizeof(laStringSplitor));
  1508. while (temp_result = strGetNextString(&pivot, &NextType)){
  1509. if (*temp_result != U'\0'){
  1510. sp = memAcquireSimple(sizeof(laStringPart));
  1511. sp->Content = temp_result;
  1512. lstAppendItem(&ss->parts, sp);
  1513. ss->NumberParts += 1;
  1514. if (NextType == U'$') sp->Type = U'$';
  1515. else
  1516. sp->Type = Type;
  1517. if (sp->Type == U'='){
  1518. if (sp->Content[0] >= U'0' && sp->Content[0] <= 9){
  1519. sscanf(sp->Content, "%d", &sp->IntValue);
  1520. }
  1521. }
  1522. if (NextType == U'$') NextType = U'.';
  1523. Type = NextType;
  1524. }
  1525. }
  1526. if (ss->NumberParts == 0){
  1527. strDestroyStringSplitor(&ss);
  1528. return 0;
  1529. }
  1530. return ss;
  1531. };
  1532. void DF_ClearStingParts(laStringPart *sp){
  1533. FreeMem(sp->Content);
  1534. };
  1535. int strDestroyStringSplitor(laStringSplitor **ss){
  1536. if (!(*ss)) return 0;
  1537. lstForAllItemsDo(DF_ClearStingParts, &(*ss)->parts);
  1538. lstDestroyList(&(*ss)->parts);
  1539. memFree(*ss);
  1540. *ss = 0;
  1541. return 1;
  1542. }
  1543. char * strSub(char *input, char *substring, char *replace){
  1544. int number_of_matches = 0;
  1545. size_t substring_size = strlen(substring), replace_size = strlen(replace), buffer_size;
  1546. char *buffer, *bp, *ip;
  1547. if (substring_size){
  1548. ip = strstr(input, substring);
  1549. while (ip != NULL){
  1550. number_of_matches++;
  1551. ip = strstr(ip+substring_size, substring);
  1552. }
  1553. }
  1554. else number_of_matches = strlen (input) + 1;
  1555. buffer_size = strlen(input) + number_of_matches*(replace_size - substring_size) + 1;
  1556. if ((buffer = ((char *) malloc(buffer_size))) == NULL){
  1557. return NULL;
  1558. }
  1559. bp = buffer;
  1560. ip = strstr(input, substring);
  1561. while ((ip != NULL) && (*input != '\0')){
  1562. if (ip == input){
  1563. memcpy (bp, replace, replace_size+1);
  1564. bp += replace_size;
  1565. if (substring_size)input += substring_size;
  1566. else*(bp++) = *(input++);
  1567. ip = strstr(input, substring);
  1568. }
  1569. else while (input != ip) *(bp++) = *(input++);
  1570. }
  1571. if (substring_size)strcpy (bp, input);
  1572. else memcpy (bp, replace, replace_size+1);
  1573. return buffer;
  1574. }
  1575. char buff[128]={0};
  1576. int strMakeInstructions(laStringSplitor **result, char *content){
  1577. laStringPart *sp;
  1578. laStringSplitor *ss = *result;
  1579. char *pivot = content;
  1580. unsigned char *temp_result;
  1581. if (!content || !content[0]) return 0;
  1582. if (!ss) ss = *result = memAcquireSimple(sizeof(laStringSplitor));
  1583. while (temp_result = strGetNewStringTerminateBy_PivotOver(pivot, '=', &pivot, 0)){
  1584. if (*temp_result != U'\0'){
  1585. sp = memAcquireSimple(sizeof(laStringPart));
  1586. sp->Content = temp_result;
  1587. lstAppendItem(&ss->parts, sp);
  1588. ss->NumberParts += 1;
  1589. }
  1590. temp_result = strGetNewStringTerminateBy_PivotOver(pivot, ';', &pivot, 0);
  1591. if (!temp_result) break;
  1592. if (*temp_result != U'\0'){
  1593. sp = memAcquireSimple(sizeof(laStringPart));
  1594. sp->Content = temp_result;
  1595. lstAppendItem(&ss->parts, sp);
  1596. ss->NumberParts += 1;
  1597. if (temp_result[0] >= U'0' && temp_result[0] <= U'9' || temp_result[0]>=128){
  1598. sscanf(temp_result, "%d", &sp->IntValue);
  1599. sscanf(temp_result, "%lf", &sp->FloatValue);
  1600. }
  1601. }
  1602. }
  1603. if (ss->NumberParts == 0){
  1604. strDestroyStringSplitor(&ss);
  1605. return 0;
  1606. }
  1607. return 1;
  1608. }
  1609. laStringPart *strGetArgument(laStringSplitor *ss, char *content){
  1610. laStringPart *sp;
  1611. if (!ss) return 0;
  1612. for (sp = ss->parts.pFirst; sp; sp = sp->Item.pNext ? ((laListItem *)sp->Item.pNext)->pNext : 0){
  1613. if (strSame(content, sp->Content)) return sp->Item.pNext;
  1614. }
  1615. return 0;
  1616. }
  1617. char *strGetArgumentString(laStringSplitor *ss, char *content){
  1618. laStringPart *sp;
  1619. if (!ss) return 0;
  1620. for (sp = ss->parts.pFirst; sp; sp = sp->Item.pNext ? ((laListItem *)sp->Item.pNext)->pNext : 0){
  1621. if (strSame(content, sp->Content)) return sp->Item.pNext ? ((laStringPart *)sp->Item.pNext)->Content : 0;
  1622. }
  1623. return 0;
  1624. }
  1625. int strArgumentMatch(laStringSplitor *ss, char *id, char *value){
  1626. laStringPart *sp;
  1627. if (!ss) return 0;
  1628. for (sp = ss->parts.pFirst; sp; sp = sp->Item.pNext ? ((laListItem *)sp->Item.pNext)->pNext : 0){
  1629. if (strSame(id, sp->Content)) return (strSame(((laStringPart *)sp->Item.pNext)->Content, value));
  1630. }
  1631. return 0;
  1632. }
  1633. int strGetIntSimple(char *content){
  1634. int a;
  1635. sscanf(content, "%d", &a);
  1636. return a;
  1637. }
  1638. real strGetFloatSimple(char *content){
  1639. real a;
  1640. sscanf(content, "%lf", &a);
  1641. return a;
  1642. }
  1643. void strConvInt_CString(int src, char *dest, int lenth){
  1644. sprintf(dest, "%d", src);
  1645. };
  1646. void strConvFloat_CString(real src, char *dest, int lenth){
  1647. sprintf(dest, "%lf", src);
  1648. };
  1649. void strCopyFull(char *dest, char *src){
  1650. if (src && dest) strcpy(dest, src);
  1651. }
  1652. void strCopySized(char *dest, int LenthLim, char *src){
  1653. if (src && dest) strcpy(dest, src);
  1654. }
  1655. void strPrintFloatAfter(char *dest, int LenthLim, int bits, real data){
  1656. char temp[64]={0};
  1657. sprintf(temp, "%.*lf", bits, data);
  1658. strcat(dest, temp);
  1659. }
  1660. void strPrintIntAfter(char *dest, int LenthLim, int data){
  1661. char temp[64]={0};
  1662. sprintf(&temp[0], "%d", data);
  1663. strcat(dest, temp);
  1664. }
  1665. void strEscapePath(char* OutCanBeSame, char* path){
  1666. char t[256]={0}; int ti=0;
  1667. for(int i=0;path[i];i++,ti++){
  1668. if(path[i]=='.'){ t[ti]='\\'; ti++; }
  1669. t[ti]=path[i];
  1670. }
  1671. strcpy(OutCanBeSame,t);
  1672. }
  1673. int strSame(char *src, char *dest){
  1674. return (src && dest && !strcmp(src, dest));
  1675. }
  1676. void strSafeDestroy(laSafeString **ss){
  1677. if (!*ss) return; lstRemoveItem(&SSC.SafeStrings, *ss);
  1678. if((*ss)->Ptr) memFree((*ss)->Ptr);
  1679. memFree(*ss); *ss=0;
  1680. }
  1681. void strSafeSet(laSafeString **ss, char *Content){
  1682. int len;
  1683. if (!Content||!Content[0]){ strSafeDestroy(ss); return; }
  1684. len = strlen(Content);
  1685. if (len < 1) return;
  1686. if (*ss){
  1687. char* mem=memAcquireSimple(sizeof(char)*(len+1));
  1688. strcpy(mem, Content);
  1689. memFree((*ss)->Ptr);
  1690. (*ss)->Ptr=mem;
  1691. return;
  1692. }
  1693. (*ss) = memAcquireSimple(sizeof(laSafeString));
  1694. (*ss)->Ptr = memAcquireSimple(sizeof(char)*(len+1));
  1695. strcpy((*ss)->Ptr, Content);
  1696. lstAppendItem(&SSC.SafeStrings, *ss);
  1697. }
  1698. void strSafeAppend(laSafeString **ss, char *Content){
  1699. if(!ss || !(*ss) || !Content){ strSafeSet(ss, Content); return; }
  1700. int OrigLen=strlen((*ss)->Ptr), ContentLen=strlen(Content);
  1701. char* mem=memAcquireSimple(sizeof(char)*(OrigLen+ContentLen+1));
  1702. memcpy(mem, (*ss)->Ptr, sizeof(char)*OrigLen);
  1703. memcpy(mem+sizeof(char)*OrigLen, Content, sizeof(char)*ContentLen);
  1704. mem[OrigLen+ContentLen]=0;
  1705. memFree((*ss)->Ptr);
  1706. (*ss)->Ptr=mem;
  1707. }
  1708. void strSafePrint(laSafeString **ss, char *Format, ...){
  1709. char content[512]; va_list va; va_start(va, Format); vsprintf(content, Format, va); va_end(va);
  1710. strSafeAppend(ss,content);
  1711. }
  1712. void strSafePrintV(laSafeString **ss, char *Format, va_list args){
  1713. char content[512]; va_list va; vsprintf(content, Format, args);
  1714. strSafeAppend(ss,content);
  1715. }
  1716. void strSafeDump(){
  1717. laSafeString*ss;
  1718. while(ss=lstPopItem(&SSC.SafeStrings)){
  1719. //if(ss->Ptr) printf("[String not freed] \"%s\"\n", ss->Ptr);
  1720. }
  1721. }
  1722. void strBeginEdit(laStringEdit **se, char *FullStr){
  1723. char *p = FullStr;
  1724. char buf[1024];
  1725. laStringEdit *nse = CreateNew(laStringEdit);
  1726. if(*se){ memcpy(nse,*se,sizeof(laStringEdit)); nse->Lines.pFirst=nse->Lines.pLast=0; nse->TotalLines=0; }
  1727. strEndEdit(se, 1);
  1728. nse->_BeginLine = -1; nse->_BeginBefore = -1;
  1729. if (FullStr && FullStr[0]){
  1730. while ((*p)){
  1731. laStringLine *sl = memAcquireSimple(sizeof(laStringLine));
  1732. p += strGetStringTerminateBy(p, '\n', buf);
  1733. strToUnicode(sl->Buf, buf);
  1734. lstAppendItem(&nse->Lines, sl); nse->TotalLines++;
  1735. if(*p){ p+=1; }
  1736. }
  1737. }
  1738. if (!nse->Lines.pFirst){
  1739. laStringLine *sl = memAcquireSimple(sizeof(laStringLine));
  1740. lstAppendItem(&nse->Lines, sl); nse->TotalLines=1;
  1741. }
  1742. laStringLine *sl = strGetCursorLine(nse, 0); int len=strlen(sl->Buf);
  1743. if(len<nse->CursorBefore){ nse->CursorBefore=len; }
  1744. *se=nse;
  1745. }
  1746. char* strGetEditString(laStringEdit *se, int SelectionOnly){
  1747. if(!se) return 0; char* result=0; int next=0, max=0, len=0;
  1748. arrEnsureLength(&result, 0, &max, sizeof(char)); int NextChar=0;
  1749. int Line=0, starti=0, endat=INT_MAX;
  1750. for(laStringLine* sl=se->Lines.pFirst;sl;sl=sl->Item.pNext,Line++){
  1751. starti=0;
  1752. if(SelectionOnly && Line<se->BeginLine){ continue; }
  1753. if(SelectionOnly && Line==se->BeginLine){ starti=se->BeginBefore; }
  1754. int tlen=strlenU(&sl->Buf[starti]); int Extra=sl->Item.pNext?2:1;
  1755. arrEnsureLength(&result, (len+tlen)*4+Extra, &max, sizeof(char));
  1756. if(SelectionOnly && Line==se->EndLine){ endat=NextChar+se->EndBefore-starti; }
  1757. NextChar+=strToUTF8Lim(&result[NextChar], &sl->Buf[starti], endat); len+=tlen;
  1758. if(Extra==2){ result[NextChar]='\n'; NextChar+=1; }
  1759. if(SelectionOnly && Line==se->EndLine){ break; }
  1760. }
  1761. return result;
  1762. }
  1763. char* strEndEdit(laStringEdit **se, int FreeString){
  1764. char *p=0; laStringLine *sl, *NextSl;
  1765. if (!se || !(*se)) return 0;
  1766. p=strGetEditString(*se, 0);
  1767. while (sl=lstPopItem(&(*se)->Lines)){ memFree(sl); }
  1768. FreeMem(*se); *se=0;
  1769. if(FreeString && p){ free(p); p=0; }
  1770. return p;
  1771. }
  1772. void strSetEditViewRange(laStringEdit* se, int Lines, int Cols){
  1773. se->ViewHeight = Lines; se->ViewWidth = Cols;
  1774. }
  1775. void strEnsureCursorVisible(laStringEdit* se){
  1776. if(!se->ViewHeight || !se->ViewWidth || se->CursorLine<0 || se->CursorBefore<0 ){return;}
  1777. if(se->CursorLine>se->ViewHeight+se->ViewStartLine-1){ se->ViewStartLine=se->CursorLine-se->ViewHeight+1; }
  1778. if(se->CursorLine<se->ViewStartLine){ se->ViewStartLine=se->CursorLine; }
  1779. if(se->CursorBefore>se->ViewStartCol+se->ViewWidth-1){ se->ViewStartCol=se->CursorBefore-se->ViewWidth+1; }
  1780. if(se->CursorBefore<se->ViewStartCol){ se->ViewStartCol=se->CursorBefore; }
  1781. }
  1782. void strRemoveLine(laStringEdit *se, laStringLine *sl){
  1783. lstRemoveItem(&se->Lines, sl);
  1784. memFree(sl); se->TotalLines--;
  1785. }
  1786. void strRemoveLineI(laStringEdit *se, int LineIndex){
  1787. int i = 0;
  1788. laStringLine *sl = se->Lines.pFirst, *NextSl;
  1789. while (sl){
  1790. NextSl = sl->Item.pNext;
  1791. if (i == LineIndex){ strRemoveLine(se, sl); break; }
  1792. i++;
  1793. sl = NextSl;
  1794. }
  1795. }
  1796. void strSetCursor(laStringEdit *se, int LineIndex, int BeforeIndex){
  1797. int maxbefore;
  1798. if (!se) return;
  1799. if(LineIndex<0){LineIndex=0;}
  1800. se->CursorLine = LineIndex;
  1801. maxbefore = strlenU(strGetCursorLine(se, &se->CursorLine)->Buf);
  1802. BeforeIndex = BeforeIndex < 0 ? 0 : BeforeIndex > maxbefore ? maxbefore : BeforeIndex;
  1803. se->CursorBefore = BeforeIndex;
  1804. se->BeginLine = -1;
  1805. se->BeginBefore = -1;
  1806. se->EndLine = -1;
  1807. se->EndBefore = -1;
  1808. strEnsureCursorVisible(se);
  1809. }
  1810. void strMoveCursor(laStringEdit *se, int Left, int Select){
  1811. int maxbefore;
  1812. int BeforeIndex;
  1813. int width = 1;
  1814. laStringLine *sl;
  1815. if (!se) return;
  1816. if(Select){ strLazySelect(se); } else { strCancelSelect(se); }
  1817. sl = strGetCursorLine(se, 0);
  1818. maxbefore = strlenU(sl->Buf);
  1819. BeforeIndex = se->CursorBefore - (Left ? 1 : -1);
  1820. if(BeforeIndex<0){
  1821. if(se->CursorLine>0) strSetCursor(se, se->CursorLine-1, INT_MAX);
  1822. }elif(BeforeIndex>maxbefore && se->CursorLine<se->TotalLines-1){
  1823. if(se->CursorLine>0) strSetCursor(se, se->CursorLine+1, 0);
  1824. }else{
  1825. se->CursorBefore = BeforeIndex>=maxbefore?maxbefore:BeforeIndex;
  1826. }
  1827. se->CursorPreferBefore = se->CursorBefore;
  1828. se->BeginLine = -1;
  1829. se->BeginBefore = -1;
  1830. se->EndLine = -1;
  1831. se->EndBefore = -1;
  1832. if(Select){ strEndSelect(se); }
  1833. strEnsureCursorVisible(se);
  1834. }
  1835. void strMoveCursorLine(laStringEdit *se, int Up, int Select){
  1836. int Line, maxbefore, LastIndex=-1;
  1837. laStringLine *sl;
  1838. if (!se) return;
  1839. if(Select){ strLazySelect(se); } else { strCancelSelect(se); }
  1840. Line=se->CursorLine - (Up? 1:-1);
  1841. if(Line<0) {Line=0;}
  1842. se->CursorLine = Line;
  1843. sl = strGetCursorLine(se, &LastIndex);
  1844. if(LastIndex>=0){ se->CursorLine = LastIndex; se->CursorPreferBefore=10000; }
  1845. maxbefore = strlenU(sl->Buf);
  1846. se->CursorBefore = se->CursorPreferBefore;
  1847. if(se->CursorBefore>maxbefore){ se->CursorBefore = maxbefore; }
  1848. if(LastIndex>=0){se->CursorPreferBefore=se->CursorBefore;}
  1849. if(Select){ strEndSelect(se); }
  1850. strEnsureCursorVisible(se);
  1851. }
  1852. int strHasSelection(laStringEdit* se){
  1853. return se->BeginBefore!=se->EndBefore||se->BeginLine!=se->EndLine;
  1854. }
  1855. void strCancelSelect(laStringEdit *se){
  1856. if (!se) return;
  1857. se->_BeginLine = -1;
  1858. se->_BeginBefore = -1;
  1859. se->BeginLine = -1;
  1860. se->EndLine = -1;
  1861. se->BeginBefore = -1;
  1862. se->EndBefore = -1;
  1863. }
  1864. void strLazySelect(laStringEdit *se){
  1865. if (!se || se->_BeginLine>=0) return;
  1866. se->_BeginLine = TNS_MAX2(se->CursorLine,0);
  1867. se->_BeginBefore = se->CursorBefore;
  1868. }
  1869. void strEndSelect(laStringEdit *se){
  1870. if (!se) return;
  1871. se->_EndLine = se->CursorLine;
  1872. se->_EndBefore = se->CursorBefore;
  1873. se->BeginLine = se->_BeginLine;
  1874. se->EndLine = se->_EndLine;
  1875. se->BeginBefore = se->_BeginBefore;
  1876. se->EndBefore = se->_EndBefore;
  1877. if(se->BeginLine>se->EndLine || (se->BeginLine==se->EndLine && se->BeginBefore>se->EndBefore))
  1878. { LA_SWAP(int,se->BeginLine,se->EndLine); LA_SWAP(int,se->BeginBefore,se->EndBefore); }
  1879. }
  1880. void strSelectLineAll(laStringEdit *se){
  1881. if (!se) return;
  1882. laStringLine *sl;
  1883. int len;
  1884. if (se->CursorLine == -1) sl = strGetBeginLine(se);
  1885. else
  1886. sl = strGetCursorLine(se, 0);
  1887. len = strlenU(sl->Buf);
  1888. se->EndBefore = len; se->EndLine=0;
  1889. se->BeginBefore = 0; se->BeginLine=0;
  1890. se->CursorBefore = len;
  1891. se->CursorLine = 0;
  1892. }
  1893. void strDeselectAll(laStringEdit *se){
  1894. if (!se) return;
  1895. laStringLine *sl;
  1896. int len;
  1897. if (se->CursorLine == -1) sl = strGetBeginLine(se);
  1898. else
  1899. sl = strGetCursorLine(se, 0);
  1900. len = strlenU(sl->Buf);
  1901. se->EndBefore = -1;
  1902. se->BeginBefore = -1;
  1903. se->BeginLine = -1;
  1904. se->EndLine = -1;
  1905. se->CursorBefore = len;
  1906. se->CursorLine = -1;
  1907. }
  1908. void strPanFoward(uint32_t *str, int Before, int Offset){
  1909. int len = strlenU(str);
  1910. int i = len + 1;
  1911. for (i; i >= Before; i--){
  1912. str[i + Offset] = str[i];
  1913. }
  1914. }
  1915. void strSquishBackward(uint32_t *str, int Before, int EndBefore){
  1916. int len = strlenU(str);
  1917. int i = Before;
  1918. int Offset = Before - EndBefore;
  1919. if (Before <= 0) return;
  1920. for (i; i <= len; i++){
  1921. str[i - Offset] = str[i];
  1922. }
  1923. }
  1924. void strClearSelection(laStringEdit *se){
  1925. //if (se->EndLine == -1) return;
  1926. if (se->BeginLine != se->EndLine){
  1927. int i = 0; int RemovedLines=0;
  1928. laStringLine *sl = se->Lines.pFirst, *NextSl;
  1929. while (sl){
  1930. NextSl = sl->Item.pNext;
  1931. if (i == se->BeginLine){
  1932. sl->Buf[se->BeginBefore] = U'\0';
  1933. }else if (i > se->BeginLine && i < se->EndLine){
  1934. strRemoveLine(se, sl); RemovedLines++;
  1935. }else if (i == se->EndLine){
  1936. strSquishBackward(sl->Buf, se->EndBefore, 0);
  1937. se->CursorLine = i-RemovedLines;
  1938. se->CursorBefore = 0;
  1939. se->BeginLine = -1;
  1940. se->BeginBefore = -1;
  1941. se->EndLine = -1;
  1942. se->EndBefore = -1;
  1943. strBackspace(se);
  1944. }
  1945. if (i > se->EndLine) break;
  1946. i++;
  1947. sl = NextSl;
  1948. }
  1949. }else{
  1950. int i = 0;
  1951. laStringLine *sl = se->Lines.pFirst, *NextSl;
  1952. while (sl){
  1953. NextSl = sl->Item.pNext;
  1954. if (i == se->EndLine) {
  1955. strSquishBackward(sl->Buf, se->EndBefore, se->BeginBefore);
  1956. se->CursorLine = i;
  1957. se->CursorBefore = se->BeginBefore;
  1958. se->BeginLine = -1;
  1959. se->BeginBefore = -1;
  1960. se->EndLine = -1;
  1961. se->EndBefore = -1;
  1962. break;
  1963. }
  1964. i++; sl = NextSl;
  1965. }
  1966. }
  1967. strEnsureCursorVisible(se);
  1968. }
  1969. laStringLine *strGetCursorLine(laStringEdit *se, int* ReturnIndexIfLast){
  1970. if (!se || se->CursorBefore <= -1) return se->Lines.pFirst;
  1971. int i = 0;
  1972. laStringLine *sl = se->Lines.pFirst, *NextSl;
  1973. while (sl){
  1974. NextSl = sl->Item.pNext;
  1975. if (i == se->CursorLine){
  1976. return sl;
  1977. }
  1978. i++;
  1979. sl = NextSl;
  1980. }
  1981. if(ReturnIndexIfLast){ *ReturnIndexIfLast=i-1;}
  1982. return se->Lines.pLast;
  1983. }
  1984. laStringLine *strGetBeginLine(laStringEdit *se){
  1985. if (!se || se->BeginLine <= -1) return se->Lines.pFirst;
  1986. int i = 0;
  1987. laStringLine *sl = se->Lines.pFirst, *NextSl;
  1988. while (sl){
  1989. NextSl = sl->Item.pNext;
  1990. if (i == se->BeginLine){
  1991. return sl;
  1992. }
  1993. i++;
  1994. sl = NextSl;
  1995. }
  1996. return se->Lines.pFirst;
  1997. }
  1998. void strInsertChar(laStringEdit *se, uint32_t a){
  1999. laStringLine *sl;
  2000. strClearSelection(se);
  2001. sl = strGetCursorLine(se, 0);
  2002. if(a==U'\n'){
  2003. laStringLine* nl=memAcquireSimple(sizeof(laStringLine));
  2004. if(sl->Buf[se->CursorBefore]!=U'\0') strcpyU(nl->Buf, &sl->Buf[se->CursorBefore]);
  2005. sl->Buf[se->CursorBefore]=U'\0';
  2006. se->CursorLine++; se->CursorBefore=0;
  2007. lstInsertItemAfter(&se->Lines, nl, sl); se->TotalLines++;
  2008. }else{
  2009. strPanFoward(sl->Buf, se->CursorBefore, 1);
  2010. sl->Buf[se->CursorBefore] = a;
  2011. se->CursorBefore += 1;
  2012. }
  2013. se->CursorPreferBefore = se->CursorBefore;
  2014. strEnsureCursorVisible(se);
  2015. }
  2016. void strBackspace(laStringEdit *se){
  2017. laStringLine *sl;
  2018. int width = 1;
  2019. if (se->CursorBefore == -1){
  2020. strClearSelection(se);
  2021. }else{
  2022. laStringLine *sl;
  2023. sl = strGetCursorLine(se, 0);
  2024. if (se->CursorBefore > 1 && sl->Buf[se->CursorBefore - 2] < 0) width = 2;
  2025. strSquishBackward(sl->Buf, se->CursorBefore, se->CursorBefore - width);
  2026. se->CursorBefore -= width;
  2027. if (se->CursorBefore <= -1){
  2028. if(sl->Item.pPrev){
  2029. laStringLine* ol=sl->Item.pPrev;
  2030. se->CursorBefore = strlenU(ol->Buf);
  2031. se->CursorLine--;
  2032. strcatU(ol->Buf, sl->Buf);
  2033. strRemoveLine(se, sl);
  2034. }
  2035. else {se->CursorBefore = 0;}
  2036. }
  2037. }
  2038. se->CursorPreferBefore = se->CursorBefore;
  2039. strEnsureCursorVisible(se);
  2040. }
  2041. void strMoveView(laStringEdit *se, int DownLines, int RightCharacters){
  2042. se->ViewStartLine+=DownLines;
  2043. se->ViewStartCol+=RightCharacters;
  2044. if(se->ViewStartLine>=se->TotalLines-1) se->ViewStartLine=se->TotalLines-1;
  2045. if(se->ViewStartLine<0) se->ViewStartLine=0;
  2046. if(se->ViewStartCol<0) se->ViewStartCol=0;
  2047. }
  2048. int laCopyFile(char *to, char *from){
  2049. #ifdef _WIN32
  2050. if(CopyFile(from, to, 0)) return 1; return 0;
  2051. #endif
  2052. #ifdef __linux__
  2053. int fd_to, fd_from; char buf[4096];
  2054. ssize_t nread; int saved_errno;
  2055. fd_from = open(from, O_RDONLY); if (fd_from < 0) return 0;
  2056. fd_to = open(to, O_WRONLY|O_CREAT /* |O_EXCL */, 0666); if (fd_to < 0) goto out_error;
  2057. while (nread=read(fd_from,buf,sizeof(buf)), nread>0) {
  2058. char *out_ptr = buf; ssize_t nwritten;
  2059. do { nwritten = write(fd_to, out_ptr, nread);
  2060. if (nwritten >= 0){ nread -= nwritten; out_ptr += nwritten;}
  2061. else if (errno != EINTR){ goto out_error; }
  2062. }while (nread > 0);
  2063. }
  2064. if (nread == 0){
  2065. if (close(fd_to)<0){ fd_to = -1; goto out_error;}
  2066. close(fd_from);
  2067. return 1;
  2068. }
  2069. out_error:
  2070. saved_errno = errno;
  2071. close(fd_from); if (fd_to >= 0) close(fd_to);
  2072. errno = saved_errno;
  2073. return 0;
  2074. #endif //linux
  2075. }
  2076. int laEnsureDir(const char *dir) {
  2077. #ifdef __linux__
  2078. char tmp[1024]; char *p = NULL; size_t len;
  2079. snprintf(tmp, sizeof(tmp),"%s",dir);
  2080. len = strlen(tmp);
  2081. if (tmp[len - 1] == '/') tmp[len - 1] = 0;
  2082. for (p = tmp + 1; *p; p++){
  2083. if (*p == '/') { *p = 0;
  2084. mkdir(tmp, S_IRWXU | S_IRWXG | S_IRWXO);
  2085. *p = '/';
  2086. }
  2087. }
  2088. mkdir(tmp, S_IRWXU | S_IRWXG | S_IRWXO);
  2089. struct stat statbuf;
  2090. if(stat(dir, &statbuf) != 0){ return 0; }
  2091. return S_ISDIR(statbuf.st_mode);
  2092. #endif
  2093. }
  2094. //======================================================[ translation ]
  2095. void transNewLanguage(const char *LanguageID){
  2096. laTranslationNode *tn = memAcquire(sizeof(laTranslationNode));
  2097. strSafeSet(&tn->LanguageName, LanguageID);
  2098. lstAppendItem(&MAIN.Translation.Languages, tn);
  2099. MAIN.Translation.CurrentLanguage = tn;
  2100. }
  2101. void transSetLanguage(const char *LanguageID){
  2102. laTranslationNode *tn;
  2103. if (!LanguageID){
  2104. MAIN.Translation.CurrentLanguage = 0;
  2105. return;
  2106. }
  2107. for (tn = MAIN.Translation.Languages.pFirst; tn; tn = tn->Item.pNext){
  2108. if (!strcmp(tn->LanguageName->Ptr, LanguageID)){
  2109. MAIN.Translation.CurrentLanguage = tn; return;
  2110. }
  2111. }
  2112. transNewLanguage(LanguageID);
  2113. }
  2114. void transDumpMissMatchRecord(const char *filename){
  2115. laTranslationMatch *tm;
  2116. laListHandle *lst;
  2117. int i;
  2118. FILE *f = fopen(filename, "w"); if (!f) return;
  2119. for (i = 0; i < 256; i++){
  2120. lst = &MAIN.Translation.MisMatches.Entries[i];
  2121. for (tm = lst->pFirst; tm; tm = tm->Item.pNext){ if(tm->Target) fprintf(f, "%s | \n", tm->Target); }
  2122. }
  2123. fclose(f);
  2124. }
  2125. int IsThisTranslationMatch(laTranslationMatch *tm, char *p){
  2126. return (tm->Target && (!strcmp(tm->Target, p)));
  2127. }
  2128. void transNewEntry(const char *Target, const char *replacement){
  2129. laTranslationMatch *tm = memAcquireSimple(sizeof(laTranslationMatch));
  2130. tm->Target = Target; tm->Replacement = replacement;
  2131. hsh256InsertItemCSTR(&MAIN.Translation.CurrentLanguage->Matches, tm, Target);
  2132. }
  2133. void transNewMissEntry(const char *Target){
  2134. if (!hsh256FindItemSTR(&MAIN.Translation.MisMatches, IsThisTranslationMatch, Target)){
  2135. laTranslationMatch *tm = memAcquireSimple(sizeof(laTranslationMatch));
  2136. int len=strlen(Target); tm->Target=memAcquireSimple(len*sizeof(char)+1);
  2137. strcpy(tm->Target,Target);
  2138. hsh256InsertItemCSTR(&MAIN.Translation.MisMatches, tm, Target);
  2139. }
  2140. }
  2141. char *transLate(char *Target){
  2142. if (!MAIN.Translation.CurrentLanguage || !MAIN.Translation.EnableTranslation || !Target || !Target[0]) return Target;
  2143. laTranslationMatch *tm = hsh256FindItemSTR(&MAIN.Translation.CurrentLanguage->Matches, IsThisTranslationMatch, Target);
  2144. if (!tm){ transNewMissEntry(Target); return Target; }
  2145. return tm->Replacement;
  2146. }
  2147. void transState(void *UNUSED, int val){
  2148. if (val) MAIN.Translation.EnableTranslation = 1;
  2149. else MAIN.Translation.EnableTranslation = 0;
  2150. laRedrawCurrentWindow();
  2151. }
  2152. void laOpenInternetLink(char *url){
  2153. laSafeString* s=0;
  2154. #ifdef __linux__
  2155. strSafePrint(&s, "xdg-open %s", url);
  2156. #endif
  2157. #ifdef _WIN32
  2158. strSafePrint(&s, "start %s", url);
  2159. #endif
  2160. system(s->Ptr);
  2161. strSafeDestroy(&s);
  2162. //these were windows stuff
  2163. //HKEY hkRoot, hSubKey;
  2164. //char ValueName[256]={0};
  2165. //char DataValue[256]={0};
  2166. //u64bit cbValueName = 256;
  2167. //u64bit cbDataValue = 256;
  2168. //char ShellChar[512]={0};
  2169. //DWORD dwType;
  2170. //
  2171. //ShellExecute(0, "open", link, 0, 0, SW_SHOWNORMAL);
  2172. //
  2173. //return;
  2174. }
  2175. #ifdef _WIN32
  2176. void usleep(unsigned int usec){
  2177. HANDLE timer;
  2178. LARGE_INTEGER ft;
  2179. static int init = 0;
  2180. if (init == 0){
  2181. init = 1;
  2182. const HINSTANCE ntdll = LoadLibrary("ntdll.dll");
  2183. if (ntdll != NULL){
  2184. typedef long(NTAPI* pNtQueryTimerResolution)(u64bit* MinimumResolution, u64bit* MaximumResolution, u64bit* CurrentResolution);
  2185. typedef long(NTAPI* pNtSetTimerResolution)(u64bit RequestedResolution, char SetResolution, u64bit* ActualResolution);
  2186. pNtQueryTimerResolution NtQueryTimerResolution = (pNtQueryTimerResolution)GetProcAddress(ntdll, "NtQueryTimerResolution");
  2187. pNtSetTimerResolution NtSetTimerResolution = (pNtSetTimerResolution)GetProcAddress(ntdll, "NtSetTimerResolution");
  2188. if (NtQueryTimerResolution != NULL && NtSetTimerResolution != NULL){
  2189. u64bit minimum, maximum, current;
  2190. NtQueryTimerResolution(&minimum, &maximum, &current);
  2191. NtSetTimerResolution(maximum, (char)1, &current);
  2192. }
  2193. FreeLibrary(ntdll);
  2194. }
  2195. }
  2196. ft.QuadPart = -(10 * (__int64)usec);
  2197. timer = CreateWaitableTimer(NULL, TRUE, NULL);
  2198. SetWaitableTimer(timer, &ft, 0, NULL, NULL, 0);
  2199. WaitForSingleObject(timer, INFINITE);
  2200. CloseHandle(timer);
  2201. }
  2202. void laSpinInit(SYSLOCK* lock) {
  2203. InitializeCriticalSection(lock);
  2204. }
  2205. void laSpinDestroy(SYSLOCK* lock) {
  2206. DeleteCriticalSection(lock);
  2207. }
  2208. void laSpinLock(SYSLOCK* lock) {
  2209. EnterCriticalSection(lock);
  2210. }
  2211. void laSpinUnlock(SYSLOCK* lock) {
  2212. LeaveCriticalSection(lock);
  2213. }
  2214. #endif
  2215. #ifdef __linux__
  2216. void laSpinInit(SYSLOCK* lock) {
  2217. pthread_spin_init(lock, 0);
  2218. }
  2219. void laSpinDestroy(SYSLOCK* lock) {
  2220. pthread_spin_destroy(lock);
  2221. }
  2222. void laSpinLock(SYSLOCK* lock) {
  2223. pthread_spin_lock(lock);
  2224. }
  2225. void laSpinUnlock(SYSLOCK* lock) {
  2226. pthread_spin_unlock(lock);
  2227. }
  2228. #endif
  2229. //======================================= lua utils
  2230. #ifdef LA_WITH_LUAJIT
  2231. static const char *progname = LUA_PROGNAME;
  2232. static int la_luaTraceback(lua_State *L){
  2233. if (!lua_isstring(L, 1)) { /* Non-string error object? Try metamethod. */
  2234. if (lua_isnoneornil(L, 1) ||
  2235. !luaL_callmeta(L, 1, "__tostring") ||
  2236. !lua_isstring(L, -1))
  2237. return 1; /* Return non-string error object. */
  2238. lua_remove(L, 1); /* Replace object by result of __tostring metamethod. */
  2239. }
  2240. luaL_traceback(L, L, lua_tostring(L, 1), 1);
  2241. return 1;
  2242. }
  2243. static void la_luaMessage(const char *msg){
  2244. if (progname) { logPrint("%s: ",progname); } logPrint("%s\n",msg);
  2245. }
  2246. static int la_luaReport(lua_State *L, int status){
  2247. if (status && !lua_isnil(L, -1)) {
  2248. const char *msg = lua_tostring(L, -1);
  2249. if (msg == NULL) msg = "(error object is not a string)";
  2250. la_luaMessage(msg);
  2251. lua_pop(L, 1);
  2252. }
  2253. return status;
  2254. }
  2255. static int la_luaDoCall(lua_State *L, int narg, int clear){
  2256. int status;
  2257. int base = lua_gettop(L) - narg; /* function index */
  2258. lua_pushcfunction(L, la_luaTraceback); /* push la_luaTraceback function */
  2259. lua_insert(L, base); /* put it under chunk and args */
  2260. status = lua_pcall(L, narg, (clear ? 0 : LUA_MULTRET), base);
  2261. lua_remove(L, base); /* remove la_luaTraceback function */
  2262. /* force a complete garbage collection in case of errors */
  2263. if (status != LUA_OK) lua_gc(L, LUA_GCCOLLECT, 0);
  2264. return status;
  2265. }
  2266. static int la_luaIncomplete(lua_State *L, int status){
  2267. if (status == LUA_ERRSYNTAX) {
  2268. size_t lmsg;
  2269. const char *msg = lua_tolstring(L, -1, &lmsg);
  2270. const char *tp = msg + lmsg - (sizeof(LUA_QL("<eof>")) - 1);
  2271. if (strstr(msg, LUA_QL("<eof>")) == tp) { lua_pop(L, 1); return 1; }
  2272. }
  2273. return 0; /* else... */
  2274. }
  2275. int terLoadLine(char* buf, int firstline){
  2276. lua_State *L=MAIN.L;
  2277. if(!MAIN.TerminalIncomplete){ lua_settop(L, 0); }
  2278. size_t len = strlen(buf); if(len>=512){ buf[512]=0; }
  2279. if(len > 0 && buf[len-1] == '\n') buf[len-1] = '\0';
  2280. if(firstline && buf[0] == '=') lua_pushfstring(L, "return %s", buf+1);
  2281. else lua_pushstring(L, buf);
  2282. if(MAIN.TerminalIncomplete){
  2283. lua_pushliteral(L, "\n"); lua_insert(L, -2); lua_concat(L, 3);
  2284. }
  2285. int status = luaL_loadbuffer(L, lua_tostring(L, 1), lua_strlen(L, 1), "terLoadLine");
  2286. if(la_luaIncomplete(L,status)){
  2287. MAIN.TerminalIncomplete=1;
  2288. }else{
  2289. MAIN.TerminalIncomplete=0;
  2290. lua_remove(L, 1);
  2291. }
  2292. if(status==LUA_OK && (!MAIN.TerminalIncomplete)){
  2293. status = la_luaDoCall(L, 0, 0);
  2294. la_luaReport(L, status);
  2295. if (status == LUA_OK && lua_gettop(L) > 0) { /* any result to print? */
  2296. lua_getglobal(L, "log");
  2297. lua_insert(L, 1);
  2298. if (lua_pcall(L, lua_gettop(L)-1, 0, 0) != 0)
  2299. la_luaMessage(lua_pushfstring(L, "error calling " LUA_QL("log") " (%s)",
  2300. lua_tostring(L, -1)));
  2301. }
  2302. }
  2303. return status;
  2304. }
  2305. static int lalua_Log(lua_State *L) {
  2306. int n = lua_gettop(L); int i;
  2307. lua_getglobal(L, "tostring");
  2308. for (i=1; i<=n; i++) {
  2309. const char *s;
  2310. lua_pushvalue(L, -1); /* tostring function */
  2311. lua_pushvalue(L, i); /* value to print */
  2312. lua_call(L, 1, 1);
  2313. s = lua_tostring(L, -1); /* get result */
  2314. if (s == NULL) return luaL_error(L, LUA_QL("tostring") " must return a string to "LUA_QL("use `log`"));
  2315. if (i>1) logPrint(" ");
  2316. logPrint(s); lua_pop(L, 1); /* pop result */
  2317. }
  2318. logPrint("\n");
  2319. return 0;
  2320. }
  2321. void la_luaLoadLibs(lua_State *L){
  2322. lua_gc(L, LUA_GCSTOP, 0);
  2323. luaL_openlibs(L);
  2324. lua_register(L,"log",lalua_Log);
  2325. if(luaL_loadstring(L, LA_LUA_LIB_COMMON) || lua_pcall(L, 0, 0, 0)){ logPrint(" Error loading lagui lua libs.\n"); };
  2326. if(luaL_loadstring(L, LA_LUA_LIB_AUDIO) || lua_pcall(L, 0, 0, 0)){ logPrint(" Error loading lua libs for audio.\n"); };
  2327. lua_gc(L, LUA_GCRESTART, -1);
  2328. }
  2329. void la_luaPrintStatus(lua_State *L){
  2330. logPrint(LUAJIT_VERSION " -- " LUAJIT_COPYRIGHT ". " LUAJIT_URL "\n");
  2331. int n; const char *s;
  2332. lua_getfield(L, LUA_REGISTRYINDEX, "_LOADED");
  2333. lua_getfield(L, -1, "jit"); lua_remove(L, -2); /* Get jit.* module table. */
  2334. lua_getfield(L, -1, "status"); lua_remove(L, -2);
  2335. n = lua_gettop(L);
  2336. lua_call(L, 0, LUA_MULTRET);
  2337. logPrint(lua_toboolean(L, n) ? "JIT: ON" : "JIT: OFF");
  2338. for (n++; (s = lua_tostring(L, n)); n++) { logPrint("%s ",s); }
  2339. logPrint("\n");
  2340. lua_settop(L, 0); /* clear stack */
  2341. }
  2342. void la_luaDumpStack(lua_State *L){
  2343. int top=lua_gettop(L); for (int i=1; i <= top; i++) {
  2344. printf("%d\t%s\t", i, luaL_typename(L,i));
  2345. switch (lua_type(L, i)) {
  2346. case LUA_TNUMBER: printf("%g\n",lua_tonumber(L,i)); break;
  2347. case LUA_TSTRING: printf("%s\n",lua_tostring(L,i)); break;
  2348. case LUA_TBOOLEAN: printf("%s\n", (lua_toboolean(L, i) ? "true" : "false")); break;
  2349. case LUA_TNIL: printf("%s\n", "nil"); break;
  2350. default: printf("%p\n",lua_topointer(L,i)); break;
  2351. }
  2352. }
  2353. }
  2354. #else //luajit
  2355. int terLoadLine(char* buf, int firstline){
  2356. logPrint(buf); return 0;
  2357. }
  2358. #endif //luajit