/*
* LaGUI: A graphical application framework.
* Copyright (C) 2022-2023 Wu Yiming
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see .
*/
#define _CRT_SEQURE_NO_WARNINGS
#include "la_util.h"
#include "la_interface.h"
#include
#include
laSafeStringCollection SSC;
extern LA MAIN;
#define BYTE unsigned char
uint32_t laToUnicode(const unsigned char* ch, int* advance){
if((*ch)<0x80) { *advance=1; return *ch; }
uint32_t u=0;
if(((*ch)>>5)==0x06){ *advance=2; u|=((*(ch+1))&0x3f)|((*(ch)&0x1f)<<6); return u; }
if(((*ch)>>4)==0x0e){ *advance=3; u|=((*(ch+2))&0x3f)|((*(ch+1)&0x3f)<<6)|((*(ch)&0x0f)<<12); return u; }
if(((*ch)>>3)==0x1e){ *advance=4; u|=((*(ch+3))&0x3f)|((*(ch+2)&0x3f)<<6)|((*(ch+1)&0x3f)<<12)|((*(ch)&0x07)<<18); return u; }
*advance=1; return '?';
}
int laToUTF8(const uint32_t ch, unsigned char* out, unsigned char** next){
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;}
elif(ch>=0x800){ out[0]=0xe0|(ch>>12); out[1]=0x80|(0x3f&(ch>>6)); out[2]=0x80|(0x3f&ch); (*next)+=3;}
elif(ch>=0x80){ out[0]=0xc0|(ch>>6); out[1]=0x80|(0x3f&ch); (*next)+=2;}
else { if(!ch){return 0;} out[0]=ch&0x7f; (*next)++;} return 1;
}
int strToUnicode(uint32_t* target, unsigned char* const src){
uint32_t UC,adv,i=0; unsigned char* source=src; while(target[i]=laToUnicode(source, &adv)) { source+=adv; i++; } target[i]=0; return i;
}
int strToUTF8Lim(unsigned char* target, uint32_t* const src, int count){
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;
}
int strToUTF8(unsigned char* target, uint32_t* const src){
strToUTF8Lim(target,src,INT_MAX);
}
int strlenU(uint32_t* str){ int i=0; while(str[i]!=0) i++; return i; }
int strcpyU(uint32_t* target, uint32_t* const source ){ int i=0; while(source[i]!=0){ target[i]=source[i]; i++; } target[i]=0; }
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; }
struct tm *laGetFullTime(){
time_t t = time(0);
return localtime(&t);
}
void laRecordTime(laTimeRecorder *tr){
#ifdef LA_LINUX
clock_gettime(CLOCK_REALTIME, &tr->ts);
#endif
#ifdef _WIN32
QueryPerformanceCounter(&tr->tm);
#endif
}
real laTimeElapsedSecondsf(laTimeRecorder *End, laTimeRecorder *Begin){
real sec=0;
#ifdef LA_LINUX
sec=End->ts.tv_sec-Begin->ts.tv_sec; sec+=((End->ts.tv_nsec-Begin->ts.tv_nsec)/1e9);
#endif
#ifdef _WIN32
LARGE_INTEGER perfCnt; QueryPerformanceFrequency(&perfCnt);
sec = ((real)(End->tm.QuadPart - Begin->tm.QuadPart))/ perfCnt.QuadPart;
#endif
#ifdef LAGUI_ANDROID
#endif
return sec;
}
void laSetAuthorInfo(char *Name, char *CopyrightString){
strSafeSet(&MAIN.Author.Name, Name);
strSafeSet(&MAIN.Author.CopyrightString, CopyrightString);
}
void memCreateNUID(char* buf,laMemNodeHyper* Hyper){
sprintf(buf, "%08X-%hd%02hd%02hd%02hd%02hd%02hd", Hyper, LA_HYPER_CREATED_TIME(Hyper));
}
void memHyperInfo(laPropPack* pp, char* buf){
int level=0;void* head=0;
laMemNodeHyper* hi; laMemNode* mn;
int a=0, count=0, pc;
laProp* p=pp->LastPs->p;
laPropContainer* c=p->Container;
if(c->OtherAlloc){
count=lstCountElements(&c->LocalUsers);
}else{
head=memGetHead(pp->LastPs->UseInstance, &level);
if(!level){
sprintf(buf,"Not HyperData.\n");
}elif(level==1){
mn=head; count=lstCountElements(&mn->Users);
}elif(level==2){
hi=head; count=lstCountElements(&hi->Users);
}
}
a=sprintf(buf,"HyperData:\n\tProperty:%s\n\tContainer:%s (%d users)\n",
pp->LastPs->p->Identifier, pp->LastPs->p->Container->Identifier, count);
if(level==2){
sprintf(buf+a,"\tCreated:%hd-%02hd-%02hd %02hd:%02hd:%02hd\n",LA_HYPER_CREATED_TIME(hi));
}
}
void memMakeHyperData(laMemNodeHyper* hi){
struct tm *time;
hi->Modified = 1;
time = laGetFullTime();
//hi->CreatedBy = &MAIN.Author;
hi->TimeCreated.Year = time->tm_year + 1900;
hi->TimeCreated.Month = time->tm_mon + 1;
hi->TimeCreated.Day = time->tm_mday;
hi->TimeCreated.Hour = time->tm_hour;
hi->TimeCreated.Minute = time->tm_min;
hi->TimeCreated.Second = time->tm_sec;
//memcpy(&hi->TimeModified, &hi->TimeCreated, sizeof(laTimeInfo));
memCreateNUID(hi->NUID.String,hi);
}
void memMarkClean(void* HyperUserMem){
int Hyper=0;
laMemNodeHyper* h = memGetHead(HyperUserMem, &Hyper);
if(Hyper!=2) return;
h->Modified=0;
}
void nutFreeMem(void **ptr){
//free_total+=1;
if (!*ptr) return;
free(*ptr);
*ptr = 0;
}
int nutFloatCompare(real l, real r){
return (l > r - 0.00005 && l < r + 0.00005);
}
int nutSameAddress(void *l, void *r){
return (l == r);
}
//===================================================================[barray]
#ifdef _MSC_VER
# include
# define __builtin_popcountll __popcnt64
static inline int __builtin_ctzl(u64bit x)
{
#ifdef _WIN64
return (int)_tzcnt_u64(x);
#else
return !!unsigned(x) ? __builtin_ctz((unsigned)x) : 32 + __builtin_ctz((unsigned)(x >> 32));
#endif
}
#endif
barray_t *barray_init(size_t num_bits)
{
size_t num_longs = BITS_TO_LONGS(num_bits);
barray_t *barray = calloc(1,sizeof(u64bit) * num_longs + sizeof(barray_t));
barray->num_bits = num_bits;
barray->num_longs = num_longs;
return barray;
}
void barray_free(barray_t *barray)
{
free(barray);
}
u64bit *barray_data(barray_t *barray)
{
return barray->data;
}
size_t barray_count_set(barray_t *barray)
{
size_t count = 0;
for (int i = 0; i < barray->num_longs; i++)
count += __builtin_popcountll(barray->data[i]);
return count;
}
void barray_set(barray_t *barray, bit_t bit)
{
if (bit >= barray->num_bits)
return;
int index = bit / BITS_PER_LONG;
int shift = bit % BITS_PER_LONG;
barray->data[index] |= ((u64bit)1 << shift);
}
void barray_clear(barray_t *barray, bit_t bit)
{
if (bit >= barray->num_bits)
return;
int index = bit / BITS_PER_LONG;
int shift = bit % BITS_PER_LONG;
barray->data[index] &= ~((u64bit)1 << shift);
}
bool barray_is_set(barray_t *barray, bit_t bit)
{
if (bit >= barray->num_bits)
return false;
int index = bit / BITS_PER_LONG;
int shift = bit % BITS_PER_LONG;
return (barray->data[index] & ((u64bit)1 << shift)) != 0;
}
void barray_foreach_set(barray_t *barray, barray_callback_t callback, void *arg)
{
for (int i = 0; i < barray->num_longs; i++)
{
u64bit bits = barray->data[i];
while (bits != 0)
{
callback(i * BITS_PER_LONG + __builtin_ctzl(bits), arg);
bits ^= (bits & -bits);
}
}
}
//===================================================================[md5]
#define A 0x67452301
#define B 0xefcdab89
#define C 0x98badcfe
#define D 0x10325476
static uint32_t S[] = {7, 12, 17, 22, 7, 12, 17, 22, 7, 12, 17, 22, 7, 12, 17, 22,
5, 9, 14, 20, 5, 9, 14, 20, 5, 9, 14, 20, 5, 9, 14, 20,
4, 11, 16, 23, 4, 11, 16, 23, 4, 11, 16, 23, 4, 11, 16, 23,
6, 10, 15, 21, 6, 10, 15, 21, 6, 10, 15, 21, 6, 10, 15, 21};
static uint32_t K[] = {0xd76aa478, 0xe8c7b756, 0x242070db, 0xc1bdceee,
0xf57c0faf, 0x4787c62a, 0xa8304613, 0xfd469501,
0x698098d8, 0x8b44f7af, 0xffff5bb1, 0x895cd7be,
0x6b901122, 0xfd987193, 0xa679438e, 0x49b40821,
0xf61e2562, 0xc040b340, 0x265e5a51, 0xe9b6c7aa,
0xd62f105d, 0x02441453, 0xd8a1e681, 0xe7d3fbc8,
0x21e1cde6, 0xc33707d6, 0xf4d50d87, 0x455a14ed,
0xa9e3e905, 0xfcefa3f8, 0x676f02d9, 0x8d2a4c8a,
0xfffa3942, 0x8771f681, 0x6d9d6122, 0xfde5380c,
0xa4beea44, 0x4bdecfa9, 0xf6bb4b60, 0xbebfbc70,
0x289b7ec6, 0xeaa127fa, 0xd4ef3085, 0x04881d05,
0xd9d4d039, 0xe6db99e5, 0x1fa27cf8, 0xc4ac5665,
0xf4292244, 0x432aff97, 0xab9423a7, 0xfc93a039,
0x655b59c3, 0x8f0ccc92, 0xffeff47d, 0x85845dd1,
0x6fa87e4f, 0xfe2ce6e0, 0xa3014314, 0x4e0811a1,
0xf7537e82, 0xbd3af235, 0x2ad7d2bb, 0xeb86d391};
static uint8_t PADDING[] = {0x80, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00};
#define F(X, Y, Z) ((X & Y) | (~X & Z))
#define G(X, Y, Z) ((X & Z) | (Y & ~Z))
#define H(X, Y, Z) (X ^ Y ^ Z)
#define I(X, Y, Z) (Y ^ (X | ~Z))
uint32_t rotateLeft(uint32_t x, uint32_t n){
return (x << n) | (x >> (32 - n));
}
void md5Init(MD5Context *ctx){
ctx->size = (uint64_t)0;
ctx->buffer[0] = (uint32_t)A;
ctx->buffer[1] = (uint32_t)B;
ctx->buffer[2] = (uint32_t)C;
ctx->buffer[3] = (uint32_t)D;
}
void md5Update(MD5Context *ctx, uint8_t *input_buffer, size_t input_len){
uint32_t input[16];
unsigned int offset = ctx->size % 64;
ctx->size += (uint64_t)input_len;
// Copy each byte in input_buffer into the next space in our context input
for(unsigned int i = 0; i < input_len; ++i){
ctx->input[offset++] = (uint8_t)*(input_buffer + i);
// If we've filled our context input, copy it into our local array input
// then reset the offset to 0 and fill in a new buffer.
// Every time we fill out a chunk, we run it through the algorithm
// to enable some back and forth between cpu and i/o
if(offset % 64 == 0){
for(unsigned int j = 0; j < 16; ++j){
// Convert to little-endian
// The local variable `input` our 512-bit chunk separated into 32-bit words
// we can use in calculations
input[j] = (uint32_t)(ctx->input[(j * 4) + 3]) << 24 |
(uint32_t)(ctx->input[(j * 4) + 2]) << 16 |
(uint32_t)(ctx->input[(j * 4) + 1]) << 8 |
(uint32_t)(ctx->input[(j * 4)]);
}
md5Step(ctx->buffer, input);
offset = 0;
}
}
}
void md5Finalize(MD5Context *ctx){
uint32_t input[16];
unsigned int offset = ctx->size % 64;
unsigned int padding_length = offset < 56 ? 56 - offset : (56 + 64) - offset;
// Fill in the padding and undo the changes to size that resulted from the update
md5Update(ctx, PADDING, padding_length);
ctx->size -= (uint64_t)padding_length;
// Do a final update (internal to this function)
// Last two 32-bit words are the two halves of the size (converted from bytes to bits)
for(unsigned int j = 0; j < 14; ++j){
input[j] = (uint32_t)(ctx->input[(j * 4) + 3]) << 24 |
(uint32_t)(ctx->input[(j * 4) + 2]) << 16 |
(uint32_t)(ctx->input[(j * 4) + 1]) << 8 |
(uint32_t)(ctx->input[(j * 4)]);
}
input[14] = (uint32_t)(ctx->size * 8);
input[15] = (uint32_t)((ctx->size * 8) >> 32);
md5Step(ctx->buffer, input);
// Move the result into digest (convert from little-endian)
for(unsigned int i = 0; i < 4; ++i){
ctx->digest[(i * 4) + 0] = (uint8_t)((ctx->buffer[i] & 0x000000FF));
ctx->digest[(i * 4) + 1] = (uint8_t)((ctx->buffer[i] & 0x0000FF00) >> 8);
ctx->digest[(i * 4) + 2] = (uint8_t)((ctx->buffer[i] & 0x00FF0000) >> 16);
ctx->digest[(i * 4) + 3] = (uint8_t)((ctx->buffer[i] & 0xFF000000) >> 24);
}
}
void md5Step(uint32_t *buffer, uint32_t *input){
uint32_t AA = buffer[0];
uint32_t BB = buffer[1];
uint32_t CC = buffer[2];
uint32_t DD = buffer[3];
uint32_t E;
unsigned int j;
for(unsigned int i = 0; i < 64; ++i){
switch(i / 16){
case 0:
E = F(BB, CC, DD);
j = i;
break;
case 1:
E = G(BB, CC, DD);
j = ((i * 5) + 1) % 16;
break;
case 2:
E = H(BB, CC, DD);
j = ((i * 3) + 5) % 16;
break;
default:
E = I(BB, CC, DD);
j = (i * 7) % 16;
break;
}
uint32_t temp = DD;
DD = CC;
CC = BB;
BB = BB + rotateLeft(AA + E + K[i] + input[j], S[i]);
AA = temp;
}
buffer[0] += AA;
buffer[1] += BB;
buffer[2] += CC;
buffer[3] += DD;
}
void md5String(char *input, uint8_t *result){
MD5Context ctx;
md5Init(&ctx);
md5Update(&ctx, (uint8_t *)input, strlen(input));
md5Finalize(&ctx);
memcpy(result, ctx.digest, 16);
}
void md5File(FILE *file, uint8_t *result){
char *input_buffer = malloc(1024);
size_t input_size = 0;
MD5Context ctx;
md5Init(&ctx);
while((input_size = fread(input_buffer, 1, 1024, file)) > 0){
md5Update(&ctx, (uint8_t *)input_buffer, input_size);
}
md5Finalize(&ctx);
free(input_buffer);
memcpy(result, ctx.digest, 16);
}
void toHexString(char* text, char* hex){
int len = strlen(text);
for (int i = 0, j = 0; i < len; ++i, j += 2)
sprintf(hex + j, "%02x", text[i] & 0xff);
}
#undef A
#undef B
#undef C
#undef D
//===================================================================[list]
void* arrElement(void* head, int i, int size){
return ((char*)head+size*i);
}
int arrEnsureLength(void** head, int next, int* max, size_t ElementSize){
int UseMax=*max; int nocopy=(!UseMax);
if(next>=UseMax){
if(!UseMax){ UseMax=50; }
int AllocMax=next>(UseMax*2)?(next+16):(UseMax*2);
void* data = CreateNew_Size(ElementSize* AllocMax);
if(((*head) || next)&&(!nocopy)){ memcpy(data, *head, ElementSize*UseMax); }
if(*head) free(*head);
*head=data;
*max=AllocMax;
return 1;
}
return 0;
}
int arrInitLength(void** head, int max, int* pmax, size_t ElementSize){
if(*head){ free(head); }
*head=CreateNew_Size(ElementSize*max);
*pmax=max;
}
void arrFree(void** head, int* max){ free(*head); *head=0; *max=0; }
void lstPushSingle(void **Head, laListSingle *Item){
Item->pNext = *Head;
*Head = Item;
}
void *lstPopSingle(void **Head, laListSingle *Item){
*Head = ((laListSingle *)(*Head))->pNext;
Item->pNext = 0;
return *Head;
}
int lstCountElements(laListHandle* Handle){
int count=0; if(!Handle) return 0;
for(laListItem* i=Handle->pFirst;i;i=i->pNext){count++;}
return count;
}
void lstAppendItem(laListHandle* Handle, void* Item){
laListItem* li = Item;
li->pNext = li->pPrev = 0;
if (!Handle->pFirst) Handle->pFirst = Item;
if (Handle->pLast) ((laListItem*)Handle->pLast)->pNext = li;
li->pPrev = Handle->pLast;
li->pNext = 0;
Handle->pLast = li;
};
void lstPushItem(laListHandle* Handle, void* Item){
laListItem* li = Item;
li->pNext = li->pPrev = 0;
if (!Handle->pLast) Handle->pLast = Item;
li->pNext = Handle->pFirst;
if (Handle->pFirst) ((laListItem*)Handle->pFirst)->pPrev = Item;
Handle->pFirst = li;
};
void* lstPopItem(laListHandle* Handle){
laListItem* popitem;
laListItem* next;
if (!Handle->pFirst) return 0;
popitem = Handle->pFirst;
next = ((laListItem*)Handle->pFirst)->pNext;
if (!next){
Handle->pFirst = 0;
Handle->pLast = 0;
}else{
Handle->pFirst = next;
if (next) next->pPrev = 0;
};
popitem->pNext=popitem->pPrev=0;
return popitem;
};
int lstHaveItemInList(laListHandle *Handle){
if (Handle->pFirst) return 1;
return 0;
};
void lstAppendItem2(laListHandle *Handle, void *Item){
laListItem2 *li = Item;
li->pNext = li->pPrev = 0;
if (!Handle->pFirst) Handle->pFirst = Item;
if (Handle->pLast) ((laListItem2 *)Handle->pLast)->pNext = li;
li->pPrev = Handle->pLast;
li->pNext = 0;
Handle->pLast = li;
};
void lstPushItem2(laListHandle *Handle, void *Item){
laListItem2 *li = Item;
li->pNext = li->pPrev = 0;
if (!Handle->pLast) Handle->pLast = Item;
li->pNext = Handle->pFirst;
if (Handle->pFirst) ((laListItem2 *)Handle->pFirst)->pPrev = Item;
Handle->pFirst = li;
};
void *lstPopItem2(laListHandle *Handle){
void *popitem;
laListItem2 *next;
if (!Handle->pFirst) return 0;
popitem = Handle->pFirst;
next = ((laListItem2 *)Handle->pFirst)->pNext;
if (!next){
Handle->pFirst = 0;
Handle->pLast = 0;
}else{
Handle->pFirst = next;
if (next) next->pPrev = 0;
};
return popitem;
};
void lstAppendItem3(laListHandle *Handle, void *Item){
laListItem3 *li = Item;
li->pNext = li->pPrev = 0;
if (!Handle->pFirst) Handle->pFirst = Item;
if (Handle->pLast) ((laListItem3 *)Handle->pLast)->pNext = li;
li->pPrev = Handle->pLast;
li->pNext = 0;
Handle->pLast = li;
};
void lstPushItem3(laListHandle *Handle, void *Item){
laListItem3 *li = Item;
li->pNext = li->pPrev = 0;
if (!Handle->pLast) Handle->pLast = Item;
li->pNext = Handle->pFirst;
if (Handle->pFirst) ((laListItem3 *)Handle->pFirst)->pPrev = Item;
Handle->pFirst = li;
};
void *lstPopItem3(laListHandle *Handle){
void *popitem;
laListItem3 *next;
if (!Handle->pFirst) return 0;
popitem = Handle->pFirst;
next = ((laListItem3 *)Handle->pFirst)->pNext;
if (!next){
Handle->pFirst = 0;
Handle->pLast = 0;
}else{
Handle->pFirst = next;
if (next) next->pPrev = 0;
};
return popitem;
};
void *lstGetTop(laListHandle *Handle){
return Handle->pFirst;
};
int lstRemoveItem(laListHandle* Handle, laListItem* li) {
if (!li->pPrev && Handle->pFirst != li) return 0;
if (!li->pPrev) Handle->pFirst = li->pNext;
else
((laListItem*)li->pPrev)->pNext = li->pNext;
if (!li->pNext) Handle->pLast = li->pPrev;
else
((laListItem*)li->pNext)->pPrev = li->pPrev;
li->pNext = li->pPrev = 0;
}
int lstRemoveItem2(laListHandle *Handle, laListItem2 *li){
if (!li->pPrev) Handle->pFirst = li->pNext;
else
((laListItem2 *)li->pPrev)->pNext = li->pNext;
if (!li->pNext) Handle->pLast = li->pPrev;
else
((laListItem2 *)li->pNext)->pPrev = li->pPrev;
li->pNext = li->pPrev = 0;
};
int lstRemoveItem3(laListHandle *Handle, laListItem2 *li){
if (!li->pPrev) Handle->pFirst = li->pNext;
else
((laListItem3 *)li->pPrev)->pNext = li->pNext;
if (!li->pNext) Handle->pLast = li->pPrev;
else
((laListItem3 *)li->pNext)->pPrev = li->pPrev;
li->pNext = li->pPrev = 0;
};
int lstRemoveSegment(laListHandle *Handle, laListItem *Begin, laListItem *End){
if (!Begin->pPrev) Handle->pFirst = End->pNext;
else
((laListItem *)Begin->pPrev)->pNext = End->pNext;
if (!End->pNext) Handle->pLast = Begin->pPrev;
else
((laListItem *)End->pNext)->pPrev = Begin->pPrev;
End->pNext = Begin->pPrev = 0;
};
void lstInsertItemBefore(laListHandle *Handle, laListItem *toIns, laListItem *pivot){
if (!pivot){
lstPushItem(Handle, toIns);
return;
}
if (pivot->pPrev){
((laListItem *)pivot->pPrev)->pNext = toIns;
toIns->pPrev = pivot->pPrev;
}else{
Handle->pFirst = toIns;
}
toIns->pNext = pivot;
pivot->pPrev = toIns;
};
void lstInsertItemAfter(laListHandle *Handle, laListItem *toIns, laListItem *pivot){
if (!pivot){
lstAppendItem(Handle, toIns);
return;
}
if (pivot->pNext){
((laListItem *)pivot->pNext)->pPrev = toIns;
toIns->pNext = pivot->pNext;
}else{
Handle->pLast = toIns;
}
toIns->pPrev = pivot;
pivot->pNext = toIns;
}
void lstInsertSegmentBefore(laListHandle *Handle, laListItem *Begin, laListItem *End, laListItem *pivot){
if (pivot->pPrev){
((laListItem *)pivot->pPrev)->pNext = Begin;
Begin->pPrev = pivot->pPrev;
}else{
Handle->pFirst = Begin;
}
End->pNext = pivot;
pivot->pPrev = End;
};
void lstInsertSegmentAfter(laListHandle *Handle, laListItem *Begin, laListItem *End, laListItem *pivot){
if (pivot->pNext){
((laListItem *)pivot->pNext)->pPrev = End;
End->pNext = pivot->pNext;
}else{
Handle->pLast = End;
}
Begin->pPrev = pivot;
pivot->pNext = Begin;
}
void *lstAppendPointerOnly(laListHandle *h, void *p){
laListItemPointer *lip;
if (!h) return 0;
lip = CreateNew(laListItemPointer);
lip->p = p;
lstAppendItem(h, lip);
return lip;
}
void *lstAppendPointerSizedOnly(laListHandle *h, void *p, int size){
laListItemPointer *lip;
if (!h) return 0;
lip = calloc(1, size);
lip->p = p;
lstAppendItem(h, lip);
return lip;
}
void *lstPushPointerOnly(laListHandle *h, void *p){
laListItemPointer *lip = 0;
if (!h) return 0;
lip = CreateNew(laListItemPointer);
lip->p = p;
lstPushItem(h, lip);
return lip;
}
void *lstPushPointerSizedOnly(laListHandle *h, void *p, int size){
laListItemPointer *lip = 0;
if (!h) return 0;
lip = calloc(1, size);
lip->p = p;
lstPushItem(h, lip);
return lip;
}
void lstReverse(laListHandle* h){
laListHandle l={0}; void* i; while(i=lstPopItem(h)){ lstPushItem(&l,i); }
memcpy(h,&l,sizeof(laListHandle));
}
int lstHasPointer(laListHandle* h, void *p){
laListItemPointer *i; for (i = h->pFirst; i; i = i->pNext){
if (i->p == p){return 1;}
} return 0;
}
void *lstAppendPointer(laListHandle *h, void *p){
laListItemPointer *lip;
if (!h) return 0;
lip = memAcquireSimple(sizeof(laListItemPointer));
lip->p = p;
lstAppendItem(h, lip);
return lip;
}
void *lstAppendPointerSized(laListHandle *h, void *p, int size){
laListItemPointer *lip;
if (!h) return 0;
lip = memAcquireSimple(size);
lip->p = p;
lstAppendItem(h, lip);
return lip;
}
void *lstPushPointer(laListHandle *h, void *p){
laListItemPointer *lip = 0;
if (!h) return 0;
lip = memAcquireSimple(sizeof(laListItemPointer));
lip->p = p;
lstPushItem(h, lip);
return lip;
}
void *lstPushPointerSized(laListHandle *h, void *p, int size){
laListItemPointer *lip = 0;
if (!h) return 0;
lip = memAcquireSimple(size);
lip->p = p;
lstPushItem(h, lip);
return lip;
}
void *lstAppendPointerStatic(laListHandle *h, laStaticMemoryPool *smp, void *p){
laListItemPointer *lip;
if (!h) return 0;
lip = memStaticAcquire(smp, sizeof(laListItemPointer));
lip->p = p;
lstAppendItem(h, lip);
return lip;
}
void *lstAppendPointerStaticSized(laListHandle *h, laStaticMemoryPool *smp, void *p, int size){
laListItemPointer *lip;
if (!h) return 0;
lip = memStaticAcquire(smp, size);
lip->p = p;
lstAppendItem(h, lip);
return lip;
}
void *lstPushPointerStatic(laListHandle *h, laStaticMemoryPool *smp, void *p){
laListItemPointer *lip = 0;
if (!h) return 0;
lip = memStaticAcquire(smp, sizeof(laListItemPointer));
lip->p = p;
lstPushItem(h, lip);
return lip;
}
void *lstPushPointerStaticSized(laListHandle *h, laStaticMemoryPool *smp, void *p, int size){
laListItemPointer *lip = 0;
if (!h) return 0;
lip = memStaticAcquire(smp, size);
lip->p = p;
lstPushItem(h, lip);
return lip;
}
void *lstPopPointerOnly(laListHandle *h){
laListItemPointer *lip;
void *rev = 0;
if (!h) return 0;
lip = lstPopItem(h);
rev = lip ? lip->p : 0;
FreeMem(lip);
return rev;
}
void lstRemovePointerItemOnly(laListHandle *h, laListItemPointer *lip){
lstRemoveItem(h, lip);
FreeMem(lip);
}
void lstRemovePointerOnly(laListHandle *h, void *p){
laListItemPointer *i;
for (i = h->pFirst; i; i = i->pNext){
if (i->p == p){
lstRemovePointerItem(h, i);
break;
}
}
}
void lstClearPointerOnly(laListHandle *h){
laListItemPointer *i;
while (h && h->pFirst){
lstPopPointer(h);
}
}
void lstGeneratePointerListOnly(laListHandle *from1, laListHandle *from2, laListHandle *to){
laListItemPointer *lip = from2 ? from2->pLast : 0;
while (lip){
lstPushPointer(to, lip->p);
lip = lip->pPrev;
}
lip = from1 ? from1->pLast : 0;
while (lip){
lstPushPointer(to, lip->p);
lip = lip->pPrev;
}
}
void *lstPopPointer(laListHandle *h){
laListItemPointer *lip;
void *rev = 0;
if (!h) return 0;
lip = lstPopItem(h);
rev = lip ? lip->p : 0;
memFree(lip);
return rev;
}
void lstRemovePointerItem(laListHandle *h, laListItemPointer *lip){
lstRemoveItem(h, lip);
memFree(lip);
}
void lstRemovePointer(laListHandle *h, void *p){
laListItemPointer *i;
for (i = h->pFirst; i; i = i->pNext){
if (i->p == p){ lstRemovePointerItem(h, i); break; }
}
}
void lstRemovePointerLeave(laListHandle *h, void *p){
laListItemPointer *i;
for (i = h->pFirst; i; i = i->pNext){
if (i->p == p){ lstRemoveItem(h, i); memLeave(i); break; }
}
}
void lstClearPointer(laListHandle *h){
laListItemPointer *i;
while (h && h->pFirst){
lstPopPointer(h);
}
}
void lstGeneratePointerList(laListHandle *from1, laListHandle *from2, laListHandle *to){
laListItemPointer *lip = from2 ? from2->pLast : 0;
while (lip){
lstPushPointer(to, lip->p);
lip = lip->pPrev;
}
lip = from1 ? from1->pLast : 0;
while (lip){
lstPushPointer(to, lip->p);
lip = lip->pPrev;
}
}
void *lstAppendPointerStaticPool(laStaticMemoryPool *mph, laListHandle *h, void *p){
laListItemPointer *lip;
if (!h) return 0;
lip = memStaticAcquire(mph, sizeof(laListItemPointer));
lip->p = p;
lstAppendItem(h, lip);
return lip;
}
void *lstPopPointerLeave(laListHandle *h){
laListItemPointer *lip;
void *rev = 0;
if (!h) return 0;
lip = lstPopItem(h); memLeave(lip);
rev = lip ? lip->p : 0;
return rev;
}
void lstRemovePointerItemNoFree(laListHandle *h, laListItemPointer *lip){
lstRemoveItem(h, lip);
}
void lstCopyHandle(laListHandle *target, laListHandle *src){
target->pFirst = src->pFirst;
target->pLast = src->pLast;
};
void lstClearHandle(laListHandle *h){
h->pFirst = 0;
h->pLast = 0;
}
void lstClearPrevNext(laListItem *li){
li->pNext = 0;
li->pPrev = 0;
}
void lstMoveUp(laListHandle *h, laListItem *li){
void *pprev = li->pPrev ? ((laListItem *)li->pPrev)->pPrev : 0;
if (!h || !li) return;
if (li == h->pFirst) return;
else{
if (li == h->pLast) h->pLast = li->pPrev;
((laListItem *)li->pPrev)->pNext = li->pNext;
((laListItem *)li->pPrev)->pPrev = li;
if (li->pNext) ((laListItem *)li->pNext)->pPrev = li->pPrev;
li->pNext = li->pPrev;
li->pPrev = pprev;
if (pprev) ((laListItem *)pprev)->pNext = li;
}
if (!li->pPrev) h->pFirst = li;
}
void lstMoveDown(laListHandle *h, laListItem *li){
void *ppnext = li->pNext ? ((laListItem *)li->pNext)->pNext : 0;
if (!h || !li) return;
if (li == h->pLast) return;
else{
if (li == h->pFirst) h->pFirst = li->pNext;
((laListItem *)li->pNext)->pPrev = li->pPrev;
((laListItem *)li->pNext)->pNext = li;
if (li->pPrev) ((laListItem *)li->pPrev)->pNext = li->pNext;
li->pPrev = li->pNext;
li->pNext = ppnext;
if (ppnext) ((laListItem *)ppnext)->pPrev = li;
}
if (!li->pNext) h->pLast = li;
}
void lstForAllItemsDo(laListDoFunc func, laListHandle *hList){
laListItem *it = hList->pFirst;
for (; it; it = it->pNext){
func(it);
}
};
void lstForAllItemsDoLNRR(laListNonRecursiveDoFunc func, laListHandle *hList){
laListItem *it = hList->pFirst;
for (; it; it = it->pNext){
func(0, it, 0);
}
};
void lstForAllItemsDo_DirectFree(laListDoFunc func, laListHandle *hList){
laListItem *it;
while (it = lstPopItem(hList)){
if (func) func(it);
FreeMem(it);
}
};
void lstForAllItemsDo_arg_ptr(laListDoFuncArgp func, laListHandle *hList, void *arg){
laListItem *it = hList->pFirst;
for (; it; it = it->pNext){
func(it, arg);
};
};
void lstForAllItemsDo_NonRecursive_Root(laListHandle *FirstHandle, laListNonRecursiveDoFunc func, int bFreeItem, void *custom_data, laListCustomDataRemover remover){
laListItem *li = 0, *NextLi;
laListNonRecursiveRoot root = {0};
laListNonRecursiveItem *nrItem = CreateNew(laListNonRecursiveItem);
nrItem->bFreeList = bFreeItem;
nrItem->func = func;
nrItem->CustomData = custom_data;
nrItem->remover = remover;
lstCopyHandle(&nrItem->handle, FirstHandle);
lstAppendItem(&root.NSItems, nrItem);
while (lstHaveItemInList(&root.NSItems)){
nrItem = lstPopItem(&root.NSItems);
for (li = nrItem->handle.pFirst; li /*!=nrItem->handle.pLast*/; li = NextLi){
if (nrItem->func) nrItem->func(&root, li, custom_data);
NextLi = li->pNext;
if (nrItem->bFreeList){
laListItem *fli = li;
FreeMem(fli);
}
if (li == nrItem->handle.pLast) break;
}
if (nrItem->remover) nrItem->remover(nrItem->CustomData);
FreeMem(nrItem);
}
};
void lstAddNonRecursiveListHandle(laListNonRecursiveRoot *root, laListHandle *newHandle, laListNonRecursiveDoFunc nrFunc, int bFreeList, void *custom_data, laListCustomDataRemover remover){
laListNonRecursiveItem *nrItem = CreateNew(laListNonRecursiveItem);
nrItem->bFreeList = bFreeList;
nrItem->func = nrFunc;
nrItem->CustomData = custom_data;
nrItem->remover = remover;
lstCopyHandle(&nrItem->handle, newHandle);
lstAppendItem(&root->NSItems, nrItem);
};
void lstCopy_NonRecursive_Root(laListHandle *FromHandle, laListHandle *ToHandle, int SizeEachNode, laListNonRecursiveCopyFunc func, void *custom_data, laListCustomDataRemover remover){
laListItem *li = 0, *tli = 0;
laListNonRecursiveRoot root = {0};
laListNonRecursiveItem *nrItem = CreateNew(laListNonRecursiveItem);
laListItem *NextLi;
nrItem->CopyFunc = func;
lstCopyHandle(&nrItem->handle, FromHandle);
nrItem->ToHandle = ToHandle; //Pointer
lstClearHandle(ToHandle);
nrItem->CustomData = custom_data;
nrItem->remover = remover;
nrItem->SizeEachNode = SizeEachNode;
lstAppendItem(&root.NSItems, nrItem);
while (lstHaveItemInList(&root.NSItems)){
nrItem = lstPopItem(&root.NSItems);
if (nrItem->CopyFunc){
for (li = nrItem->handle.pFirst; li; li = li->pNext){
tli = CreateNew_Size(nrItem->SizeEachNode);
nrItem->CopyFunc(&root, li, tli, nrItem->CustomData);
lstClearPrevNext(tli);
lstAppendItem(nrItem->ToHandle, tli);
}
if (nrItem->remover) nrItem->remover(nrItem->CustomData);
}else if (nrItem->func){
for (li = nrItem->handle.pFirst; li /*!=nrItem->handle.pLast*/; li = NextLi){
if (nrItem->func) nrItem->func(&root, li, custom_data);
NextLi = li->pNext;
if (nrItem->bFreeList){
laListItem *fli = li;
FreeMem(fli);
}
if (li == nrItem->handle.pLast) break;
}
if (nrItem->remover) nrItem->remover(nrItem->CustomData);
}
FreeMem(nrItem);
}
};
void lstAddNonRecursiveListCopier(laListNonRecursiveRoot *root, laListHandle *oldHandle, laListHandle *newHandle, int sizeEach, laListNonRecursiveCopyFunc nrCpyFunc, void *custom_data, laListCustomDataRemover remover){
laListNonRecursiveItem *nrItem = CreateNew(laListNonRecursiveItem);
nrItem->CopyFunc = nrCpyFunc;
lstCopyHandle(&nrItem->handle, oldHandle);
nrItem->ToHandle = newHandle;
nrItem->CustomData = custom_data;
nrItem->remover = remover;
nrItem->SizeEachNode = sizeEach;
lstAppendItem(&root->NSItems, nrItem);
};
void *lstFindItem(void *CmpData, laCompareFunc func, laListHandle *hList){
laListItem *it;
if (!CmpData || !hList) return 0;
it = hList->pFirst;
for (; it; it = it->pNext){
if (func(it, CmpData)) return it;
};
return 0;
};
void lstCombineLists(laListHandle *dest, laListHandle *src){
if ((!dest) || (!src)) return;
if ((!dest->pFirst) && (!dest->pLast)){
dest->pFirst = src->pFirst;
dest->pLast = src->pLast;
}else{
if (src->pLast){
((laListItem *)src->pFirst)->pPrev = dest->pLast;
((laListItem *)dest->pLast)->pNext = src->pFirst;
dest->pLast = src->pLast;
}
}
src->pFirst = 0;
src->pLast = 0;
}
void lstDestroyList(laListHandle *hlst){
laListItem *li, *nextli;
for (li = hlst->pFirst; li; li = nextli){
nextli = li->pNext;
memFree(li);
}
}
void lstDestroyListA(laListHandle *hlst){
laListItem *li, *nextli;
for (li = hlst->pFirst; li; li = nextli){
nextli = li->pNext;
FreeMem(li);
}
}
void lstDestroyList_User(laListHandle *hlst, laListDoFunc func){
laListItem *it = hlst->pFirst;
for (; it; it = it->pNext){
func(it);
FreeMem(it);
}
};
void lstCopyList(laListHandle *hOldlst, laListHandle *hNewList, int SizeEachNode, laCopyListFunc func){
laListItem *li, *nextli, *newli;
for (li = hOldlst->pFirst; li; li = nextli){
newli = (laListItem *)CreateNew_Size(SizeEachNode);
func(li, newli);
lstAppendItem(hNewList, newli);
nextli = li->pNext;
}
}
void *lstReMatch(laListHandle *SearchHandle, laListHandle *CurrentHandle, void *ItemToFind){
laListItem *sl = 0, *rl = 0;
if (!SearchHandle || !CurrentHandle || !ItemToFind) return 0;
sl = SearchHandle->pFirst;
rl = CurrentHandle->pFirst;
while (sl && rl){
if (ItemToFind == sl){
return rl;
}else{
sl = sl->pNext;
rl = rl->pNext;
}
}
return 0;
}
//void* lstReMatchEx(laListHandle* SearchHandle, laListHandle* CurrentHandle, void* ItemToFind, MatcherFunc func){
// laListItem* sl = 0, *rl = 0;
//
// if (!SearchHandle || !CurrentHandle || !ItemToFind) return 0;
//
// sl = SearchHandle->pFirst; rl = CurrentHandle->pFirst;
//
// while (sl && rl){
// if (func(ItemToFind, sl)){
// return rl;
// }
// else{
// sl = sl->pNext;
// rl = rl->pNext;
// }
// }
// return 0;
//}
void lstAddElement(laListHandle *hlst, void *ext){
laElementListItem *eli = CreateNew(laElementListItem);
eli->Ext = ext;
lstAppendItem(hlst, eli);
}
void lstDestroyElementList(laListHandle *hlst){
laElementListItem *eli, *NextEli;
for (eli = hlst->pFirst; eli; eli = NextEli){
lstRemoveItem(hlst, eli);
NextEli = eli->Item.pNext;
FreeMem(eli);
}
}
uint16_t BKDRHash16bit(char* str){
unsigned int seed = 131, hash = 0;
while (*str) { hash = hash * seed + (*str++); }
return (hash & 0xFFFF);
}
void hsh65536Init(laHash65536** h){
if(!h) return; *h=calloc(1,sizeof(laHash65536));
}
void hshFree(laHash65536** h){
if(!h || !*h) return; free(*h); *h=0;
}
laListHandle* hsh65536DoHashLongPtr(laHash65536* hash, u64bit buckle) {
return &hash->Entries[(unsigned short)(buckle*13)];
}
laListHandle* hsh65536DoHashNUID(laHash65536* hash, char * NUID) {
u64bit Hash;
return &hash->Entries[BKDRHash16bit(NUID)];
}
unsigned char hsh256DoHashSTR(char *buckle){
int i, len = 0;
unsigned char rev = 0;
if (buckle) len = strlen(buckle);
for (i = 0; i < len; i++){
rev = rev * 31 + (unsigned char)buckle[i];
}
return (unsigned char)rev;
}
void hsh256InsertItemCSTR(laHash256 *hash, laListItem *li, char *buckle){
unsigned char a = hsh256DoHashSTR(buckle);
lstAppendItem(&hash->Entries[a], li);
};
void hsh256InsertItem(laHash256 *hash, laListItem *li, char buckle){
lstAppendItem(&hash->Entries[(unsigned char)buckle], li);
};
void hsh65536InsertItem(laHash65536 *hash, laListItem *li, long buckle){
lstAppendItem(&hash->Entries[(unsigned short)((buckle >> 10))], li);
//hsh256InsertItem(&hash->HashHandles[(char)((buckle >> 8) / 8)], li, (char)(buckle/8));
//printf("%d %d\n", (char)(buckle >> 5), (char)(buckle >> 6));
};
laListItem *hsh256FindItemSTR(laHash256 *hash, laCompareFunc func, char *buckle){
unsigned char hsh;
hsh = hsh256DoHashSTR(buckle);
//if(hash->Entries[hsh].pFirst == hash->Entries[hsh].pLast)
// return hash->Entries[hsh].pFirst;
laListItem* item=lstFindItem(buckle, func, &hash->Entries[hsh]);
return item;
}
//================================================================ [mem]
void* memGetHead(void* UserMem, int* HyperLevel){
laMemoryPoolPart **mpp = (laMemoryPoolPart**)(((char*)UserMem)-sizeof(void*));
if(!(*mpp)) return 0;
laMemoryPool* mp = (*mpp)->PoolRoot;
if(HyperLevel) *HyperLevel= mp->Hyperlevel;
if(mp->Hyperlevel==2) return ((char*)UserMem)-sizeof(laMemNodeHyper);
if(mp->Hyperlevel==1) return ((char*)UserMem)-sizeof(laMemNode);
if(mp->Hyperlevel==0) return ((char*)UserMem)-sizeof(laMemNode0);
return 0;
}
laListHandle* memGetUserList(void* UserMem){
int level; void* head=memGetHead(UserMem, &level);
if(level==2) return &((laMemNodeHyper*)head)->Users;
if(level==1) return &((laMemNode*)head)->Users;
return 0;
}
laMemoryPool *memInitPool(int NodeSize, int HyperLevel){
if (!NodeSize) return 0;
laMemoryPool *mph = calloc(1, sizeof(laMemoryPool));
mph->NodeSize = NodeSize;
mph->NextCount = 1;
mph->Hyperlevel = HyperLevel;
u8bit Buckle = NodeSize;
lstAppendItem(&MAIN.GlobalMemPool.Entries[Buckle], mph);
return mph;
}
laMemoryPoolPart *memNewPoolPart(laMemoryPool *mph){
if (!mph->NodeSize) return 0;
int MemNodeSize=(mph->Hyperlevel==0)?sizeof(laMemNode0):((mph->Hyperlevel==1)?sizeof(laMemNode):sizeof(laMemNodeHyper));
int PoolRefOffset=MemNodeSize-sizeof(void*);
int RealNodeSize = mph->NodeSize + MemNodeSize;
int NodeCount = mph->NextCount;
int TotalSize = sizeof(laMemoryPoolPart) + NodeCount * RealNodeSize;
laMemoryPoolPart *mp = calloc(1, TotalSize);
void *BeginMem = ((BYTE *)mp) + sizeof(laMemoryPoolPart);
mp->PoolRoot = mph;
mp->FreeMemoryNodes.pFirst = mp->FreeMemoryNodes.pLast = 0;
for (int i = 0; i < NodeCount; i++){
void* mpn = ((BYTE *)BeginMem) + RealNodeSize * i;
void** ref = ((BYTE *)mpn) + PoolRefOffset;
(*ref)=mp;
lstAppendItem(&mp->FreeMemoryNodes, mpn);
}
lstPushItem(&mph->Pools, mp);
return mp;
}
void *memAcquireH(laMemoryPool *Handle){
laMemoryPoolPart *mp = Handle->Pools.pFirst;
laMemNode *mpn;
if (!mp || !mp->FreeMemoryNodes.pFirst){
mp = memNewPoolPart(Handle);
}
if (!mp) return 0;
mpn = mp->FreeMemoryNodes.pFirst;
lstRemoveItem(&mp->FreeMemoryNodes, mpn);
mp->UsedCount++;
//lstAppendItem(&mp->MemoryNodes, mpn);
return mpn;
}
void *memAcquire_(int Size, int Hyper){
laMemoryPool *mp;
u8bit Buckle = Size;
laSpinLock(&MAIN.MemLock);
mp = MAIN.GlobalMemPool.Entries[Buckle].pFirst;
while (mp && (mp->NodeSize != Size || mp->Hyperlevel!=Hyper))
mp = mp->Item.pNext;
if (!mp) mp = memInitPool(Size, Hyper);
void* ret=memAcquireH(mp);
laSpinUnlock(&MAIN.MemLock);
return ret;
}
void *memAcquireSimple(int Size){
void *mpn = memAcquire_(Size, 0);
return ((char*)mpn)+sizeof(laMemNode0);
}
void *memAcquire(int Size){
laMemNode *mpn = memAcquire_(Size, 1);
void* mem = ((char*)mpn)+sizeof(laMemNode);
return mem;
}
void *memAcquireHyperNoAppend(int Size){
laMemNodeHyper *mpn = memAcquire_(Size, 2);
void* mem = ((char*)mpn)+sizeof(laMemNodeHyper);
memMakeHyperData(mpn);
return mem;
}
void *memAcquireHyper(int Size){
laMemNodeHyper *mpn = memAcquire_(Size, 2);
void* mem = ((char*)mpn)+sizeof(laMemNodeHyper);
memMakeHyperData(mpn);
laListHandle* l=hsh65536DoHashNUID(&MAIN.DBInst2,mpn->NUID.String);
lstAppendItem(l,mpn);
return mem;
}
void memFree(void *Data){
if (!Data) return;
int level; void* head = memGetHead(Data, &level);
laMemoryPoolPart *mp;
if(level==2) { mp = ((laMemNodeHyper*)head)->InPool; laDataBlockNoLongerExists(Data,&((laMemNodeHyper*)head)->Users);
laListHandle* l=hsh65536DoHashNUID(&MAIN.DBInst2,((laMemNodeHyper*)head)->NUID.String); lstRemoveItem(l,head);}
if(level==1) { mp = ((laMemNode*)head)->InPool; laDataBlockNoLongerExists(Data,&((laMemNode*)head)->Users); }
if(level==0) { mp = ((laMemNode0*)head)->InPool; }
laMemoryPool *mph = mp->PoolRoot;
laSpinLock(&MAIN.MemLock);
//lstRemoveItem(&mp->MemoryNodes, head);
mp->UsedCount--;
void* head_except_item = ((char*)head)+sizeof(laListItem);
//memset(head_except_item, 0, ((level==2)?sizeof(laMemNodeHyper):((level==1)?sizeof(laMemNode):sizeof(laMemNode0)))+mph->NodeSize-sizeof(laListItem));
lstAppendItem(&mp->FreeMemoryNodes, head);
memset(Data, 0, mph->NodeSize);
MAIN.ByteCount -= mph->NodeSize;
if (!mp->UsedCount){
lstRemoveItem(&mph->Pools, mp);
FreeMem(mp);
}
laSpinUnlock(&MAIN.MemLock);
//if (!mph->Pools.pFirst) {
// mph->CountPerPool = 0;
// mph->NodeSize = 0;
//}
}
void memDestroyPool(laMemoryPool *mph){
laMemoryPool *mp;
while ((mp = lstPopItem(&mph->Pools))){
FreeMem(mp);
}
FreeMem(mph);
}
// Leave memory in an temporary place and if when push difference these are still not acquired, free them.
void memLeave(void *Data){
laListHandle* l=hsh65536DoHashLongPtr(MAIN.DBInstMemLeft,Data); lstAppendPointer(l,Data);
}
void memTake(void *Data){
laListHandle* l=hsh65536DoHashLongPtr(MAIN.DBInstMemLeft,Data); lstRemovePointer(l,Data);
}
void memFreeRemainingLeftNodes(){
laListHandle* l; void* m;
for(int i=0;i<65536;i++){
l=&MAIN.DBInstMemLeft->Entries[i]; while(m=lstPopPointer(l)){ memFree(m);
#ifdef DEBUG
printf("left freed %x\n",m);
#endif
}
}
}
void memNoLonger(){
for(int i=0;i<256;i++){
laMemoryPool* mp; while(mp=lstPopItem(&MAIN.GlobalMemPool.Entries[i])){ memDestroyPool(mp); }
}
}
laStaticMemoryPoolNode *memNewStaticPool(laStaticMemoryPool *smp){
laStaticMemoryPoolNode *smpn = calloc(1, LA_MEMORY_POOL_128MB);
smpn->UsedByte = sizeof(laStaticMemoryPoolNode);
lstPushItem(&smp->Pools, smpn);
return smpn;
}
void *memStaticAcquire(laStaticMemoryPool *smp, int size){
laStaticMemoryPoolNode *smpn = smp->Pools.pFirst;
void *ret;
if (!smpn || (smpn->UsedByte + size) > LA_MEMORY_POOL_128MB) smpn = memNewStaticPool(smp);
ret = ((BYTE *)smpn) + smpn->UsedByte;
smpn->UsedByte += size;
return ret;
}
void *memStaticAcquireThread(laStaticMemoryPool *smp, int size){
laStaticMemoryPoolNode *smpn = smp->Pools.pFirst;
void *ret;
//laSpinLock(&smp->csMem);
if (!smpn || (smpn->UsedByte + size) > LA_MEMORY_POOL_128MB) smpn = memNewStaticPool(smp);
ret = ((BYTE *)smpn) + smpn->UsedByte;
smpn->UsedByte += size;
//laSpinUnlock(&smp->csMem);
return ret;
}
void *memStaticDestroy(laStaticMemoryPool *smp){
laStaticMemoryPoolNode *smpn;
void *ret;
while (smpn = lstPopItem(&smp->Pools)){
FreeMem(smpn);
}
smp->EachSize = 0;
return ret;
}
void la_ReferencedBlockDeleted(void* This, laItemUserLinker* iul){
void** user=iul->Pointer.p; if(*user==This){ (*user)=0; } laStopUsingDataBlock(iul->Additional, 0, This); // <<< should always remove.
}
void la_ReferrerDeleted(void* This, laItemUserLinker* iul){
void* instance=iul->Pointer.p; if(instance!=This){ laStopUsingDataBlock(instance, 0, This); }
}
void memAssignRef(void* This, void** ptr, void* instance){
laItemUserLinker* iul;
if((!This)||(!ptr)) return;
if(instance){
laItemUserLinker*iul=laUseDataBlock(instance, 0, 0, ptr, la_ReferencedBlockDeleted, 0); if(iul){iul->Additional=This;}
laUseDataBlock(This, 0, 0, instance, la_ReferrerDeleted, 0);
}else{
laStopUsingDataBlock((*ptr), 0, This);
laStopUsingDataBlock(This, 0, (*ptr));
}
(*ptr)=instance;
}
void memAssignRefSafe(laSubProp* sp, void* This, void** ptr, void* instance){
laPropContainer* pc=sp?la_EnsureSubTarget(sp,instance):0;
if(pc&&!pc->OtherAlloc) memAssignRef(This,ptr,instance);
else (*ptr)=instance;
}
//=======================================================================[str]
char *strGetNextString(char **pivot, char *NextMark){
int lenth = 0;
char *countP = *pivot;
char *result = 0;
int FloatArg = 0;
int i,advance;
if (**pivot == U'\0') return 0;
if (*NextMark == U'~') FloatArg = 1;
// container@identifier=window container#window contianer%
int UC=1;
while (!lenth){
for (countP; *countP != U'.' && *(*pivot) != U'\0' && UC && *countP && *countP != U'@' && *countP != U'=' && *countP != U'#' && *countP != U'$';){
if((*countP)=='\\'){
countP++; lenth++; }
UC = laToUnicode(countP, &advance);
lenth+=advance;
countP+=advance;
}
if (lenth || (*countP) == 0) break;
(*pivot)++; countP++;
}
*NextMark = (*pivot)[lenth];
if (!(*NextMark)) *NextMark = U'.';
if (lenth){
result = CreateNewBuffer(char, lenth + 1);
int pi=0; for (i = 0; i < lenth; i++){
if((*pivot)[i]=='\\'){ continue; }
result[pi] = (*pivot)[i]; pi++;
}
result[pi] = U'\0';
if ((*pivot)[lenth] == U'\0') *pivot = &((*pivot)[lenth]);
else
(*pivot) += lenth + 1;
return result;
}else{
return 0;
}
};
int strGetStringTerminateBy(char *content, char terminator, char *Out){
int Ofst = 0;
int Skip = 0;
int i = 0, advance;
if ((!content) || (*content == U'\0')) return 0;
int UC;
for (Ofst; content[Ofst] != terminator && content[Ofst] != U'\0'; ){
UC = laToUnicode(&content[Ofst], &advance);
for(int a=0;a= 'a' && *p <= 'z') *p += 'A' - 'a';
p++;
}
}
void strToLower(char *Str){
char *p = Str; if (!p) return;
while (*p){
if (*p >= 'A' && *p <= 'Z') *p -= 'A' - 'a';
p++;
}
}
int tolowerGuarded(int a) {
if (a >= 'A' && a <= 'Z') a -= 'A' - 'a';
return a;
}
laStringSplitor *strSplitPath(char *path,char terminator){
laStringPart *sp;
laStringSplitor *ss;
char *pivot = path;
char *temp_result;
char Type = terminator?terminator:'.';
char NextType = '.';
if (!path || !path[0]) return 0;
ss = memAcquireSimple(sizeof(laStringSplitor));
while (temp_result = strGetNextString(&pivot, &NextType)){
if (*temp_result != U'\0'){
sp = memAcquireSimple(sizeof(laStringPart));
sp->Content = temp_result;
lstAppendItem(&ss->parts, sp);
ss->NumberParts += 1;
if (NextType == U'$') sp->Type = U'$';
else
sp->Type = Type;
if (sp->Type == U'='){
if (sp->Content[0] >= U'0' && sp->Content[0] <= 9){
sscanf(sp->Content, "%d", &sp->IntValue);
}
}
if (NextType == U'$') NextType = U'.';
Type = NextType;
}
}
if (ss->NumberParts == 0){
strDestroyStringSplitor(&ss);
return 0;
}
return ss;
};
void DF_ClearStingParts(laStringPart *sp){
FreeMem(sp->Content);
};
int strDestroyStringSplitor(laStringSplitor **ss){
if (!(*ss)) return 0;
lstForAllItemsDo(DF_ClearStingParts, &(*ss)->parts);
lstDestroyList(&(*ss)->parts);
memFree(*ss);
*ss = 0;
return 1;
}
char * strSub(char *input, char *substring, char *replace){
int number_of_matches = 0;
size_t substring_size = strlen(substring), replace_size = strlen(replace), buffer_size;
char *buffer, *bp, *ip;
if (substring_size){
ip = strstr(input, substring);
while (ip != NULL){
number_of_matches++;
ip = strstr(ip+substring_size, substring);
}
}
else number_of_matches = strlen (input) + 1;
buffer_size = strlen(input) + number_of_matches*(replace_size - substring_size) + 1;
if ((buffer = ((char *) malloc(buffer_size))) == NULL){
return NULL;
}
bp = buffer;
ip = strstr(input, substring);
while ((ip != NULL) && (*input != '\0')){
if (ip == input){
memcpy (bp, replace, replace_size+1);
bp += replace_size;
if (substring_size)input += substring_size;
else*(bp++) = *(input++);
ip = strstr(input, substring);
}
else while (input != ip) *(bp++) = *(input++);
}
if (substring_size)strcpy (bp, input);
else memcpy (bp, replace, replace_size+1);
return buffer;
}
char buff[128]={0};
int strMakeInstructions(laStringSplitor **result, char *content){
laStringPart *sp;
laStringSplitor *ss = *result;
char *pivot = content;
unsigned char *temp_result;
if (!content || !content[0]) return 0;
if (!ss) ss = *result = memAcquireSimple(sizeof(laStringSplitor));
while (temp_result = strGetNewStringTerminateBy_PivotOver(pivot, '=', &pivot, 0)){
if (*temp_result != U'\0'){
sp = memAcquireSimple(sizeof(laStringPart));
sp->Content = temp_result;
lstAppendItem(&ss->parts, sp);
ss->NumberParts += 1;
}
temp_result = strGetNewStringTerminateBy_PivotOver(pivot, ';', &pivot, 0);
if (!temp_result) break;
if (*temp_result != U'\0'){
sp = memAcquireSimple(sizeof(laStringPart));
sp->Content = temp_result;
lstAppendItem(&ss->parts, sp);
ss->NumberParts += 1;
if (temp_result[0] >= U'0' && temp_result[0] <= U'9' || temp_result[0]>=128){
sscanf(temp_result, "%d", &sp->IntValue);
sscanf(temp_result, "%lf", &sp->FloatValue);
}
}
}
if (ss->NumberParts == 0){
strDestroyStringSplitor(&ss);
return 0;
}
return 1;
}
laStringPart *strGetArgument(laStringSplitor *ss, char *content){
laStringPart *sp;
if (!ss) return 0;
for (sp = ss->parts.pFirst; sp; sp = sp->Item.pNext ? ((laListItem *)sp->Item.pNext)->pNext : 0){
if (strSame(content, sp->Content)) return sp->Item.pNext;
}
return 0;
}
char *strGetArgumentString(laStringSplitor *ss, char *content){
laStringPart *sp;
if (!ss) return 0;
for (sp = ss->parts.pFirst; sp; sp = sp->Item.pNext ? ((laListItem *)sp->Item.pNext)->pNext : 0){
if (strSame(content, sp->Content)) return sp->Item.pNext ? ((laStringPart *)sp->Item.pNext)->Content : 0;
}
return 0;
}
int strArgumentMatch(laStringSplitor *ss, char *id, char *value){
laStringPart *sp;
if (!ss) return 0;
for (sp = ss->parts.pFirst; sp; sp = sp->Item.pNext ? ((laListItem *)sp->Item.pNext)->pNext : 0){
if (strSame(id, sp->Content)) return (strSame(((laStringPart *)sp->Item.pNext)->Content, value));
}
return 0;
}
int strGetIntSimple(char *content){
int a;
sscanf(content, "%d", &a);
return a;
}
real strGetFloatSimple(char *content){
real a;
sscanf(content, "%lf", &a);
return a;
}
void strConvInt_CString(int src, char *dest, int lenth){
sprintf(dest, "%d", src);
};
void strConvFloat_CString(real src, char *dest, int lenth){
sprintf(dest, "%lf", src);
};
void strCopyFull(char *dest, char *src){
if (src && dest) strcpy(dest, src);
}
void strCopySized(char *dest, int LenthLim, char *src){
if (src && dest) strcpy(dest, src);
}
void strPrintFloatAfter(char *dest, int LenthLim, int bits, real data){
char temp[64]={0};
sprintf(temp, "%.*lf", bits, data);
strcat(dest, temp);
}
void strPrintIntAfter(char *dest, int LenthLim, int data){
char temp[64]={0};
sprintf(&temp[0], "%d", data);
strcat(dest, temp);
}
void strEscapePath(char* OutCanBeSame, char* path){
char t[256]={0}; int ti=0;
for(int i=0;path[i];i++,ti++){
if(path[i]=='.'){ t[ti]='\\'; ti++; }
t[ti]=path[i];
}
strcpy(OutCanBeSame,t);
}
int strSame(char *src, char *dest){
return (src && dest && !strcmp(src, dest));
}
void strSafeDestroy(laSafeString **ss){
if (!*ss) return; lstRemoveItem(&SSC.SafeStrings, *ss);
if((*ss)->Ptr) memFree((*ss)->Ptr);
memFree(*ss); *ss=0;
}
void strSafeSet(laSafeString **ss, char *Content){
int len;
if (!Content||!Content[0]){ strSafeDestroy(ss); return; }
len = strlen(Content);
if (len < 1) return;
if (*ss){
char* mem=memAcquireSimple(sizeof(char)*(len+1));
strcpy(mem, Content);
memFree((*ss)->Ptr);
(*ss)->Ptr=mem;
return;
}
(*ss) = memAcquireSimple(sizeof(laSafeString));
(*ss)->Ptr = memAcquireSimple(sizeof(char)*(len+1));
strcpy((*ss)->Ptr, Content);
lstAppendItem(&SSC.SafeStrings, *ss);
}
void strSafeAppend(laSafeString **ss, char *Content){
if(!ss || !(*ss) || !Content){ strSafeSet(ss, Content); return; }
int OrigLen=strlen((*ss)->Ptr), ContentLen=strlen(Content);
char* mem=memAcquireSimple(sizeof(char)*(OrigLen+ContentLen+1));
memcpy(mem, (*ss)->Ptr, sizeof(char)*OrigLen);
memcpy(mem+sizeof(char)*OrigLen, Content, sizeof(char)*ContentLen);
mem[OrigLen+ContentLen]=0;
memFree((*ss)->Ptr);
(*ss)->Ptr=mem;
}
void strSafePrint(laSafeString **ss, char *Format, ...){
char content[1024]; va_list va; va_start(va, Format); vsprintf(content, Format, va); va_end(va);
strSafeAppend(ss,content);
}
void strSafePrintV(laSafeString **ss, char *Format, va_list args){
char content[1024]; va_list va; vsprintf(content, Format, args);
strSafeAppend(ss,content);
}
void strSafeDump(){
laSafeString*ss;
while(ss=lstPopItem(&SSC.SafeStrings)){
//if(ss->Ptr) printf("[String not freed] \"%s\"\n", ss->Ptr);
}
}
void strBeginEdit(laStringEdit **se, char *FullStr){
char *p = FullStr;
char buf[1024];
laStringEdit *nse = CreateNew(laStringEdit);
if(*se){ memcpy(nse,*se,sizeof(laStringEdit)); nse->Lines.pFirst=nse->Lines.pLast=0; nse->TotalLines=0; }
strEndEdit(se, 1);
nse->_BeginLine = -1; nse->_BeginBefore = -1;
if (FullStr && FullStr[0]){
while ((*p)){
laStringLine *sl = memAcquireSimple(sizeof(laStringLine));
p += strGetStringTerminateBy(p, '\n', buf);
strToUnicode(sl->Buf, buf);
lstAppendItem(&nse->Lines, sl); nse->TotalLines++;
if(*p){ p+=1; }
}
}
if (!nse->Lines.pFirst){
laStringLine *sl = memAcquireSimple(sizeof(laStringLine));
lstAppendItem(&nse->Lines, sl); nse->TotalLines=1;
}
laStringLine *sl = strGetCursorLine(nse, 0); int len=strlen(sl->Buf);
if(lenCursorBefore){ nse->CursorBefore=len; }
*se=nse;
}
char* strGetEditString(laStringEdit *se, int SelectionOnly){
if(!se) return 0; char* result=0; int next=0, max=0, len=0;
arrEnsureLength(&result, 0, &max, sizeof(char)); int NextChar=0;
int Line=0, starti=0, endat=INT_MAX;
for(laStringLine* sl=se->Lines.pFirst;sl;sl=sl->Item.pNext,Line++){
starti=0;
if(SelectionOnly && LineBeginLine){ continue; }
if(SelectionOnly && Line==se->BeginLine){ starti=se->BeginBefore; }
int tlen=strlenU(&sl->Buf[starti]); int Extra=sl->Item.pNext?2:1;
arrEnsureLength(&result, (len+tlen)*4+Extra, &max, sizeof(char));
if(SelectionOnly && Line==se->EndLine){ endat=NextChar+se->EndBefore-starti; }
NextChar+=strToUTF8Lim(&result[NextChar], &sl->Buf[starti], endat); len+=tlen;
if(Extra==2){ result[NextChar]='\n'; NextChar+=1; }
if(SelectionOnly && Line==se->EndLine){ break; }
}
return result;
}
char* strEndEdit(laStringEdit **se, int FreeString){
char *p=0; laStringLine *sl, *NextSl;
if (!se || !(*se)) return 0;
p=strGetEditString(*se, 0);
while (sl=lstPopItem(&(*se)->Lines)){ memFree(sl); }
FreeMem(*se); *se=0;
if(FreeString && p){ free(p); p=0; }
return p;
}
void strSetEditViewRange(laStringEdit* se, int Lines, int Cols){
se->ViewHeight = Lines; se->ViewWidth = Cols;
}
void strEnsureCursorVisible(laStringEdit* se){
if(!se->ViewHeight || !se->ViewWidth || se->CursorLine<0 || se->CursorBefore<0 ){return;}
if(se->CursorLine>se->ViewHeight+se->ViewStartLine-1){ se->ViewStartLine=se->CursorLine-se->ViewHeight+1; }
if(se->CursorLineViewStartLine){ se->ViewStartLine=se->CursorLine; }
if(se->CursorBefore>se->ViewStartCol+se->ViewWidth-1){ se->ViewStartCol=se->CursorBefore-se->ViewWidth+1; }
if(se->CursorBeforeViewStartCol){ se->ViewStartCol=se->CursorBefore; }
}
void strRemoveLine(laStringEdit *se, laStringLine *sl){
lstRemoveItem(&se->Lines, sl);
memFree(sl); se->TotalLines--;
}
void strRemoveLineI(laStringEdit *se, int LineIndex){
int i = 0;
laStringLine *sl = se->Lines.pFirst, *NextSl;
while (sl){
NextSl = sl->Item.pNext;
if (i == LineIndex){ strRemoveLine(se, sl); break; }
i++;
sl = NextSl;
}
}
void strSetCursor(laStringEdit *se, int LineIndex, int BeforeIndex){
int maxbefore;
if (!se) return;
if(LineIndex<0){LineIndex=0;}
se->CursorLine = LineIndex;
maxbefore = strlenU(strGetCursorLine(se, &se->CursorLine)->Buf);
BeforeIndex = BeforeIndex < 0 ? 0 : BeforeIndex > maxbefore ? maxbefore : BeforeIndex;
se->CursorBefore = BeforeIndex;
se->BeginLine = -1;
se->BeginBefore = -1;
se->EndLine = -1;
se->EndBefore = -1;
strEnsureCursorVisible(se);
}
void strMoveCursor(laStringEdit *se, int Left, int Select){
int maxbefore;
int BeforeIndex;
int width = 1;
laStringLine *sl;
if (!se) return;
if(Select){ strLazySelect(se); } else { strCancelSelect(se); }
sl = strGetCursorLine(se, 0);
maxbefore = strlenU(sl->Buf);
BeforeIndex = se->CursorBefore - (Left ? 1 : -1);
if(BeforeIndex<0){
if(se->CursorLine>0) strSetCursor(se, se->CursorLine-1, INT_MAX);
}elif(BeforeIndex>maxbefore && se->CursorLineTotalLines-1){
if(se->CursorLine>0) strSetCursor(se, se->CursorLine+1, 0);
}else{
se->CursorBefore = BeforeIndex>=maxbefore?maxbefore:BeforeIndex;
}
se->CursorPreferBefore = se->CursorBefore;
se->BeginLine = -1;
se->BeginBefore = -1;
se->EndLine = -1;
se->EndBefore = -1;
if(Select){ strEndSelect(se); }
strEnsureCursorVisible(se);
}
void strMoveCursorLine(laStringEdit *se, int Up, int Select){
int Line, maxbefore, LastIndex=-1;
laStringLine *sl;
if (!se) return;
if(Select){ strLazySelect(se); } else { strCancelSelect(se); }
Line=se->CursorLine - (Up? 1:-1);
if(Line<0) {Line=0;}
se->CursorLine = Line;
sl = strGetCursorLine(se, &LastIndex);
if(LastIndex>=0){ se->CursorLine = LastIndex; se->CursorPreferBefore=10000; }
maxbefore = strlenU(sl->Buf);
se->CursorBefore = se->CursorPreferBefore;
if(se->CursorBefore>maxbefore){ se->CursorBefore = maxbefore; }
if(LastIndex>=0){se->CursorPreferBefore=se->CursorBefore;}
if(Select){ strEndSelect(se); }
strEnsureCursorVisible(se);
}
int strHasSelection(laStringEdit* se){
return se->BeginBefore!=se->EndBefore||se->BeginLine!=se->EndLine;
}
void strCancelSelect(laStringEdit *se){
if (!se) return;
se->_BeginLine = -1;
se->_BeginBefore = -1;
se->BeginLine = -1;
se->EndLine = -1;
se->BeginBefore = -1;
se->EndBefore = -1;
}
void strLazySelect(laStringEdit *se){
if (!se || se->_BeginLine>=0) return;
se->_BeginLine = TNS_MAX2(se->CursorLine,0);
se->_BeginBefore = se->CursorBefore;
}
void strEndSelect(laStringEdit *se){
if (!se) return;
se->_EndLine = se->CursorLine;
se->_EndBefore = se->CursorBefore;
se->BeginLine = se->_BeginLine;
se->EndLine = se->_EndLine;
se->BeginBefore = se->_BeginBefore;
se->EndBefore = se->_EndBefore;
if(se->BeginLine>se->EndLine || (se->BeginLine==se->EndLine && se->BeginBefore>se->EndBefore))
{ LA_SWAP(int,se->BeginLine,se->EndLine); LA_SWAP(int,se->BeginBefore,se->EndBefore); }
}
void strSelectLineAll(laStringEdit *se){
if (!se) return;
laStringLine *sl;
int len;
if (se->CursorLine == -1) sl = strGetBeginLine(se);
else
sl = strGetCursorLine(se, 0);
len = strlenU(sl->Buf);
se->EndBefore = len; se->EndLine=0;
se->BeginBefore = 0; se->BeginLine=0;
se->CursorBefore = len;
se->CursorLine = 0;
}
void strDeselectAll(laStringEdit *se){
if (!se) return;
laStringLine *sl;
int len;
if (se->CursorLine == -1) sl = strGetBeginLine(se);
else
sl = strGetCursorLine(se, 0);
len = strlenU(sl->Buf);
se->EndBefore = -1;
se->BeginBefore = -1;
se->BeginLine = -1;
se->EndLine = -1;
se->CursorBefore = len;
se->CursorLine = -1;
}
void strPanFoward(uint32_t *str, int Before, int Offset){
int len = strlenU(str);
int i = len + 1;
for (i; i >= Before; i--){
str[i + Offset] = str[i];
}
}
void strSquishBackward(uint32_t *str, int Before, int EndBefore){
int len = strlenU(str);
int i = Before;
int Offset = Before - EndBefore;
if (Before <= 0) return;
for (i; i <= len; i++){
str[i - Offset] = str[i];
}
}
void strClearSelection(laStringEdit *se){
//if (se->EndLine == -1) return;
if (se->BeginLine != se->EndLine){
int i = 0; int RemovedLines=0;
laStringLine *sl = se->Lines.pFirst, *NextSl;
while (sl){
NextSl = sl->Item.pNext;
if (i == se->BeginLine){
sl->Buf[se->BeginBefore] = U'\0';
}else if (i > se->BeginLine && i < se->EndLine){
strRemoveLine(se, sl); RemovedLines++;
}else if (i == se->EndLine){
strSquishBackward(sl->Buf, se->EndBefore, 0);
se->CursorLine = i-RemovedLines;
se->CursorBefore = 0;
se->BeginLine = -1;
se->BeginBefore = -1;
se->EndLine = -1;
se->EndBefore = -1;
strBackspace(se);
}
if (i > se->EndLine) break;
i++;
sl = NextSl;
}
}else{
int i = 0;
laStringLine *sl = se->Lines.pFirst, *NextSl;
while (sl){
NextSl = sl->Item.pNext;
if (i == se->EndLine) {
strSquishBackward(sl->Buf, se->EndBefore, se->BeginBefore);
se->CursorLine = i;
se->CursorBefore = se->BeginBefore;
se->BeginLine = -1;
se->BeginBefore = -1;
se->EndLine = -1;
se->EndBefore = -1;
break;
}
i++; sl = NextSl;
}
}
strEnsureCursorVisible(se);
}
laStringLine *strGetCursorLine(laStringEdit *se, int* ReturnIndexIfLast){
if (!se || se->CursorBefore <= -1) return se->Lines.pFirst;
int i = 0;
laStringLine *sl = se->Lines.pFirst, *NextSl;
while (sl){
NextSl = sl->Item.pNext;
if (i == se->CursorLine){
return sl;
}
i++;
sl = NextSl;
}
if(ReturnIndexIfLast){ *ReturnIndexIfLast=i-1;}
return se->Lines.pLast;
}
laStringLine *strGetBeginLine(laStringEdit *se){
if (!se || se->BeginLine <= -1) return se->Lines.pFirst;
int i = 0;
laStringLine *sl = se->Lines.pFirst, *NextSl;
while (sl){
NextSl = sl->Item.pNext;
if (i == se->BeginLine){
return sl;
}
i++;
sl = NextSl;
}
return se->Lines.pFirst;
}
void strInsertChar(laStringEdit *se, uint32_t a){
laStringLine *sl;
strClearSelection(se);
sl = strGetCursorLine(se, 0);
if(a==U'\n'){
laStringLine* nl=memAcquireSimple(sizeof(laStringLine));
if(sl->Buf[se->CursorBefore]!=U'\0') strcpyU(nl->Buf, &sl->Buf[se->CursorBefore]);
sl->Buf[se->CursorBefore]=U'\0';
se->CursorLine++; se->CursorBefore=0;
lstInsertItemAfter(&se->Lines, nl, sl); se->TotalLines++;
}else{
strPanFoward(sl->Buf, se->CursorBefore, 1);
sl->Buf[se->CursorBefore] = a;
se->CursorBefore += 1;
}
se->CursorPreferBefore = se->CursorBefore;
strEnsureCursorVisible(se);
}
void strBackspace(laStringEdit *se){
laStringLine *sl;
int width = 1;
if (se->CursorBefore == -1){
strClearSelection(se);
}else{
laStringLine *sl;
sl = strGetCursorLine(se, 0);
if (se->CursorBefore > 1 && sl->Buf[se->CursorBefore - 2] < 0) width = 2;
strSquishBackward(sl->Buf, se->CursorBefore, se->CursorBefore - width);
se->CursorBefore -= width;
if (se->CursorBefore <= -1){
if(sl->Item.pPrev){
laStringLine* ol=sl->Item.pPrev;
se->CursorBefore = strlenU(ol->Buf);
se->CursorLine--;
strcatU(ol->Buf, sl->Buf);
strRemoveLine(se, sl);
}
else {se->CursorBefore = 0;}
}
}
se->CursorPreferBefore = se->CursorBefore;
strEnsureCursorVisible(se);
}
void strMoveView(laStringEdit *se, int DownLines, int RightCharacters){
se->ViewStartLine+=DownLines;
se->ViewStartCol+=RightCharacters;
if(se->ViewStartLine>=se->TotalLines-1) se->ViewStartLine=se->TotalLines-1;
if(se->ViewStartLine<0) se->ViewStartLine=0;
if(se->ViewStartCol<0) se->ViewStartCol=0;
}
int laCopyFile(char *to, char *from){
#ifdef _WIN32
if(CopyFile(from, to, 0)) return 1; return 0;
#endif
#ifdef LA_LINUX
int fd_to, fd_from; char buf[4096];
ssize_t nread; int saved_errno;
fd_from = open(from, O_RDONLY); if (fd_from < 0) return 0;
fd_to = open(to, O_WRONLY|O_CREAT /* |O_EXCL */, 0666); if (fd_to < 0) goto out_error;
while (nread=read(fd_from,buf,sizeof(buf)), nread>0) {
char *out_ptr = buf; ssize_t nwritten;
do { nwritten = write(fd_to, out_ptr, nread);
if (nwritten >= 0){ nread -= nwritten; out_ptr += nwritten;}
else if (errno != EINTR){ goto out_error; }
}while (nread > 0);
}
if (nread == 0){
if (close(fd_to)<0){ fd_to = -1; goto out_error;}
close(fd_from);
return 1;
}
out_error:
saved_errno = errno;
close(fd_from); if (fd_to >= 0) close(fd_to);
errno = saved_errno;
return 0;
#endif //linux
}
int laEnsureDir(const char *dir) {
#ifdef LA_LINUX
char tmp[1024]; char *p = NULL; size_t len;
snprintf(tmp, sizeof(tmp),"%s",dir);
len = strlen(tmp);
if (tmp[len - 1] == '/') tmp[len - 1] = 0;
for (p = tmp + 1; *p; p++){
if (*p == '/') { *p = 0;
mkdir(tmp, S_IRWXU | S_IRWXG | S_IRWXO);
*p = '/';
}
}
mkdir(tmp, S_IRWXU | S_IRWXG | S_IRWXO);
struct stat statbuf;
if(stat(dir, &statbuf) != 0){ return 0; }
return S_ISDIR(statbuf.st_mode);
#endif
}
//======================================================[ translation ]
void transNewLanguage(const char *LanguageID){
laTranslationNode *tn = memAcquire(sizeof(laTranslationNode));
strSafeSet(&tn->LanguageName, LanguageID);
lstAppendItem(&MAIN.Translation.Languages, tn);
MAIN.Translation.CurrentLanguage = tn;
}
void transSetLanguage(const char *LanguageID){
laTranslationNode *tn;
if (!LanguageID){
MAIN.Translation.CurrentLanguage = 0;
return;
}
for (tn = MAIN.Translation.Languages.pFirst; tn; tn = tn->Item.pNext){
if (!strcmp(SSTR(tn->LanguageName), LanguageID)){
MAIN.Translation.CurrentLanguage = tn; return;
}
}
transNewLanguage(LanguageID);
}
void transDumpMissMatchRecord(const char *filename){
laTranslationMatch *tm;
laListHandle *lst;
int i;
FILE *f = fopen(filename, "w"); if (!f) return;
for (i = 0; i < 256; i++){
lst = &MAIN.Translation.MisMatches.Entries[i];
for (tm = lst->pFirst; tm; tm = tm->Item.pNext){ if(tm->Target) fprintf(f, "%s | \n", tm->Target); }
}
fclose(f);
}
int IsThisTranslationMatch(laTranslationMatch *tm, char *p){
return (tm->Target && (!strcmp(tm->Target, p)));
}
void transNewEntry(const char *Target, const char *replacement){
laTranslationMatch *tm = memAcquireSimple(sizeof(laTranslationMatch));
tm->Target = Target; tm->Replacement = replacement;
hsh256InsertItemCSTR(&MAIN.Translation.CurrentLanguage->Matches, tm, Target);
}
void transNewMissEntry(const char *Target){
if (!hsh256FindItemSTR(&MAIN.Translation.MisMatches, IsThisTranslationMatch, Target)){
laTranslationMatch *tm = memAcquireSimple(sizeof(laTranslationMatch));
int len=strlen(Target); tm->Target=memAcquireSimple(len*sizeof(char)+1);
strcpy(tm->Target,Target);
hsh256InsertItemCSTR(&MAIN.Translation.MisMatches, tm, Target);
}
}
char *transLate(char *Target){
if (!MAIN.Translation.CurrentLanguage || !MAIN.Translation.EnableTranslation || !Target || !Target[0]) return Target;
laTranslationMatch *tm = hsh256FindItemSTR(&MAIN.Translation.CurrentLanguage->Matches, IsThisTranslationMatch, Target);
if (!tm){ transNewMissEntry(Target); return Target; }
return tm->Replacement;
}
void transState(void *UNUSED, int val){
if (val) MAIN.Translation.EnableTranslation = 1;
else MAIN.Translation.EnableTranslation = 0;
laRedrawCurrentWindow();
}
void laOpenInternetLink(char *url){
laSafeString* s=0;
#ifdef LA_LINUX
strSafePrint(&s, "xdg-open %s", url);
#endif
#ifdef _WIN32
strSafePrint(&s, "start %s", url);
#endif
system(s->Ptr);
strSafeDestroy(&s);
//these were windows stuff
//HKEY hkRoot, hSubKey;
//char ValueName[256]={0};
//char DataValue[256]={0};
//u64bit cbValueName = 256;
//u64bit cbDataValue = 256;
//char ShellChar[512]={0};
//DWORD dwType;
//
//ShellExecute(0, "open", link, 0, 0, SW_SHOWNORMAL);
//
//return;
}
#ifdef _WIN32
void usleep(unsigned int usec){
HANDLE timer;
LARGE_INTEGER ft;
static int init = 0;
if (init == 0){
init = 1;
const HINSTANCE ntdll = LoadLibrary("ntdll.dll");
if (ntdll != NULL){
typedef long(NTAPI* pNtQueryTimerResolution)(u64bit* MinimumResolution, u64bit* MaximumResolution, u64bit* CurrentResolution);
typedef long(NTAPI* pNtSetTimerResolution)(u64bit RequestedResolution, char SetResolution, u64bit* ActualResolution);
pNtQueryTimerResolution NtQueryTimerResolution = (pNtQueryTimerResolution)GetProcAddress(ntdll, "NtQueryTimerResolution");
pNtSetTimerResolution NtSetTimerResolution = (pNtSetTimerResolution)GetProcAddress(ntdll, "NtSetTimerResolution");
if (NtQueryTimerResolution != NULL && NtSetTimerResolution != NULL){
u64bit minimum, maximum, current;
NtQueryTimerResolution(&minimum, &maximum, ¤t);
NtSetTimerResolution(maximum, (char)1, ¤t);
}
FreeLibrary(ntdll);
}
}
ft.QuadPart = -(10 * (__int64)usec);
timer = CreateWaitableTimer(NULL, TRUE, NULL);
SetWaitableTimer(timer, &ft, 0, NULL, NULL, 0);
WaitForSingleObject(timer, INFINITE);
CloseHandle(timer);
}
void laSpinInit(SYSLOCK* lock) {
InitializeCriticalSection(lock);
}
void laSpinDestroy(SYSLOCK* lock) {
DeleteCriticalSection(lock);
}
void laSpinLock(SYSLOCK* lock) {
EnterCriticalSection(lock);
}
void laSpinUnlock(SYSLOCK* lock) {
LeaveCriticalSection(lock);
}
#endif
#ifdef LA_LINUX
void laSpinInit(SYSLOCK* lock) {
pthread_spin_init(lock, 0);
}
void laSpinDestroy(SYSLOCK* lock) {
pthread_spin_destroy(lock);
}
void laSpinLock(SYSLOCK* lock) {
pthread_spin_lock(lock);
}
void laSpinUnlock(SYSLOCK* lock) {
pthread_spin_unlock(lock);
}
#endif
#ifdef LAGUI_ANDROID
void laSpinInit(SYSLOCK* lock) {
return;
}
void laSpinDestroy(SYSLOCK* lock) {
return;
}
void laSpinLock(SYSLOCK* lock) {
return;
}
void laSpinUnlock(SYSLOCK* lock) {
return;
}
#endif
//======================================= lua utils
#ifdef LA_WITH_LUAJIT
static const char *progname = LUA_PROGNAME;
static int la_luaTraceback(lua_State *L){
if (!lua_isstring(L, 1)) { /* Non-string error object? Try metamethod. */
if (lua_isnoneornil(L, 1) ||
!luaL_callmeta(L, 1, "__tostring") ||
!lua_isstring(L, -1))
return 1; /* Return non-string error object. */
lua_remove(L, 1); /* Replace object by result of __tostring metamethod. */
}
luaL_traceback(L, L, lua_tostring(L, 1), 1);
return 1;
}
static void la_luaMessage(const char *msg){
if (progname) { logPrint("%s: ",progname); } logPrint("%s\n",msg);
}
static int la_luaReport(lua_State *L, int status){
if (status && !lua_isnil(L, -1)) {
const char *msg = lua_tostring(L, -1);
if (msg == NULL) msg = "(error object is not a string)";
la_luaMessage(msg);
lua_pop(L, 1);
}
return status;
}
static int la_luaDoCall(lua_State *L, int narg, int clear){
int status;
int base = lua_gettop(L) - narg; /* function index */
lua_pushcfunction(L, la_luaTraceback); /* push la_luaTraceback function */
lua_insert(L, base); /* put it under chunk and args */
status = lua_pcall(L, narg, (clear ? 0 : LUA_MULTRET), base);
lua_remove(L, base); /* remove la_luaTraceback function */
/* force a complete garbage collection in case of errors */
if (status != LUA_OK) lua_gc(L, LUA_GCCOLLECT, 0);
return status;
}
static int la_luaIncomplete(lua_State *L, int status){
if (status == LUA_ERRSYNTAX) {
size_t lmsg;
const char *msg = lua_tolstring(L, -1, &lmsg);
const char *tp = msg + lmsg - (sizeof(LUA_QL("")) - 1);
if (strstr(msg, LUA_QL("")) == tp) { lua_pop(L, 1); return 1; }
}
return 0; /* else... */
}
int terLoadLine(char* buf, int firstline){
lua_State *L=MAIN.L;
if(!MAIN.TerminalIncomplete){ lua_settop(L, 0); }
size_t len = strlen(buf); if(len>=512){ buf[512]=0; }
if(len > 0 && buf[len-1] == '\n') buf[len-1] = '\0';
if(firstline && buf[0] == '=') lua_pushfstring(L, "return %s", buf+1);
else lua_pushstring(L, buf);
if(MAIN.TerminalIncomplete){
lua_pushliteral(L, "\n"); lua_insert(L, -2); lua_concat(L, 3);
}
int status = luaL_loadbuffer(L, lua_tostring(L, 1), lua_strlen(L, 1), "terLoadLine");
if(la_luaIncomplete(L,status)){
MAIN.TerminalIncomplete=1;
}else{
MAIN.TerminalIncomplete=0;
lua_remove(L, 1);
}
if(status==LUA_OK && (!MAIN.TerminalIncomplete)){
status = la_luaDoCall(L, 0, 0);
la_luaReport(L, status);
if (status == LUA_OK && lua_gettop(L) > 0) { /* any result to print? */
lua_getglobal(L, "log");
lua_insert(L, 1);
if (lua_pcall(L, lua_gettop(L)-1, 0, 0) != 0)
la_luaMessage(lua_pushfstring(L, "error calling " LUA_QL("log") " (%s)",
lua_tostring(L, -1)));
}
}
return status;
}
static int lalua_Log(lua_State *L) {
int n = lua_gettop(L); int i;
lua_getglobal(L, "tostring");
for (i=1; i<=n; i++) {
const char *s;
lua_pushvalue(L, -1); /* tostring function */
lua_pushvalue(L, i); /* value to print */
lua_call(L, 1, 1);
s = lua_tostring(L, -1); /* get result */
if (s == NULL) return luaL_error(L, LUA_QL("tostring") " must return a string to "LUA_QL("use `log`"));
if (i>1) logPrint(" ");
logPrint(s); lua_pop(L, 1); /* pop result */
}
logPrint("\n");
return 0;
}
void la_luaLoadLibs(lua_State *L){
lua_gc(L, LUA_GCSTOP, 0);
luaL_openlibs(L);
lua_register(L,"log",lalua_Log);
if(luaL_loadstring(L, LA_LUA_LIB_COMMON) || lua_pcall(L, 0, 0, 0)){ logPrint(" Error loading lagui lua libs.\n"); };
if(luaL_loadstring(L, LA_LUA_LIB_AUDIO) || lua_pcall(L, 0, 0, 0)){ logPrint(" Error loading lua libs for audio.\n"); };
lua_gc(L, LUA_GCRESTART, -1);
}
void la_luaPrintStatus(lua_State *L){
logPrint(LUAJIT_VERSION " -- " LUAJIT_COPYRIGHT ". " LUAJIT_URL "\n");
int n; const char *s;
lua_getfield(L, LUA_REGISTRYINDEX, "_LOADED");
lua_getfield(L, -1, "jit"); lua_remove(L, -2); /* Get jit.* module table. */
lua_getfield(L, -1, "status"); lua_remove(L, -2);
n = lua_gettop(L);
lua_call(L, 0, LUA_MULTRET);
logPrint(lua_toboolean(L, n) ? "JIT: ON" : "JIT: OFF");
for (n++; (s = lua_tostring(L, n)); n++) { logPrint("%s ",s); }
logPrint("\n");
lua_settop(L, 0); /* clear stack */
}
void la_luaDumpStack(lua_State *L){
int top=lua_gettop(L); for (int i=1; i <= top; i++) {
printf("%d\t%s\t", i, luaL_typename(L,i));
switch (lua_type(L, i)) {
case LUA_TNUMBER: printf("%g\n",lua_tonumber(L,i)); break;
case LUA_TSTRING: printf("%s\n",lua_tostring(L,i)); break;
case LUA_TBOOLEAN: printf("%s\n", (lua_toboolean(L, i) ? "true" : "false")); break;
case LUA_TNIL: printf("%s\n", "nil"); break;
default: printf("%p\n",lua_topointer(L,i)); break;
}
}
}
#else //luajit
int terLoadLine(char* buf, int firstline){
logPrint(buf); return 0;
}
#endif //luajit
#ifdef LAGUI_ANDROID
void glPointSize(real a){
return;
}
void glDrawBuffer(GLenum mode){
GLenum b={GL_NONE};
glDrawBuffers(1,b);
}
#endif