*/}}

la_util.c 71 KB

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