#pragma once // ---------------------------------------------------------------------------- // dynamic array typedef struct BufHdr { vlong len; vlong cap; byte buf[]; } BufHdr; #define bufhdr(b) ((BufHdr*)((uint8*)(b)-offsetof(BufHdr, buf))) #define buflen(b) ((b) ? (bufhdr(b)->len) : 0) #define bufcap(b) ((b) ? (bufhdr(b)->cap) : 0) #define bufend(b) ((b) + buflen(b)) #define bufsize(b) ((b) ? (buflen(b) * sizeof((b)[0])) : 0) #define buffree(b) ((b) ? (free(bufhdr(b)), (b) = nil) : 0) #define buffit(b, n) ((n) <= bufcap(b) ? 0 : ((b) = ·bufgrow((b), (n), sizeof(*(b))))) #define bufpush(b, ...) (buffit((b), 1 + buflen(b)), (b)[bufhdr(b)->len++] = (__VA_ARGS__)) #define bufaddn(b, n) (buffit(b, buflen(b)+n), bufhdr(b)->len += n, b+bufhdr(b)->len-n) #define bufpop(b) ((b)[--bufhdr(b)->len]) #define bufdel(b, i) bufdeln((b), (i), 1) #define bufdeln(b, i, n) (memmove((b)+(i), (b)+(i)+(n), sizeof(*(b))*(bufhdr(b)->len-(n)-(i)), bufhdr(b)->len -= (n)) #define bufdelswap(b, i) ((b)[i] = bufend(b)[-1], bufhdr(b)->len-=1) void* ·bufgrow(void*, vlong, vlong); // ----------------------------------------------------------------------------- // memory allocation /* allocator interface */ typedef struct mem·Allocator { void *(*alloc)(void *heap, uint n, ulong size); void (*free)(void *heap, void *ptr); } mem·Allocator; extern mem·Allocator sys·Memory; typedef struct mem·Reallocator { void *(*alloc)(void *iface, uint n, ulong size); void *(*realloc)(void *iface, void *ptr, uint n, ulong size); void (*free)(void *iface, void *ptr); } mem·Reallocator; extern mem·Reallocator sys·FullMemory; /* simple memory arena */ typedef struct mem·Arena mem·Arena; mem·Arena *mem·makearena(mem·Allocator from, void*); void *mem·arenaalloc(mem·Arena *A, uint n, ulong size); void mem·freearena(mem·Arena *A); extern mem·Allocator mem·ArenaAllocator; /* mem functions */ int mem·move(void *dst, void *src, uintptr size); void *mem·findc(void *dst, uintptr len, int c); int mem·set(void *dst, int val, uintptr size); int mem·set64(void *dst, uint64 val, uintptr size);