*/}}

la_util.c 72 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429
  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++;
  1504. }
  1505. *se=nse;
  1506. }
  1507. char* strGetEditString(laStringEdit *se, int SelectionOnly){
  1508. if(!se) return 0; char* result=0; int next=0, max=0, len=0;
  1509. arrEnsureLength(&result, 0, &max, sizeof(char)); int NextChar=0;
  1510. int Line=0, starti=0, endat=INT_MAX;
  1511. for(laStringLine* sl=se->Lines.pFirst;sl;sl=sl->Item.pNext,Line++){
  1512. starti=0;
  1513. if(SelectionOnly && Line<se->BeginLine){ continue; }
  1514. if(SelectionOnly && Line==se->BeginLine){ starti=se->BeginBefore; }
  1515. int tlen=strlenU(&sl->Buf[starti]); int Extra=sl->Item.pNext?2:1;
  1516. arrEnsureLength(&result, (len+tlen)*4+Extra, &max, sizeof(char));
  1517. if(SelectionOnly && Line==se->EndLine){ endat=NextChar+se->EndBefore-starti; }
  1518. NextChar+=strToUTF8Lim(&result[NextChar], &sl->Buf[starti], endat); len+=tlen;
  1519. if(Extra==2){ result[NextChar]='\n'; NextChar+=1; }
  1520. if(SelectionOnly && Line==se->EndLine){ break; }
  1521. }
  1522. return result;
  1523. }
  1524. char* strEndEdit(laStringEdit **se, int FreeString){
  1525. char *p=0; laStringLine *sl, *NextSl;
  1526. if (!se || !(*se)) return 0;
  1527. p=strGetEditString(*se, 0);
  1528. while (sl=lstPopItem(&(*se)->Lines)){ memFree(sl); }
  1529. FreeMem(*se); *se=0;
  1530. if(FreeString && p){ free(p); p=0; }
  1531. return p;
  1532. }
  1533. void strSetEditViewRange(laStringEdit* se, int Lines, int Cols){
  1534. se->ViewHeight = Lines; se->ViewWidth = Cols;
  1535. }
  1536. void strEnsureCursorVisible(laStringEdit* se){
  1537. if(!se->ViewHeight || !se->ViewWidth || se->CursorLine<0 || se->CursorBefore<0 ){return;}
  1538. if(se->CursorLine>se->ViewHeight+se->ViewStartLine-1){ se->ViewStartLine=se->CursorLine-se->ViewHeight+1; }
  1539. if(se->CursorLine<se->ViewStartLine){ se->ViewStartLine=se->CursorLine; }
  1540. if(se->CursorBefore>se->ViewStartCol+se->ViewWidth-1){ se->ViewStartCol=se->CursorBefore-se->ViewWidth+1; }
  1541. if(se->CursorBefore<se->ViewStartCol){ se->ViewStartCol=se->CursorBefore; }
  1542. }
  1543. void strRemoveLine(laStringEdit *se, laStringLine *sl){
  1544. lstRemoveItem(&se->Lines, sl);
  1545. memFree(sl); se->TotalLines--;
  1546. }
  1547. void strRemoveLineI(laStringEdit *se, int LineIndex){
  1548. int i = 0;
  1549. laStringLine *sl = se->Lines.pFirst, *NextSl;
  1550. while (sl){
  1551. NextSl = sl->Item.pNext;
  1552. if (i == LineIndex){ strRemoveLine(se, sl); break; }
  1553. i++;
  1554. sl = NextSl;
  1555. }
  1556. }
  1557. void strSetCursor(laStringEdit *se, int LineIndex, int BeforeIndex){
  1558. int maxbefore;
  1559. if (!se) return;
  1560. if(LineIndex<0){LineIndex=0;}
  1561. se->CursorLine = LineIndex;
  1562. maxbefore = strlenU(strGetCursorLine(se, &se->CursorLine)->Buf);
  1563. BeforeIndex = BeforeIndex < 0 ? 0 : BeforeIndex > maxbefore ? maxbefore : BeforeIndex;
  1564. se->CursorBefore = BeforeIndex;
  1565. se->BeginLine = -1;
  1566. se->BeginBefore = -1;
  1567. se->EndLine = -1;
  1568. se->EndBefore = -1;
  1569. strEnsureCursorVisible(se);
  1570. }
  1571. void strMoveCursor(laStringEdit *se, int Left, int Select){
  1572. int maxbefore;
  1573. int BeforeIndex;
  1574. int width = 1;
  1575. laStringLine *sl;
  1576. if (!se) return;
  1577. if(Select){ strLazySelect(se); } else { strCancelSelect(se); }
  1578. sl = strGetCursorLine(se, 0);
  1579. maxbefore = strlenU(sl->Buf);
  1580. BeforeIndex = se->CursorBefore - (Left ? 1 : -1);
  1581. if(BeforeIndex<0){
  1582. if(se->CursorLine>0) strSetCursor(se, se->CursorLine-1, INT_MAX);
  1583. }elif(BeforeIndex>maxbefore && se->CursorLine<se->TotalLines-1){
  1584. if(se->CursorLine>0) strSetCursor(se, se->CursorLine+1, 0);
  1585. }else{
  1586. se->CursorBefore = BeforeIndex>=maxbefore?maxbefore:BeforeIndex;
  1587. }
  1588. se->CursorPreferBefore = se->CursorBefore;
  1589. se->BeginLine = -1;
  1590. se->BeginBefore = -1;
  1591. se->EndLine = -1;
  1592. se->EndBefore = -1;
  1593. if(Select){ strEndSelect(se); }
  1594. strEnsureCursorVisible(se);
  1595. }
  1596. void strMoveCursorLine(laStringEdit *se, int Up, int Select){
  1597. int Line, maxbefore, LastIndex=-1;
  1598. laStringLine *sl;
  1599. if (!se) return;
  1600. if(Select){ strLazySelect(se); } else { strCancelSelect(se); }
  1601. Line=se->CursorLine - (Up? 1:-1);
  1602. if(Line<0) {Line=0;}
  1603. se->CursorLine = Line;
  1604. sl = strGetCursorLine(se, &LastIndex);
  1605. if(LastIndex>=0){ se->CursorLine = LastIndex; se->CursorPreferBefore=10000; }
  1606. maxbefore = strlenU(sl->Buf);
  1607. se->CursorBefore = se->CursorPreferBefore;
  1608. if(se->CursorBefore>maxbefore){ se->CursorBefore = maxbefore; }
  1609. if(LastIndex>=0){se->CursorPreferBefore=se->CursorBefore;}
  1610. if(Select){ strEndSelect(se); }
  1611. strEnsureCursorVisible(se);
  1612. }
  1613. int strHasSelection(laStringEdit* se){
  1614. return se->BeginBefore!=se->EndBefore||se->BeginLine!=se->EndLine;
  1615. }
  1616. void strCancelSelect(laStringEdit *se){
  1617. if (!se) return;
  1618. se->_BeginLine = -1;
  1619. se->_BeginBefore = -1;
  1620. se->BeginLine = -1;
  1621. se->EndLine = -1;
  1622. se->BeginBefore = -1;
  1623. se->EndBefore = -1;
  1624. }
  1625. void strLazySelect(laStringEdit *se){
  1626. if (!se || se->_BeginLine>=0) return;
  1627. se->_BeginLine = TNS_MAX2(se->CursorLine,0);
  1628. se->_BeginBefore = se->CursorBefore;
  1629. }
  1630. void strEndSelect(laStringEdit *se){
  1631. if (!se) return;
  1632. se->_EndLine = se->CursorLine;
  1633. se->_EndBefore = se->CursorBefore;
  1634. se->BeginLine = se->_BeginLine;
  1635. se->EndLine = se->_EndLine;
  1636. se->BeginBefore = se->_BeginBefore;
  1637. se->EndBefore = se->_EndBefore;
  1638. if(se->BeginLine>se->EndLine || (se->BeginLine==se->EndLine && se->BeginBefore>se->EndBefore))
  1639. { LA_SWAP(int,se->BeginLine,se->EndLine); LA_SWAP(int,se->BeginBefore,se->EndBefore); }
  1640. }
  1641. void strSelectLineAll(laStringEdit *se){
  1642. if (!se) return;
  1643. laStringLine *sl;
  1644. int len;
  1645. if (se->CursorLine == -1) sl = strGetBeginLine(se);
  1646. else
  1647. sl = strGetCursorLine(se, 0);
  1648. len = strlenU(sl->Buf);
  1649. se->EndBefore = len; se->EndLine=0;
  1650. se->BeginBefore = 0; se->BeginLine=0;
  1651. se->CursorBefore = len;
  1652. se->CursorLine = 0;
  1653. }
  1654. void strDeselectAll(laStringEdit *se){
  1655. if (!se) return;
  1656. laStringLine *sl;
  1657. int len;
  1658. if (se->CursorLine == -1) sl = strGetBeginLine(se);
  1659. else
  1660. sl = strGetCursorLine(se, 0);
  1661. len = strlenU(sl->Buf);
  1662. se->EndBefore = -1;
  1663. se->BeginBefore = -1;
  1664. se->BeginLine = -1;
  1665. se->EndLine = -1;
  1666. se->CursorBefore = len;
  1667. se->CursorLine = -1;
  1668. }
  1669. void strPanFoward(uint32_t *str, int Before, int Offset){
  1670. int len = strlenU(str);
  1671. int i = len + 1;
  1672. for (i; i >= Before; i--){
  1673. str[i + Offset] = str[i];
  1674. }
  1675. }
  1676. void strSquishBackward(uint32_t *str, int Before, int EndBefore){
  1677. int len = strlenU(str);
  1678. int i = Before;
  1679. int Offset = Before - EndBefore;
  1680. if (Before <= 0) return;
  1681. for (i; i <= len; i++){
  1682. str[i - Offset] = str[i];
  1683. }
  1684. }
  1685. void strClearSelection(laStringEdit *se){
  1686. //if (se->EndLine == -1) return;
  1687. if (se->BeginLine != se->EndLine){
  1688. int i = 0; int RemovedLines=0;
  1689. laStringLine *sl = se->Lines.pFirst, *NextSl;
  1690. while (sl){
  1691. NextSl = sl->Item.pNext;
  1692. if (i == se->BeginLine){
  1693. sl->Buf[se->BeginBefore] = U'\0';
  1694. }else if (i > se->BeginLine && i < se->EndLine){
  1695. strRemoveLine(se, sl); RemovedLines++;
  1696. }else if (i == se->EndLine){
  1697. strSquishBackward(sl->Buf, se->EndBefore, 0);
  1698. se->CursorLine = i-RemovedLines;
  1699. se->CursorBefore = 0;
  1700. se->BeginLine = -1;
  1701. se->BeginBefore = -1;
  1702. se->EndLine = -1;
  1703. se->EndBefore = -1;
  1704. strBackspace(se);
  1705. }
  1706. if (i > se->EndLine) break;
  1707. i++;
  1708. sl = NextSl;
  1709. }
  1710. }else{
  1711. int i = 0;
  1712. laStringLine *sl = se->Lines.pFirst, *NextSl;
  1713. while (sl){
  1714. NextSl = sl->Item.pNext;
  1715. if (i == se->EndLine) {
  1716. strSquishBackward(sl->Buf, se->EndBefore, se->BeginBefore);
  1717. se->CursorLine = i;
  1718. se->CursorBefore = se->BeginBefore;
  1719. se->BeginLine = -1;
  1720. se->BeginBefore = -1;
  1721. se->EndLine = -1;
  1722. se->EndBefore = -1;
  1723. break;
  1724. }
  1725. i++; sl = NextSl;
  1726. }
  1727. }
  1728. strEnsureCursorVisible(se);
  1729. }
  1730. laStringLine *strGetCursorLine(laStringEdit *se, int* ReturnIndexIfLast){
  1731. if (!se || se->CursorBefore <= -1) return se->Lines.pFirst;
  1732. int i = 0;
  1733. laStringLine *sl = se->Lines.pFirst, *NextSl;
  1734. while (sl){
  1735. NextSl = sl->Item.pNext;
  1736. if (i == se->CursorLine){
  1737. return sl;
  1738. }
  1739. i++;
  1740. sl = NextSl;
  1741. }
  1742. if(ReturnIndexIfLast){ *ReturnIndexIfLast=i-1;}
  1743. return se->Lines.pLast;
  1744. }
  1745. laStringLine *strGetBeginLine(laStringEdit *se){
  1746. if (!se || se->BeginLine <= -1) return se->Lines.pFirst;
  1747. int i = 0;
  1748. laStringLine *sl = se->Lines.pFirst, *NextSl;
  1749. while (sl){
  1750. NextSl = sl->Item.pNext;
  1751. if (i == se->BeginLine){
  1752. return sl;
  1753. }
  1754. i++;
  1755. sl = NextSl;
  1756. }
  1757. return se->Lines.pFirst;
  1758. }
  1759. void strInsertChar(laStringEdit *se, uint32_t a){
  1760. laStringLine *sl;
  1761. strClearSelection(se);
  1762. sl = strGetCursorLine(se, 0);
  1763. if(a==U'\n'){
  1764. laStringLine* nl=memAcquireSimple(sizeof(laStringLine));
  1765. if(sl->Buf[se->CursorBefore]!=U'\0') strcpyU(nl->Buf, &sl->Buf[se->CursorBefore]);
  1766. sl->Buf[se->CursorBefore]=U'\0';
  1767. se->CursorLine++; se->CursorBefore=0;
  1768. lstInsertItemAfter(&se->Lines, nl, sl); se->TotalLines++;
  1769. }else{
  1770. strPanFoward(sl->Buf, se->CursorBefore, 1);
  1771. sl->Buf[se->CursorBefore] = a;
  1772. se->CursorBefore += 1;
  1773. }
  1774. se->CursorPreferBefore = se->CursorBefore;
  1775. strEnsureCursorVisible(se);
  1776. }
  1777. void strBackspace(laStringEdit *se){
  1778. laStringLine *sl;
  1779. int width = 1;
  1780. if (se->CursorBefore == -1){
  1781. strClearSelection(se);
  1782. }else{
  1783. laStringLine *sl;
  1784. sl = strGetCursorLine(se, 0);
  1785. if (se->CursorBefore > 1 && sl->Buf[se->CursorBefore - 2] < 0) width = 2;
  1786. strSquishBackward(sl->Buf, se->CursorBefore, se->CursorBefore - width);
  1787. se->CursorBefore -= width;
  1788. if (se->CursorBefore <= -1){
  1789. if(sl->Item.pPrev){
  1790. laStringLine* ol=sl->Item.pPrev;
  1791. se->CursorBefore = strlenU(ol->Buf);
  1792. se->CursorLine--;
  1793. strcatU(ol->Buf, sl->Buf);
  1794. strRemoveLine(se, sl);
  1795. }
  1796. else {se->CursorBefore = 0;}
  1797. }
  1798. }
  1799. se->CursorPreferBefore = se->CursorBefore;
  1800. strEnsureCursorVisible(se);
  1801. }
  1802. void strMoveView(laStringEdit *se, int DownLines, int RightCharacters){
  1803. se->ViewStartLine+=DownLines;
  1804. se->ViewStartCol+=RightCharacters;
  1805. if(se->ViewStartLine>=se->TotalLines-1) se->ViewStartLine=se->TotalLines-1;
  1806. if(se->ViewStartLine<0) se->ViewStartLine=0;
  1807. if(se->ViewStartCol<0) se->ViewStartCol=0;
  1808. }
  1809. int laCopyFile(char *to, char *from){
  1810. #ifdef _WIN32
  1811. if(CopyFile(from, to, 0)) return 1; return 0;
  1812. #endif
  1813. #ifdef __linux__
  1814. int fd_to, fd_from; char buf[4096];
  1815. ssize_t nread; int saved_errno;
  1816. fd_from = open(from, O_RDONLY); if (fd_from < 0) return -1;
  1817. fd_to = open(to, O_WRONLY|O_CREAT|O_EXCL, 0666); if (fd_to < 0) goto out_error;
  1818. while (nread=read(fd_from,buf,sizeof(buf)), nread>0) {
  1819. char *out_ptr = buf; ssize_t nwritten;
  1820. do { nwritten = write(fd_to, out_ptr, nread);
  1821. if (nwritten >= 0){ nread -= nwritten; out_ptr += nwritten;}
  1822. else if (errno != EINTR){ goto out_error; }
  1823. }while (nread > 0);
  1824. }
  1825. if (nread == 0){
  1826. if (close(fd_to)<0){ fd_to = -1; goto out_error;}
  1827. close(fd_from);
  1828. /* Success! */
  1829. return 0;
  1830. }
  1831. out_error:
  1832. saved_errno = errno;
  1833. close(fd_from); if (fd_to >= 0) close(fd_to);
  1834. errno = saved_errno;
  1835. return -1;
  1836. #endif //linux
  1837. }
  1838. //======================================================[ translation ]
  1839. void transNewLanguage(const char *LanguageID){
  1840. laTranslationNode *tn = memAcquire(sizeof(laTranslationNode));
  1841. strSafeSet(&tn->LanguageName, LanguageID);
  1842. lstAppendItem(&MAIN.Translation.Languages, tn);
  1843. MAIN.Translation.CurrentLanguage = tn;
  1844. }
  1845. void transSetLanguage(const char *LanguageID){
  1846. laTranslationNode *tn;
  1847. if (!LanguageID){
  1848. MAIN.Translation.CurrentLanguage = 0;
  1849. return;
  1850. }
  1851. for (tn = MAIN.Translation.Languages.pFirst; tn; tn = tn->Item.pNext){
  1852. if (!strcmp(tn->LanguageName->Ptr, LanguageID)){
  1853. MAIN.Translation.CurrentLanguage = tn; return;
  1854. }
  1855. }
  1856. transNewLanguage(LanguageID);
  1857. }
  1858. void transDumpMissMatchRecord(const char *filename){
  1859. laTranslationMatch *tm;
  1860. laListHandle *lst;
  1861. int i;
  1862. FILE *f = fopen(filename, "w"); if (!f) return;
  1863. for (i = 0; i < 256; i++){
  1864. lst = &MAIN.Translation.MisMatches.Entries[i];
  1865. for (tm = lst->pFirst; tm; tm = tm->Item.pNext){ if(tm->Target) fprintf(f, "%s | \n", tm->Target); }
  1866. }
  1867. fclose(f);
  1868. }
  1869. int IsThisTranslationMatch(laTranslationMatch *tm, char *p){
  1870. return (tm->Target && (!strcmp(tm->Target, p)));
  1871. }
  1872. void transNewEntry(const char *Target, const char *replacement){
  1873. laTranslationMatch *tm = memAcquireSimple(sizeof(laTranslationMatch));
  1874. tm->Target = Target; tm->Replacement = replacement;
  1875. hsh256InsertItemCSTR(&MAIN.Translation.CurrentLanguage->Matches, tm, Target);
  1876. }
  1877. void transNewMissEntry(const char *Target){
  1878. if (!hsh256FindItemSTR(&MAIN.Translation.MisMatches, IsThisTranslationMatch, Target)){
  1879. laTranslationMatch *tm = memAcquireSimple(sizeof(laTranslationMatch));
  1880. int len=strlen(Target); tm->Target=memAcquireSimple(len*sizeof(char)+1);
  1881. strcpy(tm->Target,Target);
  1882. hsh256InsertItemCSTR(&MAIN.Translation.MisMatches, tm, Target);
  1883. }
  1884. }
  1885. char *transLate(char *Target){
  1886. if (!MAIN.Translation.CurrentLanguage || !MAIN.Translation.EnableTranslation || !Target || !Target[0]) return Target;
  1887. laTranslationMatch *tm = hsh256FindItemSTR(&MAIN.Translation.CurrentLanguage->Matches, IsThisTranslationMatch, Target);
  1888. if (!tm){ transNewMissEntry(Target); return Target; }
  1889. return tm->Replacement;
  1890. }
  1891. void transState(void *UNUSED, int val){
  1892. if (val) MAIN.Translation.EnableTranslation = 1;
  1893. else MAIN.Translation.EnableTranslation = 0;
  1894. laRedrawCurrentWindow();
  1895. }
  1896. void laOpenInternetLink(char *url){
  1897. laSafeString* s=0;
  1898. #ifdef __linux__
  1899. strSafePrint(&s, "xdg-open %s", url);
  1900. #endif
  1901. #ifdef _WIN32
  1902. strSafePrint(&s, "start %s", url);
  1903. #endif
  1904. system(s->Ptr);
  1905. strSafeDestroy(&s);
  1906. //these were windows stuff
  1907. //HKEY hkRoot, hSubKey;
  1908. //char ValueName[256]={0};
  1909. //char DataValue[256]={0};
  1910. //unsigned long cbValueName = 256;
  1911. //unsigned long cbDataValue = 256;
  1912. //char ShellChar[512]={0};
  1913. //DWORD dwType;
  1914. //
  1915. //ShellExecute(0, "open", link, 0, 0, SW_SHOWNORMAL);
  1916. //
  1917. //return;
  1918. }
  1919. #ifdef _WIN32
  1920. void usleep(unsigned int usec){
  1921. HANDLE timer;
  1922. LARGE_INTEGER ft;
  1923. static int init = 0;
  1924. if (init == 0){
  1925. init = 1;
  1926. const HINSTANCE ntdll = LoadLibrary("ntdll.dll");
  1927. if (ntdll != NULL){
  1928. typedef long(NTAPI* pNtQueryTimerResolution)(unsigned long* MinimumResolution, unsigned long* MaximumResolution, unsigned long* CurrentResolution);
  1929. typedef long(NTAPI* pNtSetTimerResolution)(unsigned long RequestedResolution, char SetResolution, unsigned long* ActualResolution);
  1930. pNtQueryTimerResolution NtQueryTimerResolution = (pNtQueryTimerResolution)GetProcAddress(ntdll, "NtQueryTimerResolution");
  1931. pNtSetTimerResolution NtSetTimerResolution = (pNtSetTimerResolution)GetProcAddress(ntdll, "NtSetTimerResolution");
  1932. if (NtQueryTimerResolution != NULL && NtSetTimerResolution != NULL){
  1933. unsigned long minimum, maximum, current;
  1934. NtQueryTimerResolution(&minimum, &maximum, &current);
  1935. NtSetTimerResolution(maximum, (char)1, &current);
  1936. }
  1937. FreeLibrary(ntdll);
  1938. }
  1939. }
  1940. ft.QuadPart = -(10 * (__int64)usec);
  1941. timer = CreateWaitableTimer(NULL, TRUE, NULL);
  1942. SetWaitableTimer(timer, &ft, 0, NULL, NULL, 0);
  1943. WaitForSingleObject(timer, INFINITE);
  1944. CloseHandle(timer);
  1945. }
  1946. void laSpinInit(SYSLOCK* lock) {
  1947. InitializeCriticalSection(lock);
  1948. }
  1949. void laSpinDestroy(SYSLOCK* lock) {
  1950. DeleteCriticalSection(lock);
  1951. }
  1952. void laSpinLock(SYSLOCK* lock) {
  1953. EnterCriticalSection(lock);
  1954. }
  1955. void laSpinUnlock(SYSLOCK* lock) {
  1956. LeaveCriticalSection(lock);
  1957. }
  1958. #endif
  1959. #ifdef __linux__
  1960. void laSpinInit(SYSLOCK* lock) {
  1961. pthread_spin_init(lock, 0);
  1962. }
  1963. void laSpinDestroy(SYSLOCK* lock) {
  1964. pthread_spin_destroy(lock);
  1965. }
  1966. void laSpinLock(SYSLOCK* lock) {
  1967. pthread_spin_lock(lock);
  1968. }
  1969. void laSpinUnlock(SYSLOCK* lock) {
  1970. pthread_spin_unlock(lock);
  1971. }
  1972. #endif
  1973. //======================================= lua utils
  1974. static const char *progname = LUA_PROGNAME;
  1975. static int traceback(lua_State *L){
  1976. if (!lua_isstring(L, 1)) { /* Non-string error object? Try metamethod. */
  1977. if (lua_isnoneornil(L, 1) ||
  1978. !luaL_callmeta(L, 1, "__tostring") ||
  1979. !lua_isstring(L, -1))
  1980. return 1; /* Return non-string error object. */
  1981. lua_remove(L, 1); /* Replace object by result of __tostring metamethod. */
  1982. }
  1983. luaL_traceback(L, L, lua_tostring(L, 1), 1);
  1984. return 1;
  1985. }
  1986. static void l_message(const char *msg){
  1987. if (progname) { fputs(progname, stderr); fputc(':', stderr); fputc(' ', stderr); }
  1988. fputs(msg, stderr); fputc('\n', stderr);
  1989. fflush(stderr);
  1990. }
  1991. static int report(lua_State *L, int status){
  1992. if (status && !lua_isnil(L, -1)) {
  1993. const char *msg = lua_tostring(L, -1);
  1994. if (msg == NULL) msg = "(error object is not a string)";
  1995. l_message(msg);
  1996. lua_pop(L, 1);
  1997. }
  1998. return status;
  1999. }
  2000. static int docall(lua_State *L, int narg, int clear){
  2001. int status;
  2002. int base = lua_gettop(L) - narg; /* function index */
  2003. lua_pushcfunction(L, traceback); /* push traceback function */
  2004. lua_insert(L, base); /* put it under chunk and args */
  2005. status = lua_pcall(L, narg, (clear ? 0 : LUA_MULTRET), base);
  2006. lua_remove(L, base); /* remove traceback function */
  2007. /* force a complete garbage collection in case of errors */
  2008. if (status != LUA_OK) lua_gc(L, LUA_GCCOLLECT, 0);
  2009. return status;
  2010. }
  2011. static void write_prompt(lua_State *L, int firstline){
  2012. const char *p;
  2013. lua_getfield(L, LUA_GLOBALSINDEX, firstline ? "_PROMPT" : "_PROMPT2");
  2014. p = lua_tostring(L, -1);
  2015. if (p == NULL) p = firstline ? LUA_PROMPT : LUA_PROMPT2;
  2016. fputs(p, stdout);
  2017. fflush(stdout);
  2018. lua_pop(L, 1); /* remove global */
  2019. }
  2020. static int incomplete(lua_State *L, int status){
  2021. if (status == LUA_ERRSYNTAX) {
  2022. size_t lmsg;
  2023. const char *msg = lua_tolstring(L, -1, &lmsg);
  2024. const char *tp = msg + lmsg - (sizeof(LUA_QL("<eof>")) - 1);
  2025. if (strstr(msg, LUA_QL("<eof>")) == tp) {
  2026. lua_pop(L, 1);
  2027. return 1;
  2028. }
  2029. }
  2030. return 0; /* else... */
  2031. }
  2032. static int pushline(lua_State *L, int firstline){
  2033. char buf[LUA_MAXINPUT];
  2034. write_prompt(L, firstline);
  2035. if (fgets(buf, LUA_MAXINPUT, stdin)) {
  2036. size_t len = strlen(buf);
  2037. if (len > 0 && buf[len-1] == '\n')
  2038. buf[len-1] = '\0';
  2039. if (firstline && buf[0] == '=')
  2040. lua_pushfstring(L, "return %s", buf+1);
  2041. else
  2042. lua_pushstring(L, buf);
  2043. return 1;
  2044. }
  2045. return 0;
  2046. }
  2047. static int loadline(lua_State *L){
  2048. int status;
  2049. lua_settop(L, 0);
  2050. if (!pushline(L, 1))
  2051. return -1; /* no input */
  2052. for (;;) { /* repeat until gets a complete line */
  2053. status = luaL_loadbuffer(L, lua_tostring(L, 1), lua_strlen(L, 1), "=stdin");
  2054. if (!incomplete(L, status)) break; /* cannot try to add lines? */
  2055. if (!pushline(L, 0)) /* no more input? */
  2056. return -1;
  2057. lua_pushliteral(L, "\n"); /* add a new line... */
  2058. lua_insert(L, -2); /* ...between the two lines */
  2059. lua_concat(L, 3); /* join them */
  2060. }
  2061. lua_remove(L, 1); /* remove line */
  2062. return status;
  2063. }
  2064. void dotty(lua_State *L){
  2065. int status;
  2066. const char *oldprogname = progname;
  2067. progname = NULL;
  2068. while ((status = loadline(L)) != -1) {
  2069. if (status == LUA_OK) status = docall(L, 0, 0);
  2070. report(L, status);
  2071. if (status == LUA_OK && lua_gettop(L) > 0) { /* any result to print? */
  2072. lua_getglobal(L, "print");
  2073. lua_insert(L, 1);
  2074. if (lua_pcall(L, lua_gettop(L)-1, 0, 0) != 0)
  2075. l_message(lua_pushfstring(L, "error calling " LUA_QL("print") " (%s)",
  2076. lua_tostring(L, -1)));
  2077. }
  2078. }
  2079. lua_settop(L, 0); /* clear stack */
  2080. fputs("\n", stdout);
  2081. fflush(stdout);
  2082. progname = oldprogname;
  2083. }
  2084. static int lalua_Log(lua_State *L) {
  2085. int n = lua_gettop(L); int i;
  2086. lua_getglobal(L, "tostring");
  2087. for (i=1; i<=n; i++) {
  2088. const char *s;
  2089. lua_pushvalue(L, -1); /* tostring function */
  2090. lua_pushvalue(L, i); /* value to print */
  2091. lua_call(L, 1, 1);
  2092. s = lua_tostring(L, -1); /* get result */
  2093. if (s == NULL) return luaL_error(L, LUA_QL("tostring") " must return a string to "LUA_QL("use `log`"));
  2094. if (i>1) logPrint(" ");
  2095. logPrint(s); lua_pop(L, 1); /* pop result */
  2096. }
  2097. logPrint("\n");
  2098. return 0;
  2099. }
  2100. void la_LuaJITLoadLibs(){
  2101. lua_State *L=MAIN.L;
  2102. lua_gc(MAIN.L, LUA_GCSTOP, 0);
  2103. luaL_openlibs(MAIN.L);
  2104. lua_register(L,"log",lalua_Log);
  2105. lua_gc(MAIN.L, LUA_GCRESTART, -1);
  2106. }
  2107. int terLoadLine(char* buf, int firstline){
  2108. lua_State *L=MAIN.L;
  2109. if(!MAIN.TerminalIncomplete){ lua_settop(L, 0); }
  2110. size_t len = strlen(buf); if(len>=512){ buf[512]=0; }
  2111. if(len > 0 && buf[len-1] == '\n') buf[len-1] = '\0';
  2112. if(firstline && buf[0] == '=') lua_pushfstring(L, "return %s", buf+1);
  2113. else lua_pushstring(L, buf);
  2114. if(MAIN.TerminalIncomplete){
  2115. lua_pushliteral(L, "\n"); lua_insert(L, -2); lua_concat(L, 3);
  2116. }
  2117. int status = luaL_loadbuffer(L, lua_tostring(L, 1), lua_strlen(L, 1), "terLoadLine");
  2118. if(incomplete(L,status)){
  2119. MAIN.TerminalIncomplete=1;
  2120. }else{
  2121. MAIN.TerminalIncomplete=0;
  2122. lua_remove(L, 1);
  2123. }
  2124. if(status==LUA_OK && (!MAIN.TerminalIncomplete)){
  2125. status = docall(L, 0, 0);
  2126. report(L, status);
  2127. if (status == LUA_OK && lua_gettop(L) > 0) { /* any result to print? */
  2128. lua_getglobal(L, "log");
  2129. lua_insert(L, 1);
  2130. if (lua_pcall(L, lua_gettop(L)-1, 0, 0) != 0)
  2131. l_message(lua_pushfstring(L, "error calling " LUA_QL("log") " (%s)",
  2132. lua_tostring(L, -1)));
  2133. }
  2134. }
  2135. return status;
  2136. }
  2137. void la_PrintLuaJITStatus(){
  2138. lua_State *L=MAIN.L;
  2139. logPrint(LUAJIT_VERSION " -- " LUAJIT_COPYRIGHT ". " LUAJIT_URL "\n");
  2140. int n; const char *s;
  2141. lua_getfield(L, LUA_REGISTRYINDEX, "_LOADED");
  2142. lua_getfield(L, -1, "jit"); lua_remove(L, -2); /* Get jit.* module table. */
  2143. lua_getfield(L, -1, "status"); lua_remove(L, -2);
  2144. n = lua_gettop(L);
  2145. lua_call(L, 0, LUA_MULTRET);
  2146. logPrint(lua_toboolean(L, n) ? "JIT: ON" : "JIT: OFF");
  2147. for (n++; (s = lua_tostring(L, n)); n++) {
  2148. logPrint("%s ",s);
  2149. }
  2150. putc('\n', stdout);
  2151. lua_settop(L, 0); /* clear stack */
  2152. }