*/}}

la_util.c 71 KB

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