chore: make specific vector (heap stack) impl

This commit is contained in:
javalsai 2024-10-18 21:54:39 +02:00
parent c586a48320
commit 01ddd62852
Signed by: javalsai
SSH Key Fingerprint: SHA256:3G83yKhBUWVABVX/vPWH88xnK4+ptMtHkZGCRXD4Mk8
2 changed files with 73 additions and 0 deletions

View File

@ -3,6 +3,7 @@
#include <keys.h>
#include <stdbool.h>
#include <stdint.h>
#include <sys/types.h>
enum keys find_keyname(char *);
@ -10,4 +11,19 @@ enum keys find_ansi(char *);
void read_press(u_char *, char *);
void strcln(char **dest, const char *source);
struct Vector {
uint32_t length;
uint32_t alloc_len;
uint16_t alloc_size;
void** pages;
};
struct Vector vec_new();
int vec_push(struct Vector*, void* item);
void vec_free(struct Vector*);
void vec_clear(struct Vector*);
void vec_reset(struct Vector*);
void* vec_pop(struct Vector*); // wont free it, nor shrink vec list space
void* vec_get(struct Vector*, uint32_t index);
#endif

View File

@ -1,3 +1,4 @@
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
@ -66,3 +67,59 @@ static int selret_magic() {
timeout.tv_usec = 0;
return select(1, &set, NULL, NULL, &timeout);
}
// Vector shii
struct Vector vec_new() {
struct Vector vec;
vec_clear(&vec);
return vec;
}
int vec_push(struct Vector* vec, void* item) {
if (vec->length >= vec->alloc_len) {
uint32_t new_size = vec->alloc_len + vec->alloc_size;
void **new_location = realloc(vec->pages, vec->alloc_size);
if (new_location != NULL) {
vec->alloc_size = new_size;
vec->pages = new_location;
} else {
return -1;
}
}
vec->pages[vec->length] = item;
vec->length++;
return 0;
}
void vec_free(struct Vector* vec) {
for(; vec->length > 0; vec->length--)
free(vec->pages[--vec->length]);
vec_clear(vec);
}
void vec_clear(struct Vector* vec) {
free(vec->pages);
vec_reset(vec);
}
void vec_reset(struct Vector* vec) {
vec->length = 0;
vec->alloc_len = 0;
vec->alloc_size = 4096; // 4KiB page size?
vec->pages = NULL;
}
void* vec_pop(struct Vector* vec) {
if (vec->length == 0)
return NULL;
vec->length--;
return vec->pages[vec->length];
}
void* vec_get(struct Vector* vec, uint32_t index) {
return vec->pages[index];
}