diff --git a/.gitmodules b/.gitmodules new file mode 100644 index 00000000..f563a76c --- /dev/null +++ b/.gitmodules @@ -0,0 +1,3 @@ +[submodule "shared"] + path = shared + url = ../redlib diff --git a/Makefile b/Makefile index 1197788a..435275ee 100644 --- a/Makefile +++ b/Makefile @@ -16,7 +16,7 @@ all: kshared modules kernel shared user utils bins ./createfs kshared: - $(MAKE) -C shared SH_FLAGS=-DKERNEL BUILD_DIR=./kbuild TARGET=klibshared.a + $(MAKE) -C shared kern modules: kshared $(MAKE) -C modules XHCI_CTX_SIZE=$(XHCI_CTX_SIZE) QEMU=$(QEMU) TEST=$(TEST) DRIVER_TARGET=$(MODE) @@ -52,9 +52,6 @@ clean: @echo "removing images" $(RM) kernel.img kernel.elf disk.img dump -cross: - $(MAKE) -C shared ARCH= SH_FLAGS=-DCROSS BUILD_DIR=./cbuild TARGET=clibshared.a - raspi: $(MAKE) LOAD_ADDR=0x80000 XHCI_CTX_SIZE=64 QEMU=true MODE=raspi all ./run_raspi @@ -76,7 +73,7 @@ dump: install: $(MAKE) clean - $(MAKE) LOAD_ADDR=0x80000 XHCI_CTX_SIZE=64 QEMU=false all + $(MAKE) LOAD_ADDR=0x80000 XHCI_CTX_SIZE=64 QEMU=false MODE=raspi all cp kernel.img $(BOOTFS)/kernel8.img cp kernel.img $(BOOTFS)/kernel_2712.img cp config.txt $(BOOTFS)/config.txt diff --git a/kernel/bin/ping.c b/kernel/bin/ping.c index 5b05b5df..50bf6e48 100644 --- a/kernel/bin/ping.c +++ b/kernel/bin/ping.c @@ -42,7 +42,7 @@ static bool parse_args(int argc, char *argv[], ping_opts_t *o) { o->src_set = false; o->host = NULL; - for (int i = 0; i < argc; ++i) { + for (int i = 1; i < argc; ++i) { const char *a = argv[i]; if (a && a[0] == '-') { if (strcmp_case(a, "-4",true) == 0) o->ver = IP_VER4; diff --git a/kernel/bin/shutdown.c b/kernel/bin/shutdown.c index 21fd8ad4..f74abb15 100644 --- a/kernel/bin/shutdown.c +++ b/kernel/bin/shutdown.c @@ -27,7 +27,7 @@ int run_shutdown(int argc, char* argv[]){ int mode = -1; - for (int i = 0; i < argc; ++i){ + for (int i = 1; i < argc; ++i){ const char *a = argv[i]; if (!a || a[0] == 0) continue; diff --git a/kernel/bin/tracert.c b/kernel/bin/tracert.c index addbea48..98da6a32 100644 --- a/kernel/bin/tracert.c +++ b/kernel/bin/tracert.c @@ -43,7 +43,7 @@ static bool parse_args(int argc, char *argv[], tr_opts_t *o) { o->src_set = false; o->host = NULL; - for (int i = 0; i < argc; i++) { + for (int i = 1; i < argc; i++) { const char *a = argv[i]; if (a && a[0] == '-') { if (strcmp_case(a, "-4",true) == 0) { diff --git a/kernel/console/kio.c b/kernel/console/kio.c index ef45e03e..19e25741 100644 --- a/kernel/console/kio.c +++ b/kernel/console/kio.c @@ -5,7 +5,7 @@ #include "memory/page_allocator.h" #include "std/memory.h" #include "math/math.h" -#include "data_struct/ring_buffer.h" +#include "data/struct/ring_buffer.h" static bool use_visual = false; diff --git a/kernel/dev/driver_base.c b/kernel/dev/driver_base.c index e67f5c27..06647d9a 100644 --- a/kernel/dev/driver_base.c +++ b/kernel/dev/driver_base.c @@ -1,5 +1,5 @@ #include "driver_base.h" -#include "data_struct/hashmap.h" +#include "data/struct/hashmap.h" #include "std/string.h" uint64_t fd_id = 256;//First byte reserved diff --git a/kernel/dev/module_loader.h b/kernel/dev/module_loader.h index 3bab6ceb..9933a04d 100644 --- a/kernel/dev/module_loader.h +++ b/kernel/dev/module_loader.h @@ -1,7 +1,7 @@ #pragma once #include "driver_base.h" -#include "data_struct/linked_list.h" +#include "data/struct/linked_list.h" #ifdef __cplusplus extern "C" { diff --git a/kernel/filesystem/fat32.hpp b/kernel/filesystem/fat32.hpp index 589d4886..9b19de43 100644 --- a/kernel/filesystem/fat32.hpp +++ b/kernel/filesystem/fat32.hpp @@ -3,7 +3,7 @@ #include "types.h" #include "std/string.h" #include "fsdriver.hpp" -#include "data_struct/hashmap.h" +#include "data/struct/hashmap.h" typedef struct fat32_mbs { uint8_t jumpboot[3];//3 diff --git a/kernel/filesystem/pipe.c b/kernel/filesystem/pipe.c index 09050b6b..6c72c4ce 100644 --- a/kernel/filesystem/pipe.c +++ b/kernel/filesystem/pipe.c @@ -1,8 +1,8 @@ #include "pipe.h" #include "filesystem.h" #include "memory/page_allocator.h" -#include "data_struct/hashmap.h" -#include "data_struct/linked_list.h" +#include "data/struct/hashmap.h" +#include "data/struct/linked_list.h" #include "process/scheduler.h" static void *pipe_page; diff --git a/kernel/filesystem/virtio_9p_pci.hpp b/kernel/filesystem/virtio_9p_pci.hpp index 4bc8291b..c351c41e 100644 --- a/kernel/filesystem/virtio_9p_pci.hpp +++ b/kernel/filesystem/virtio_9p_pci.hpp @@ -2,7 +2,7 @@ #include "fsdriver.hpp" #include "virtio/virtio_pci.h" -#include "data_struct/hashmap.h" +#include "data/struct/hashmap.h" typedef struct p9_packet_header { uint32_t size; diff --git a/kernel/gpio.c b/kernel/gpio.c index 46edb7e4..417b7855 100644 --- a/kernel/gpio.c +++ b/kernel/gpio.c @@ -1,16 +1,62 @@ #include "gpio.h" #include "hw/hw.h" #include "async.h" -#include "std/memory_access.h" #include "memory/mmu.h" +#include "std/memory_access.h" void reset_gpio(){ - register_device_memory(GPIO_BASE, GPIO_BASE); + register_device_memory(GPIO_BASE, GPIO_BASE); write32(GPIO_BASE + GPIO_PIN_BASE + 0x94, 0x0); delay(150); } +#define GPIOFSEL0 0 +#define GPIOSET0 0x1C +#define GPIOCLR0 0x28 +#define GPIOPUPPDN0 0xE4 + +#define GPIO_PULL_NONE 0 +#define GPIO_PULL_DOWN 2 +#define GPIO_PULL_UP 1 + +#define GPIO_FUNCTION_IN 0 +#define GPIO_FUNCTION_OUT 1 +#define GPIO_FUNCTION_ALT5 2 +#define GPIO_FUNCTION_ALT3 7 +#define GPIO_FUNCTION_ALT0 4 + +bool call_gpio(unsigned long pin, unsigned long value, uint32_t base, unsigned long field_size) +{ + unsigned long field_mask = (1 << field_size) - 1; + + if (pin > field_mask && value > field_mask) + return false; + + unsigned long num_fields = 32 / field_size; + unsigned long regist = GPIO_BASE + base + ((pin / num_fields) * 4); + unsigned long shift = (pin % num_fields) * field_size; + + unsigned long finalval = read32(regist); + finalval &= ~(field_mask << shift); + finalval |= value << shift; + + write32(regist, finalval); + + return true; +} + +bool pull_gpio(unsigned long pin, uint32_t pull) +{ + return call_gpio(pin, pull, GPIOPUPPDN0, 2); +} + +bool set_gpio_func(unsigned long pin, uint32_t func) +{ + return call_gpio(pin, func, GPIOFSEL0, 3); +} + void enable_gpio_pin(uint8_t pin){ - uint32_t v = read32(GPIO_BASE + GPIO_PIN_BASE + 0x98); - write32(GPIO_BASE + GPIO_PIN_BASE + 0x98, v | (1 << pin)); + pull_gpio(pin, GPIO_PULL_NONE); + set_gpio_func(pin, GPIO_FUNCTION_ALT0); + pull_gpio(pin, GPIO_PULL_NONE); } \ No newline at end of file diff --git a/kernel/graph/tres.h b/kernel/graph/tres.h index 12072a6b..6202a382 100644 --- a/kernel/graph/tres.h +++ b/kernel/graph/tres.h @@ -2,7 +2,7 @@ #include "types.h" #include "ui/draw/draw.h" -#include "data_struct/linked_list.h" +#include "data/struct/linked_list.h" #ifdef __cplusplus extern "C" { diff --git a/kernel/kernel_processes/windows/launcher.cpp b/kernel/kernel_processes/windows/launcher.cpp index 8d22c151..a02ba2f2 100644 --- a/kernel/kernel_processes/windows/launcher.cpp +++ b/kernel/kernel_processes/windows/launcher.cpp @@ -10,6 +10,7 @@ #include "graph/tres.h" #include "process/scheduler.h" #include "exceptions/irq.h" +#include "math/math.h" #define MAX_COLS 3 #define MAX_ROWS 3 diff --git a/kernel/kernel_processes/windows/launcher.hpp b/kernel/kernel_processes/windows/launcher.hpp index ab352846..9156c153 100644 --- a/kernel/kernel_processes/windows/launcher.hpp +++ b/kernel/kernel_processes/windows/launcher.hpp @@ -3,7 +3,7 @@ #include "types.h" #include "graph/graphics.h" #include "process/process.h" -#include "std/std.h" +#include "data/struct/array.hpp" #include "process/loading/package_info.h" struct LaunchEntry { diff --git a/kernel/memory/page_allocator.c b/kernel/memory/page_allocator.c index bb558866..4f1e8ee9 100644 --- a/kernel/memory/page_allocator.c +++ b/kernel/memory/page_allocator.c @@ -82,6 +82,7 @@ void* palloc_inner(uint64_t size, uint8_t level, uint8_t attributes, bool full, end = count_pages(get_user_ram_end(),PAGE_SIZE); mem_bitmap = (uintptr_t*)(start * PAGE_SIZE); start += count_pages(65536*8,PAGE_SIZE); + memset(mem_bitmap, 0, 65536*8); heap_end = start*PAGE_SIZE; } uint64_t page_count = count_pages(size,PAGE_SIZE); diff --git a/kernel/networking/application_layer/dhcpv6_daemon.c b/kernel/networking/application_layer/dhcpv6_daemon.c index 5032514b..f602400d 100644 --- a/kernel/networking/application_layer/dhcpv6_daemon.c +++ b/kernel/networking/application_layer/dhcpv6_daemon.c @@ -6,7 +6,7 @@ #include "process/scheduler.h" #include "math/rng.h" -#include "data_struct/linked_list.h" +#include "data/struct/linked_list.h" #include "networking/interface_manager.h" #include "networking/network.h" diff --git a/kernel/networking/network_dispatch.hpp b/kernel/networking/network_dispatch.hpp index 2701988b..b810af6d 100644 --- a/kernel/networking/network_dispatch.hpp +++ b/kernel/networking/network_dispatch.hpp @@ -5,7 +5,7 @@ #include "net/network_types.h" #include "networking/internet_layer/ipv4.h" #include "interface_manager.h" -#include "data_struct/data_struct.hpp" +#include "data/struct/data_struct.hpp" class NetworkDispatch { public: diff --git a/kernel/networking/transport_layer/csocket.c b/kernel/networking/transport_layer/csocket.c index 46c6a17b..820e2817 100644 --- a/kernel/networking/transport_layer/csocket.c +++ b/kernel/networking/transport_layer/csocket.c @@ -3,7 +3,7 @@ #include "csocket_udp.h" #include "memory/page_allocator.h" #include "console/kio.h" -#include "data_struct/hashmap.h" +#include "data/struct/hashmap.h" uint16_t socket_ids; diff --git a/kernel/networking/transport_layer/socket_tcp.hpp b/kernel/networking/transport_layer/socket_tcp.hpp index bad5d0b4..bece35ed 100755 --- a/kernel/networking/transport_layer/socket_tcp.hpp +++ b/kernel/networking/transport_layer/socket_tcp.hpp @@ -7,7 +7,7 @@ #include "networking/internet_layer/ipv4.h" #include "networking/application_layer/dns/dns.h" #include "types.h" -#include "data_struct/ring_buffer.hpp" +#include "data/struct/ring_buffer.hpp" #include "net/socket_types.h" #include "networking/internet_layer/ipv4_route.h" #include "networking/internet_layer/ipv6_route.h" diff --git a/kernel/process/loading/package_info.c b/kernel/process/loading/package_info.c index 28b84472..740e2557 100644 --- a/kernel/process/loading/package_info.c +++ b/kernel/process/loading/package_info.c @@ -2,7 +2,7 @@ #include "std/string.h" #include "syscalls/syscalls.h" #include "console/kio.h" -#include "data/toml.h" +#include "data/format/toml.h" static inline void handle_package_kvp(string_slice key, string_slice value, void* ctx){ package_info *pkg_info = (package_info*)ctx; diff --git a/kernel/process/scheduler.c b/kernel/process/scheduler.c index 6dcf9082..7fe03481 100644 --- a/kernel/process/scheduler.c +++ b/kernel/process/scheduler.c @@ -7,7 +7,7 @@ #include "exceptions/timer.h" #include "console/kconsole/kconsole.h" #include "std/string.h" -#include "data_struct/hashmap.h" +#include "data/struct/hashmap.h" #include "std/memory.h" #include "math/math.h" #include "memory/mmu.h" diff --git a/kernel/theme/theme.c b/kernel/theme/theme.c index 606409e3..3ca03b2b 100644 --- a/kernel/theme/theme.c +++ b/kernel/theme/theme.c @@ -1,6 +1,6 @@ #include "theme.h" #include "syscalls/syscalls.h" -#include "data/toml.h" +#include "data/format/toml.h" #include "default.h" #include "console/kio.h" #include "math/math.h" diff --git a/kernel/usb/USBDevice.hpp b/kernel/usb/USBDevice.hpp index dcbe8126..fae9b198 100644 --- a/kernel/usb/USBDevice.hpp +++ b/kernel/usb/USBDevice.hpp @@ -3,6 +3,7 @@ #include "usb_types.h" #include "std/std.h" #include "console/kio.h" +#include "data/struct/indexmap.hpp" class USBDriver; diff --git a/modules/serial/common/uart_base.c b/modules/serial/common/uart_base.c index 7d6b17b9..c1bb83f0 100644 --- a/modules/serial/common/uart_base.c +++ b/modules/serial/common/uart_base.c @@ -11,6 +11,7 @@ #define UART0_FBRD (UART0_BASE + 0x28) #define UART0_LCRH (UART0_BASE + 0x2C) #define UART0_CR (UART0_BASE + 0x30) +#define UART0_IMSC (UART0_BASE + 0x38) #define UART_FIFO 4 #define UART_WLEN 5 @@ -42,6 +43,8 @@ void enable_uart() { write32(UART0_LCRH, (1 << UART_FIFO) | (UART_8B_WLEN << UART_WLEN)); write32(UART0_CR, (1 << UART_EN) | (1 << UART_TXE) | (1 << UART_RXE)); + + write32(UART0_IMSC, 1 << 4); } void uart_raw_putc(const char c) { diff --git a/shared b/shared new file mode 160000 index 00000000..322b1ef7 --- /dev/null +++ b/shared @@ -0,0 +1 @@ +Subproject commit 322b1ef78f90f51b0d96ab4e750a5001209bdbe1 diff --git a/shared/Makefile b/shared/Makefile deleted file mode 100644 index 5531e21b..00000000 --- a/shared/Makefile +++ /dev/null @@ -1,47 +0,0 @@ -#shared - -include ../common.mk - -CPPFLAGS := -I. -CFLAGS := $(CFLAGS_BASE) $(CPPFLAGS) -CXXFLAGS := $(CXXFLAGS_BASE) $(CPPFLAGS) - -CLEAN_OBJS := $(shell find . -name "*.o") -CLEAN_DEPS := $(shell find . -name "*.d") -C_SRC := $(shell find . -name "*.c") -CPP_SRC := $(shell find . -name "*.cpp") -ASM_SRC := $(shell find . -name "*.S") -OBJ := $(C_SRC:%.c=$(BUILD_DIR)/%.o) $(ASM_SRC:%.S=$(BUILD_DIR)/%.o) $(CPP_SRC:%.cpp=$(BUILD_DIR)/%.o) -DEP := $(C_SRC:%.c=$(BUILD_DIR)/%.d) $(ASM_SRC:%.S=$(BUILD_DIR)/%.d) $(CPP_SRC:%.cpp=$(BUILD_DIR)/%.d) - -TARGET := libshared.a - -.PHONY: all clean prepare - -all: prepare $(TARGET) - -prepare: - mkdir -p $(BUILD_DIR) - -$(TARGET): $(OBJ) - @echo "Finishing build $(ARCH)" - echo $(addprefix $(BUILD_DIR)/,$(notdir $(OBJ))) - $(VAR) rcs $@ $(OBJ) - -$(BUILD_DIR)/%.o: %.S - @mkdir -p $(dir $@) - $(VAS) $(CFLAGS) $(SH_FLAGS) -c $< -o $@ - -$(BUILD_DIR)/%.o: %.c - @mkdir -p $(dir $@) - $(VCC) $(CFLAGS) $(SH_FLAGS) -c -MMD -MP $< -o $@ - -$(BUILD_DIR)/%.o: %.cpp - @mkdir -p $(dir $@) - $(VCXX) $(CXXFLAGS) $(SH_FLAGS) -c -MMD -MP $< -o $@ - -clean: - $(RM) $(CLEAN_OBJS) $(CLEAN_DEPS) $(TARGET) - $(RM) -r $(BUILD_DIR) - --include $(DEP) diff --git a/shared/audio/cuatro.c b/shared/audio/cuatro.c deleted file mode 100644 index 01d4b0b6..00000000 --- a/shared/audio/cuatro.c +++ /dev/null @@ -1,114 +0,0 @@ -#include "math/math.h" -#include "files/fs.h" -#include "syscalls/syscalls.h" -#include "cuatro.h" -#include "audio/mixer.h" -#include "wav.h" -#include "tone.h" - -static file mixer = { .id = 0 }; // 0 ok as filesystem ids > 256 - -static inline bool mixer_open_file(){ - return (mixer.id > 0) || (FS_RESULT_SUCCESS == openf("/audio/output", &mixer)); -} - -int8_t mixer_open_line(){ - mixer_line_data data; - if (mixer_open_file()){ - if (mixer_read_line(-1, &data)) return data.lineId; - } - return -1; -} - -void mixer_close_line(int8_t lineId){ - if (mixer_open_file() && lineId >= 0){ - mixer_command command = { .lineId = lineId, .command = MIXER_CLOSE_LINE }; - writef(&mixer, (char*)&command, sizeof(mixer_command)); - } -} - -bool mixer_read_line(int8_t lineId, mixer_line_data* data){ - if (mixer_open_file()){ - data->lineId = lineId; - return (sizeof(mixer_line_data) == readf(&mixer, (char*)data, sizeof(mixer_line_data))); - } - return false; -} - -bool mixer_still_playing(int8_t lineId){ - if (mixer_open_file()){ - mixer_line_data data; - data.lineId = lineId; - if (mixer_read_line(lineId, &data)){ - if (data.dbl.buf[0].ptr != 0 || data.dbl.buf[1].ptr != 0) return true; - } - } - return false; -} - -bool mixer_mute(){ - if (mixer_open_file()){ - mixer_command command = { .lineId = -1, .command = MIXER_MUTE }; - writef(&mixer, (char*)&command, sizeof(mixer_command)); - } - return false; // TODO: return prev setting -} - -bool mixer_unmute(){ - if (mixer_open_file()){ - mixer_command command = { .lineId = -1, .command = MIXER_UNMUTE }; - writef(&mixer, (char*)&command, sizeof(mixer_command)); - } - return true; // TODO: return prev setting -} - -int16_t mixer_master_level(int16_t level){ - if (mixer_open_file()){ - mixer_command command = { .lineId = -1, .command = MIXER_SETLEVEL, .level = level }; - writef(&mixer, (char*)&command, sizeof(mixer_command)); - } - return level; // TODO: return prev setting -} - -int16_t mixer_line_level(int8_t lineId, int16_t level, int16_t pan){ - if (lineId < 0 || lineId > MIXER_INPUTS) return 0; - if (mixer_open_file()){ - mixer_command command = { .lineId = lineId, .command = MIXER_SETLEVEL, .level = level, .pan = pan }; - writef(&mixer, (char*)&command, sizeof(mixer_command)); - } - return level; // TODO: return prev setting -} - -static bool mixer_play_async(int8_t lineId, audio_samples* audio, uint32_t delay_ms, AUDIO_LIFETIME life, int16_t level, int16_t pan){ - mixer_command command = { .lineId = lineId, .command = MIXER_PLAY, .audio = audio, .delay_ms = delay_ms, .life = life, .level = level, .pan = pan }; - return (sizeof(mixer_command) == writef(&mixer, (char*)&command, sizeof(mixer_command))); -} - -bool audio_play_sync(audio_samples *audio, uint32_t delay_ms, AUDIO_LIFETIME life, int16_t level, int16_t pan){ - int8_t lineId = mixer_open_line(); - if (lineId < 0 || false == mixer_play_async(lineId, audio, delay_ms, life, level, pan)) return false; - do { - msleep(5); - } while (mixer_still_playing(lineId)); - mixer_close_line(lineId); - return true; -} - -int8_t audio_play_async(audio_samples *audio, uint32_t delay_ms, AUDIO_LIFETIME life, int16_t level, int16_t pan){ - int8_t lineId = mixer_open_line(); - if (lineId >= 0) { - if (false == mixer_play_async(lineId, audio, delay_ms, life, level, pan)) { - mixer_close_line(lineId); - lineId = -1; - } - } - return lineId; -} - -bool audio_update_stream(int8_t lineId, sizedptr samples){ - if (mixer_open_file()){ - mixer_command command = { .lineId = lineId, .command = MIXER_SETBUFFER, .samples = samples }; - return (sizeof(mixer_command) == writef(&mixer, (char*)&command, sizeof(mixer_command))); - } - return false; -} diff --git a/shared/audio/cuatro.h b/shared/audio/cuatro.h deleted file mode 100644 index ee979e6b..00000000 --- a/shared/audio/cuatro.h +++ /dev/null @@ -1,65 +0,0 @@ -#pragma once - -#include "types.h" - -typedef int16_t audio_sample_t; - -typedef enum AUDIO_LIFETIME { - AUDIO_OFF = 0, - AUDIO_ONESHOT, // play samples once - AUDIO_ONESHOT_FREE, // play samples once then free_sized() their memory - AUDIO_LOOP, // play samples repeatedly - with delay, if set - AUDIO_STREAM, // assign samples to available dblbuf entry -} AUDIO_LIFETIME; - -typedef enum PAN_RANGE { - PAN_LEFT = -32767, - PAN_HALFLEFT = -16383, - PAN_CENTRE = 0, - PAN_CENTER = 0, - PAN_HALFRIGHT = 16383, - PAN_RIGHT = 32767, -} PAN_RANGE; - -typedef struct audio_samples { - sizedptr samples; - uint32_t smpls_per_channel; // TODO: eliminate. - uint8_t channels; -} audio_samples; - -typedef struct mixer_dblbuf { - sizedptr buf[2]; - uint8_t buf_idx; -} mixer_dblbuf; - -typedef struct mixer_line_data { - int8_t lineId; - mixer_dblbuf dbl; -} mixer_line_data; - - -#define MIXER_INPUTS 6 -#define AUDIO_LEVEL_MAX INT16_MAX -#define SIGNAL_LEVEL_MAX 32767 -#define SIGNAL_LEVEL_MIN (-32767) - -#ifdef __cplusplus -extern "C" { -#endif - -bool audio_play_sync(audio_samples *audio, uint32_t delay_ms, AUDIO_LIFETIME life, int16_t level, int16_t pan); -int8_t audio_play_async(audio_samples *audio, uint32_t delay_ms, AUDIO_LIFETIME life, int16_t level, int16_t pan); -bool audio_update_stream(int8_t lineId, sizedptr samples); - -int8_t mixer_open_line(); -void mixer_close_line(int8_t lineId); -bool mixer_read_line(int8_t lineId, mixer_line_data* data); -bool mixer_still_playing(int8_t lineId); -bool mixer_mute(); -bool mixer_unmute(); -int16_t mixer_master_level(int16_t level); -int16_t mixer_line_level(int8_t lineId, int16_t level, int16_t pan); - -#ifdef __cplusplus -} -#endif \ No newline at end of file diff --git a/shared/audio/mixer.h b/shared/audio/mixer.h deleted file mode 100644 index 9d83d4c6..00000000 --- a/shared/audio/mixer.h +++ /dev/null @@ -1,22 +0,0 @@ -#pragma once - -typedef enum MIXER_CMND { - MIXER_SETLEVEL, - MIXER_MUTE, - MIXER_UNMUTE, - MIXER_PLAY, - MIXER_SETBUFFER, - MIXER_CLOSE_LINE, -} MIXER_CMND; - -typedef struct mixer_command { - int8_t lineId; - uint32_t command; - audio_samples* audio; - sizedptr samples; - //intptr_t value; - uint32_t delay_ms; - int16_t level; - int16_t pan; - AUDIO_LIFETIME life; -} mixer_command; diff --git a/shared/audio/tone.c b/shared/audio/tone.c deleted file mode 100644 index 37f4212c..00000000 --- a/shared/audio/tone.c +++ /dev/null @@ -1,84 +0,0 @@ -#include "types.h" -#include "syscalls/syscalls.h" -#include "math/math.h" -#include "cuatro.h" -#include "tone.h" - - -#define PHASE_MASK 0x00FFFFFF -#define PHASE_MAX PHASE_MASK -#define PHASE_MID (PHASE_MAX >> 1) - - -static audio_sample_t wave_sample(WAVE_TYPE type, uint32_t phase, rng_t* rng){ - float wave = 0; - switch (type) { - case WAVE_SILENCE: - break; - case WAVE_TRIG: { - float fase = 0.25 + (float)phase / (float)PHASE_MAX; - wave = 2*(absf(fase-floor(fase + 0.5f))) - 0.5; - break; - } - case WAVE_SAW: - wave = 0.5 - (float)phase / (float)PHASE_MAX; - break; - case WAVE_SQUARE: - wave = (phase < PHASE_MID) ? 0.5 : -0.5; - break; - case WAVE_NOISE: { - return (audio_sample_t)rng_next16(rng); - } - } - return (audio_sample_t)(wave * UINT16_MAX); -} - -static void wave_generate(sound_defn* sound, audio_sample_t* sample, size_t count){ - float freq = sound->start_freq; - float freq_delta = (sound->end_freq - sound->start_freq) / count; - uint32_t phase = 0; - rng_t rng; - // TODO: rng_init_random(&rng); - rng.s0 = get_time(); - rng.s1 = (uint64_t)&wave_generate ^ rng.s0; - while (count--){ - uint32_t phase_incr = (uint32_t)(freq * PHASE_MAX / 44100.f); - *sample++ = wave_sample(sound->waveform, phase, &rng); - phase = (phase + phase_incr) & PHASE_MASK; - freq += freq_delta; - } -} - -void sound_create(float duration, sound_defn* sound, audio_samples* audio){ - // !! MONO only - audio->channels = 1; - audio->smpls_per_channel = duration * 44100.f; - audio->samples.size = audio->smpls_per_channel * sizeof(audio_sample_t); - audio->samples.ptr = (uintptr_t)malloc(audio->samples.size); - wave_generate(sound, (audio_sample_t*)audio->samples.ptr, audio->smpls_per_channel); -} - -void sound_shape(envelope_defn* env, audio_samples* audio){ - // !! MONO only - if (env->shape != ENV_NONE && audio->channels == 1){ - size_t attack = 1 + min(audio->smpls_per_channel, max(0, (int)(audio->smpls_per_channel * env->attack))); - size_t sustain = min(audio->smpls_per_channel - attack, max(0, (int)(audio->smpls_per_channel * env->sustain))); - size_t decay = max(0, (int)audio->smpls_per_channel - (int)attack - (int)sustain); - audio_sample_t* sample = (audio_sample_t*)audio->samples.ptr; - float delta = (float)INT16_MAX / attack; - float level = 0; - while (attack--){ - *sample = (int64_t)(*sample * level * level) / (INT16_MAX * INT16_MAX); - level += delta; - ++sample; - } - sample += sustain; - delta = (float)INT16_MAX / decay; - level = INT16_MAX; - while (decay--){ - *sample = (int64_t)(*sample * level * level) / (INT16_MAX * INT16_MAX); - level -= delta; - ++sample; - } - } -} \ No newline at end of file diff --git a/shared/audio/tone.h b/shared/audio/tone.h deleted file mode 100644 index bac5d369..00000000 --- a/shared/audio/tone.h +++ /dev/null @@ -1,42 +0,0 @@ -#pragma once - -#include "cuatro.h" - - -typedef enum WAVE_TYPE { - WAVE_SILENCE, - WAVE_SQUARE, - WAVE_TRIG, - WAVE_SAW, - WAVE_NOISE, -} WAVE_TYPE; - -typedef struct sound_defn { - WAVE_TYPE waveform; - float start_freq; - float end_freq; -} sound_defn; - -typedef enum ENV_TYPE { - ENV_NONE, - ENV_ASD, - // ENV_ADSR, -} ENV_TYPE; - -typedef struct envelope_defn { - ENV_TYPE shape; - float attack; // 0..1 as fraction of tone duration - float sustain; // ditto -} envelope_defn; - - -#ifdef __cplusplus -extern "C" { -#endif - -void sound_create(float seconds, sound_defn *sound, audio_samples *audio); -void sound_shape(envelope_defn* env, audio_samples* audio); - -#ifdef __cplusplus -} -#endif \ No newline at end of file diff --git a/shared/audio/wav.c b/shared/audio/wav.c deleted file mode 100644 index c775f911..00000000 --- a/shared/audio/wav.c +++ /dev/null @@ -1,145 +0,0 @@ -#include "types.h" -#include "files/fs.h" -#include "std/memory.h" -#include "math/math.h" -#include "cuatro.h" -#include "wav.h" -#include "syscalls/syscalls.h" - - -// TODO: Handle non-trivial wav headers and other sample formats: -// https://web.archive.org/web/20100325183246/http://www-mmsp.ece.mcgill.ca/Documents/AudioFormats/WAVE/WAVE.html - -typedef struct wav_header { - uint32_t id; - uint32_t fSize; - uint32_t wave_id; -}__attribute__((packed)) wav_header; - -typedef struct wav_chunk_hdr { - uint32_t ck_id; - uint32_t ck_size; -}__attribute__((packed)) wav_chunk_hdr; - -typedef struct wav_format_chunk { - uint16_t format; - uint16_t channels; - uint32_t sample_rate; - uint32_t idk; - uint16_t align; - uint16_t sample_bits; -}__attribute__((packed)) wav_format_chunk; - -static void transform_16bit(wav_format_chunk *fmt_chunk, uint32_t data_size, audio_samples* audio, uint32_t upsample, file* fd){ - int16_t* tbuf = (int16_t*)malloc(data_size); - readf(fd, (char*)tbuf, data_size); - audio->samples.size = data_size * upsample; - audio->samples.ptr = (uintptr_t)malloc(audio->samples.size); - audio->smpls_per_channel = audio->samples.size / (sizeof(int16_t) * fmt_chunk->channels); - audio->channels = fmt_chunk->channels; - uint32_t samples_remaining = data_size / sizeof(int16_t); - int16_t* source = tbuf; - int16_t* dest = (int16_t*)audio->samples.ptr; - while (samples_remaining-- > 0){ - for (int i = upsample; i > 0; i--){ - *dest++ = *source; // TODO: interpolate - } - ++source; - } - free_sized(tbuf, data_size); -} - -static void transform_8bit(wav_format_chunk *fmt_chunk, uint32_t data_size, audio_samples* audio, uint32_t upsample, file* fd){ - uint8_t* tbuf = (uint8_t*)malloc(data_size); - readf(fd, (char*)tbuf, data_size); - audio->samples.size = data_size * upsample * sizeof(int16_t); - audio->samples.ptr = (uintptr_t)malloc(audio->samples.size); - audio->smpls_per_channel = audio->samples.size / (sizeof(int16_t) * fmt_chunk->channels); - audio->channels = fmt_chunk->channels; - uint32_t samples_remaining = data_size; - uint8_t* source = tbuf; - int16_t* dest = (int16_t*)audio->samples.ptr; - while (samples_remaining-- > 0){ - int16_t sample = (int16_t)((*source++ - 128) * 256); // 8-bit source is offset binary - for (int i = upsample; i > 0; i--){ - *dest++ = sample; // TODO: interpolate - } - } - free_sized(tbuf, data_size); -} - -bool wav_load_as_int16(const char* path, audio_samples* audio){ - file fd = {}; - - if (FS_RESULT_SUCCESS != openf(path, &fd)) - { - printf("[WAV] Could not open file: %s", path); - return false; - } - - wav_header hdr = {}; - size_t read_size = readf(&fd, (char*)&hdr, sizeof(wav_header)); - if (read_size != sizeof(wav_header) || - hdr.id != 0x46464952 || // 'RIFF' - hdr.wave_id != 0x45564157){ // 'WAVE' - printf("[WAV] Non-WAV file format %s", path); - return false; - } - - wav_format_chunk fmt_chunk = {}; - while (fd.cursor < fd.size){ - wav_chunk_hdr ch_hdr = {}; - read_size = readf(&fd, (char*)&ch_hdr, sizeof(wav_chunk_hdr)); - switch (ch_hdr.ck_id){ - case 0x20746D66://fmt format - { - read_size = readf(&fd, (char*)&fmt_chunk, ch_hdr.ck_size); - if (fmt_chunk.channels < 1 || fmt_chunk.channels > 2 || - fmt_chunk.sample_rate > 44100 || - (44100 % fmt_chunk.sample_rate != 0) || - (fmt_chunk.sample_bits != 8 && fmt_chunk.sample_bits != 16) - ) - { - closef(&fd); - printf("[WAV] Unsupported file format %s", path); - printf("=== Sizes %i, %i", read_size, fd.size); - printf("=== id %x", hdr.id); - printf("=== wave id %x", hdr.wave_id); - printf("=== format %x", ch_hdr.ck_id); - printf("=== channels %i", fmt_chunk.channels); - printf("=== sample rate %i", fmt_chunk.sample_rate); - printf("=== sample_bits %i", fmt_chunk.sample_bits); - return false; - } - break; - } - case 0x61746164://data - { - uint32_t upsample = 44100 / fmt_chunk.sample_rate; - bool result = true; - if (fmt_chunk.sample_bits == 16 && upsample == 1){ - // simple case: slurp samples direct from file to wav buffer - audio->samples.size = ch_hdr.ck_size; - audio->samples.ptr = (uintptr_t)malloc(audio->samples.size); - readf(&fd, (char*)audio->samples.ptr, audio->samples.size); - audio->smpls_per_channel = ch_hdr.ck_size / (sizeof(int16_t) * fmt_chunk.channels); - audio->channels = fmt_chunk.channels; - } else if (fmt_chunk.sample_bits == 16){ - transform_16bit(&fmt_chunk, ch_hdr.ck_size, audio, upsample, &fd); - } else if (fmt_chunk.sample_bits == 8){ - transform_8bit(&fmt_chunk, ch_hdr.ck_size, audio, upsample, &fd); - } else{ - result = false; - } - - closef(&fd); - return result; - } - default: - fd.cursor += ch_hdr.ck_size; - break; - } - } - - return false; -} diff --git a/shared/audio/wav.h b/shared/audio/wav.h deleted file mode 100644 index c0a0b1ba..00000000 --- a/shared/audio/wav.h +++ /dev/null @@ -1,12 +0,0 @@ -#pragma once - - -#ifdef __cplusplus -extern "C" { -#endif - -bool wav_load_as_int16(const char*path, audio_samples *audio); - -#ifdef __cplusplus -} -#endif \ No newline at end of file diff --git a/shared/compression/deflate.c b/shared/compression/deflate.c deleted file mode 100644 index 1720bfa5..00000000 --- a/shared/compression/deflate.c +++ /dev/null @@ -1,361 +0,0 @@ -#include "deflate.h" -#include "compression/huffman.h" -#include "syscalls/syscalls.h" -#include "std/memory.h" -#include "math/math.h" - -typedef union zlib_hdr { - struct { - uint16_t cm: 4;// 8 = DEFLATE - uint16_t cinf : 4; - - uint16_t fcheck: 1;//checksum - uint16_t dict: 1; - uint16_t flevel : 2; - - uint16_t rsvd: 4; - }; - uint16_t hdr; -}__attribute__((packed)) zlib_hdr; - -huff_tree_node* deflate_decode_codes(uint8_t max_code_length, uint16_t alphabet_length, uint16_t lengths[]){ - uint16_t bl_count[max_code_length] = {}; - for (int i = 0; i < max_code_length; i++){ - bl_count[i] = 0; - } - for (int i = 0; i < max_code_length; i++){ - for (int j = 0; j < alphabet_length; j++){ - if (lengths[j] == i){ - bl_count[i]++; - } - } - // printf("%i appears %i times",i,bl_count[i]); - } - uint16_t next_code[max_code_length+1] = {}; - uint16_t code = 0; - bl_count[0] = 0; - for (int bits = 1; bits <= max_code_length; bits++) { - // printf("Bit %i: %i (i-1) appeared %i times",bits, bits-1, bl_count[bits-1]); - code = (code + bl_count[bits-1]) << 1; - next_code[bits] = code; - // printf("Next code [%i] = %i",bits,next_code[bits]); - } - huff_tree_node *root = malloc(sizeof(huff_tree_node)); - for (int i = 0; i < alphabet_length; i++){ - if (lengths[i]){ - huffman_populate(root, next_code[lengths[i]]++, lengths[i], i); - } - } - return root; -} - -#define READ_BITS(from, to, amount, bs, c) do { \ - if (bs + amount > 16){ \ - to = (((uint16_t)from[c+2] << (16-bs)) & ((1 << amount) - 1)) | \ - (((uint16_t)from[c+1] << (8-bs)) & ((1 << amount) - 1)) | \ - (((uint16_t)from[c] >> bs) & ((1 << amount) - 1) ); \ - } else if (bs+amount > 8){ \ - to = (((uint16_t)from[c+1] << (8-bs)) & ((1 << amount) - 1)) | \ - (((uint16_t)from[c] >> bs) & ((1 << amount) - 1) ); \ - } else { \ - to = (((uint16_t)from[c] >> bs) & ((1 << amount) - 1) ); \ - } \ - bs += amount;\ - if (bs > 7){\ - c += (bs/8);\ - bs %= 8;\ - } \ -} while (0) - -uint32_t base_lengths[] = { - 3, 4, 5, 6, 7, 8, 9, 10, //257 - 264 - 11, 13, 15, 17, //265 - 268 - 19, 23, 27, 31, //269 - 273 - 35, 43, 51, 59, //274 - 276 - 67, 83, 99, 115, //278 - 280 - 131, 163, 195, 227, //281 - 284 - 258 //285 -}; - -uint32_t dist_bases[] = { - /*0*/ 1, 2, 3, 4, //0-3 - /*1*/ 5, 7, //4-5 - /*2*/ 9, 13, //6-7 - /*3*/ 17, 25, //8-9 - /*4*/ 33, 49, //10-11 - /*5*/ 65, 97, //12-13 - /*6*/ 129, 193, //14-15 - /*7*/ 257, 385, //16-17 - /*8*/ 513, 769, //18-19 - /*9*/ 1025, 1537, //20-21 - /*10*/ 2049, 3073, //22-23 - /*11*/ 4097, 6145, //24-25 - /*12*/ 8193, 12289, //26-27 - /*13*/ 16385, 24577 //28-29 -}; - -size_t deflate_uncommpressed(deflate_read_ctx *ctx, size_t max_size) { - if (ctx->bs) { - ctx->bs = 0; - ctx->c++; - max_size--; - } - - // printf("Next bytes %x %x %x %x",ctx->bytes[ctx->c],ctx->bytes[ctx->c+1],ctx->bytes[ctx->c+2],ctx->bytes[ctx->c+3]); - - uint16_t len = 0; - uint16_t nlen = 0; - READ_BITS(ctx->bytes, len, 16, ctx->bs, ctx->c); - READ_BITS(ctx->bytes, nlen, 16, ctx->bs, ctx->c); - - // printf("Actual read values %x %x",len, nlen); - - if (len != (uint16_t)(~nlen)) { - printf("Wrong checksum %.16b %.16b %.16b\n", len, nlen, (uint16_t)(~nlen)); - return 0; - } - - ctx->cur_block = len; - printf("Found new block with %x len", len); - - max_size -= 4; - - len = min(len,max_size); - - // printf("Reading %x bytes from uncompressed deflate block",len); - - memcpy(ctx->output_buf + ctx->out_cursor, &ctx->bytes[ctx->c], len); - ctx->c += len; - ctx->out_cursor += len; - - return len; -} - -bool deflate_block(huff_tree_node *litlen_tree, huff_tree_node *dist_tree, deflate_read_ctx *ctx){ - huff_tree_node *tree_root = litlen_tree; - uint16_t val = 0; - while (val != 0x100){ - uint8_t next_bit = 0; - READ_BITS(ctx->bytes, next_bit, 1, ctx->bs, ctx->c); - // printf("%x",next_bit); - tree_root = huffman_traverse(tree_root, next_bit); - if (!tree_root) { - printf("DEFLATE ERROR: no tree found"); - return false; - } - if (!tree_root->left && !tree_root->right){ - val = tree_root->entry; - if (val < 0x100){ - ctx->output_buf[ctx->out_cursor] = (val & 0xFF); - ctx->out_cursor++; - } else if (val == 0x100){ - break; - } else { - uint8_t extra = 0; - if (val > 264 && val < 285) - extra = (val-261)/4; - uint16_t extra_val = 0; - READ_BITS(ctx->bytes, extra_val, extra, ctx->bs, ctx->c); - uint16_t length = base_lengths[val - 257] + extra_val; - huff_tree_node *dist_node = dist_tree; - while (dist_node->left || dist_node->right){ - READ_BITS(ctx->bytes, next_bit, 1, ctx->bs, ctx->c); - dist_node = huffman_traverse(dist_node, next_bit); - if (!dist_node){ - printf("DEFLATE ERROR: no tree found"); - return false; - } - } - uint16_t dist_base = dist_node->entry; - uint8_t extra_dist = 0; - uint16_t extra_dist_val = 0; - if (dist_base > 3){ - extra_dist = (dist_base-2)/2; - READ_BITS(ctx->bytes, extra_dist_val, extra_dist, ctx->bs, ctx->c); - } - uint32_t distance = dist_bases[dist_base] + extra_dist_val; - memcpy(ctx->output_buf + ctx->out_cursor, ctx->output_buf - distance + ctx->out_cursor, length); - ctx->out_cursor += length; - } - tree_root = litlen_tree; - } - } - return true; -} - -uint16_t lit_lengths[288]; - -size_t deflate_decode(void* ptr, size_t size, deflate_read_ctx *ctx){ - if (ctx->cur_block > 0){//TODO: this is no longer needed since we put IDATs together - // printf("Continuation of previous block %i %x",size, size); - size_t amount = min(size,ctx->cur_block); - memcpy(ctx->output_buf + ctx->out_cursor, ptr, amount); - ctx->out_cursor += amount; - ctx->cur_block -= amount; - printf("Reduced current block by %x to %x",amount, ctx->cur_block); - if (amount >= size || ctx->final_block) - return size; - ptr += amount; - size -= amount; - } else { - zlib_hdr hdr = *(zlib_hdr*)ptr; - if (hdr.cm != 8){ - printf("Error. Non-DEFLATE block"); - return 0; - } - ptr += sizeof(zlib_hdr); - size -= sizeof(zlib_hdr); - } - uintptr_t p = (uintptr_t)ptr; - - bool final = false; - - ctx->bytes = (uint8_t*)p; - ctx->c = 0; - ctx->bs = 0; - - while (!final){ - uint8_t hclen = 0;//4 - uint8_t hdist = 0;//5 - uint8_t hlit = 0;//5 - uint8_t btype = 0;//2 - READ_BITS(ctx->bytes, final, 1, ctx->bs, ctx->c); - READ_BITS(ctx->bytes, btype, 2, ctx->bs, ctx->c); - - ctx->final_block = final; - - if (btype == 0b00){ - size_t read_size = deflate_uncommpressed(ctx, size); - // printf("Uncompressed block read %x out of a max total %x",read_size, max_size); - if (!read_size){ - return 0; - } - ctx->cur_block -= read_size; - printf("Got new block and read %x with %x remaining",read_size, ctx->cur_block); - if (final || ctx->cur_block) return ctx->out_cursor; - continue; - } - - READ_BITS(ctx->bytes, hlit, 5, ctx->bs, ctx->c); - READ_BITS(ctx->bytes, hdist, 5, ctx->bs, ctx->c); - READ_BITS(ctx->bytes, hclen, 4, ctx->bs, ctx->c); - - huff_tree_node *litlen_tree, *dist_tree; - if (btype == 0b10){//Dynamic huffman - // printf("DEFLATE DYNAMIC HEADER. LAST? %i. Type %i. HLIT %i, HDIST %i, HCLEN %i", final, btype, hlit, hdist, hclen); - - uint8_t code_order[19] = {16, 17, 18, 0, 8, 7, 9, 6, 10, 5, 11, 4, 12, 3, 13, 2, 14, 1, 15}; - uint16_t permuted[19] = {}; - for (uint8_t i = 0; i < hclen+4; i++){ - READ_BITS(ctx->bytes, permuted[code_order[i]], 3, ctx->bs, ctx->c); - } - huff_tree_node *huff_decode_nodes = deflate_decode_codes(8, 19, permuted); - - // huffman_viz(huff_decode_nodes, 0, 0); - - int tree_data_size = hlit + hdist + 258; - - // printf("Expecting to read %i",tree_data_size); - - huff_tree_node *tree_root = huff_decode_nodes; - - uint16_t *full_huffman = malloc(sizeof(uint16_t) * tree_data_size); - - uint16_t last_code_len = 0; - - for (int i = 0; i < tree_data_size;){ - uint8_t next_bit = 0; - READ_BITS(ctx->bytes, next_bit, 1, ctx->bs, ctx->c); - tree_root = huffman_traverse(tree_root, next_bit); - if (!tree_root) { - printf("DEFLATE ERROR: no tree found"); - return 0; - } - if (!tree_root->left && !tree_root->right){ - uint8_t extra = 0; - switch (tree_root->entry){ - case 16: - READ_BITS(ctx->bytes, extra, 2, ctx->bs, ctx->c); - extra += 3; - for (int j = 0; j < extra; j++) - full_huffman[i+j] = last_code_len; - break; - case 17: - READ_BITS(ctx->bytes, extra, 3, ctx->bs, ctx->c); - extra += 3; - for (int j = 0; j < extra; j++) - full_huffman[i+j] = 0; - break; - case 18: - READ_BITS(ctx->bytes, extra, 7, ctx->bs, ctx->c); - extra += 11; - for (int j = 0; j < extra; j++) - full_huffman[i+j] = 0; - break; - default: - full_huffman[i] = tree_root->entry; - last_code_len = tree_root->entry; - break; - } - tree_root = huff_decode_nodes; - if (extra) - i+= extra; - else i++; - } - } - huffman_free(huff_decode_nodes); - - // printf("**** LITERAL/LENGTH ****"); - litlen_tree = deflate_decode_codes(15, hlit + 257, full_huffman); - // huffman_viz(litlen_tree, 0, 0); - - // printf("**** DISTANCE ****"); - dist_tree = deflate_decode_codes(15, hdist + 1, full_huffman + hlit + 257); - - // huffman_viz(dist_tree, 0, 0); - // printf("**** WOO ****"); - - free_sized(full_huffman, tree_data_size * sizeof(uint16_t)); - - tree_root = litlen_tree; - } else if (btype == 0b01){//Static huffman - if (lit_lengths[0] == 0){ - int l = 0; - for (; l <= 143; l++) - lit_lengths[l] = 8; - for (; l <= 255; l++) - lit_lengths[l] = 9; - for (; l <= 279; l++) - lit_lengths[l] = 7; - for (; l <= 287; l++) - lit_lengths[l] = 8; - } - - litlen_tree = deflate_decode_codes(15, 288, lit_lengths); - - uint16_t dist_lengths[32] = {}; - for (int i = 0; i < 32; i++) dist_lengths[i] = i; - dist_tree = deflate_decode_codes(5, 32, dist_lengths); - // printf("**** LITERAL/LENGTH ****"); - // huffman_viz(litlen_tree, 0, 0); - // printf("**** DISTANCE ****"); - // huffman_viz(dist_tree, 0, 0); - } else { - printf("Unknown btype %.3b",btype); - return 0; - } - - if (!deflate_block(litlen_tree, dist_tree, ctx)){ - huffman_free(litlen_tree); - huffman_free(dist_tree); - return 0; - } - - huffman_free(litlen_tree); - huffman_free(dist_tree); - } - - // printf("Wrote a total of %i bytes",out_cursor); - - return ctx->out_cursor; -} \ No newline at end of file diff --git a/shared/compression/deflate.h b/shared/compression/deflate.h deleted file mode 100644 index 621b2a92..00000000 --- a/shared/compression/deflate.h +++ /dev/null @@ -1,15 +0,0 @@ -#pragma once - -#include "types.h" - -typedef struct { - uint8_t *bytes; - uint8_t bs; - int c; - uintptr_t out_cursor; - uint8_t *output_buf; - bool final_block; - size_t cur_block; -} deflate_read_ctx; - -size_t deflate_decode(void* ptr, size_t size, deflate_read_ctx *ctx); \ No newline at end of file diff --git a/shared/compression/huffman.c b/shared/compression/huffman.c deleted file mode 100644 index 062d957b..00000000 --- a/shared/compression/huffman.c +++ /dev/null @@ -1,116 +0,0 @@ -#include "huffman.h" -#include "syscalls/syscalls.h" -#include "math/math.h" - -int* huff_count_entries(sizedptr input){ - int *entries = malloc(sizeof(int) * 257); - uint8_t *buf = (uint8_t*)input.ptr; - for (size_t i = 0; i < input.size; i++){ - entries[buf[i]]++; - } - int count = 0; - for (int i = 0; i < 256; i++){ - if (entries[i]){ count++; printf("%c = %i", i, entries[i]); } - } - entries[256] = count; - printf("%i unique bytes", entries[256]); - return entries; -} - -void huffman_populate(huff_tree_node *root, uint64_t code, uint8_t code_len, uint16_t value){ - if (code_len == 0){ - if (root->entry) printf("HUFFMAN TREE ERROR overwriting value %i with %i",root->entry,value); - root->entry = value; - if (root->right || root->left) printf("[HUFFMAN TREE ERROR] ending at non-leaf node for value %i. L %x R %x ROOT %x",value,root->left,root->right,root); - return; - } - bool right = ((code >> (code_len-1)) & 1); - huff_tree_node *child = right ? root->right : root->left; - if (!child){ - child = (huff_tree_node*)malloc(sizeof(huff_tree_node)); - if (right) - root->right = child; - else - root->left = child; - } - huffman_populate(child, code, code_len-1, value); -} - -void huffman_free(huff_tree_node *root){ - if (root->right) huffman_free(root->right); - if (root->left) huffman_free(root->left); - free_sized(root, sizeof(huff_tree_node)); -} - -static char *pad = " "; - -void huffman_viz(huff_tree_node *root, uint8_t depth, uint64_t val){ - if (!root->left && !root->right) printf("%s Leaf node %i = %b", pad + (63-depth), root->entry, val); - else { - if (root->entry) printf("[HUFFMAN TREE ERROR] non-leaf node has value %i",root->entry); - if (root->left) huffman_viz(root->left, depth+1, (val << 1) | 0); - if (root->right) huffman_viz(root->right, depth+1, (val << 1) | 1); - } -} - -int node_index = 0; - -#define TO_READABLE(c) (c >= 'a' && c <= 'z' ? c : '?') - -huff_tree_node* huff_make_node(huff_tree_node *l, huff_tree_node *r){ - huff_tree_node *node = malloc(sizeof(huff_tree_node));//TODO: no need for an alloc every time, we know the max number of nodes - node->left = l; - node->right = r; - node->depth = max(l->depth, r->depth) + 1; - node->entry = l->entry + r->entry; - node->index = node_index++; - printf("%i = %i\n-> l = %i %c - %i\n-> r = %i %c - %i", node->index, node->entry, l->index, TO_READABLE(l->byte), l->entry, r->index, TO_READABLE(r->byte), r->entry); - return node; -} - -void huff_calc_code(huff_tree_node *root, uint8_t value, uint8_t depth){ - bool leaf = true; - if (root->left){ - leaf = false; - huff_calc_code(root->left, value << 1, depth+1); - } - if (root->right){ - leaf = false; - value |= 1; - huff_calc_code(root->right, value << 1, depth+1); - } - if (leaf) printf("%c = [%b]. Depth %i",root->byte, value >> 1, depth); -} - -huff_tree_node* huff_build_tree(int entries[257]){ - int count = entries[256]; - p_queue_t *heap = p_queue_create((count * 2 + (count % 2))); - int index = 0; - for (int i = 0; i < count; i++){ - while (!entries[index]) index++; - if (index < 256){ - huff_tree_node *node = malloc(sizeof(huff_tree_node));//TODO: no need for an alloc every time, we know the max number of nodes - node->entry = entries[index]; - node->byte = index; - node->index = node_index++; - p_queue_insert(heap, node, entries[index]); - index++; - } - } - while (heap->size > 1){ - huff_tree_node *l = p_queue_pop(heap); - huff_tree_node *r = p_queue_pop(heap); - huff_tree_node *root = huff_make_node(l, r); - p_queue_insert(heap, root, root->entry); - } - - huff_tree_node *root = p_queue_pop(heap); - - return root; -} - -void huffman_encode(sizedptr input, sizedptr output){ - int* entries = huff_count_entries(input); - huff_tree_node *root = huff_build_tree(entries); - huff_calc_code(root, 0, 0); -} \ No newline at end of file diff --git a/shared/compression/huffman.h b/shared/compression/huffman.h deleted file mode 100644 index 69e59f43..00000000 --- a/shared/compression/huffman.h +++ /dev/null @@ -1,25 +0,0 @@ -#pragma once - -#include "types.h" -#include "data_struct/p_queue.h" - -/* - This compression algorithm is (very experimental). - It can only encode byte values, and is not optimized in the slightest. -*/ - -typedef struct huff_tree_node { - struct huff_tree_node *left, *right; - uint16_t entry; - uint8_t depth;//DEBUG - char byte;//DEBUG - int index;//DEBUG -} huff_tree_node; - -void huffman_encode(sizedptr input, sizedptr output); -void huffman_populate(huff_tree_node *root, uint64_t code, uint8_t code_len, uint16_t value); -void huffman_viz(huff_tree_node *root, uint8_t depth, uint64_t val); -static inline huff_tree_node *huffman_traverse(huff_tree_node *root, uint8_t bit){ - return (bit & 1) ? root->right : root->left; -} -void huffman_free(huff_tree_node *root); \ No newline at end of file diff --git a/shared/data/csv.c b/shared/data/csv.c deleted file mode 100644 index d221430d..00000000 --- a/shared/data/csv.c +++ /dev/null @@ -1,35 +0,0 @@ -#include "csv.h" -#include "scanner/scanner.h" -#include "tokenizer/tokenizer.h" -#include "helpers/token_stream.h" - -void read_csv(string_slice slice, csv_handler on_val){ - Scanner s = scanner_make(slice.data, slice.length); - Tokenizer tk = tokenizer_make(&s); - tk.comment_type = TOKENIZER_COMMENT_TYPE_HASH; - tk.skip_type_check = false; - TokenStream ts; - ts_init(&ts, &tk); - - Token t; - while (ts_next(&ts, &t)) { - if (!t.kind) break; - - switch (t.kind) { - case TOK_IDENTIFIER: - case TOK_STRING: - case TOK_CONST: - case TOK_NUMBER: - { - on_val(token_to_slice(t)); - } break; - case TOK_COMMA: { - - } break; - default: { - print("Wrong symbol %v of type %i",token_to_slice(t),t.kind); - return; - } - } - } -} \ No newline at end of file diff --git a/shared/data/csv.h b/shared/data/csv.h deleted file mode 100644 index 5679a7a5..00000000 --- a/shared/data/csv.h +++ /dev/null @@ -1,7 +0,0 @@ -#pragma once - -#include "std/string_slice.h" - -typedef void (*csv_handler)(string_slice value); - -void read_csv(string_slice slice, csv_handler on_val); \ No newline at end of file diff --git a/shared/data/helpers/token_stream.c b/shared/data/helpers/token_stream.c deleted file mode 100644 index 2d6c3c77..00000000 --- a/shared/data/helpers/token_stream.c +++ /dev/null @@ -1,118 +0,0 @@ -#include "token_stream.h" - -void ts_init(TokenStream *ts, Tokenizer *tz) { - ts->tz = tz; - ts->has_cur = false; -} - -bool ts_peek(TokenStream *ts, Token *t) { - if (!ts->has_cur) { - if (!tokenizer_next(ts->tz,&ts->cur)) return false; - ts->has_cur = true; - } - if (t) *t = ts->cur; - return true; -} - -bool ts_next(TokenStream *ts, Token *t) { - if (ts->has_cur) { - if (t) *t = ts->cur; - ts->has_cur = false; - return true; - } - return tokenizer_next(ts->tz, t); -} - -bool ts_expect(TokenStream *ts, TokenKind k, Token *out) { - Token t; - if (!ts_next(ts, &t)) return false; - if (t.kind != k) return false; - if (out) *out = t; - return true; -} - -bool ts_expect_operator(TokenStream *ts, const char *op) { - Token t; - if (!ts_next(ts, &t)) return false; - return token_is_operator_token(&t, op); -} - -bool ts_expect_identifier(TokenStream *ts, string *out) { - Token t; - if (!ts_next(ts, &t)) return false; - if (t.kind != TOK_IDENTIFIER) return false; - if (out) *out = string_from_literal_length(t.start, t.length); - return true; -} - -bool ts_expect_double(TokenStream *ts,double *out_double) { - Token a, b; - if (!ts_peek(ts, &a))return false; - - if (a.kind == TOK_OPERATOR && token_is_operator_token(&a, "-")) { - ts_next(ts, &a); - if (!ts_peek(ts, &b)) return false; - if (!token_is_number(&b)) return false; - ts_next(ts, &b); - - string merged; - if (!token_merge_negative_number(&a, &b, &merged)) return false; - - Token tmp; - tmp.kind = TOK_NUMBER; - tmp.start=merged.data; - tmp.length = merged.length; - tmp.pos = 0; - - bool ok = token_to_double(&tmp, out_double); - string_free(merged); - return ok; - } - - ts_next(ts, &a); - if (!token_is_number(&a)) return false; - return token_to_double(&a, out_double); -} - -bool ts_expect_int(TokenStream *ts, int64_t *out_int) { - Token a, b; - - if (!ts_peek(ts, &a)) return false; - - if (a.kind == TOK_OPERATOR && token_is_operator_token(&a, "-")) { - ts_next(ts, &a); - - if (!ts_peek(ts, &b)) return false; - if (!token_is_number(&b)) return false; - - ts_next(ts, &b); - - string merged; - if (!token_merge_negative_number(&a, &b, &merged)) return false; - - Token tmp; - tmp.kind = TOK_NUMBER; - tmp.start = merged.data; - tmp.length = merged.length; - tmp.pos = a.pos; - - int64_t iv; - bool ok = token_to_int64(&tmp, &iv); - - string_free(merged); - if (!ok) return false; - - *out_int = iv; - return true; - } - - ts_next(ts, &a); - if (!token_is_number(&a)) return false; - - for (uint32_t i = 0; i < a.length; i++) { - char c = a.start[i]; - if (c == '.' || c == 'e' || c == 'E') return false; - } - - return token_to_int64(&a, out_int); -} \ No newline at end of file diff --git a/shared/data/helpers/token_stream.h b/shared/data/helpers/token_stream.h deleted file mode 100644 index 016fc5ff..00000000 --- a/shared/data/helpers/token_stream.h +++ /dev/null @@ -1,23 +0,0 @@ -#pragma once - -#include "types.h" -#include "std/string.h" -#include "std/std.h" -#include "data/tokenizer/tokenizer.h" -#include "token_utils.h" - -typedef struct { - Tokenizer *tz; - Token cur; - bool has_cur; -} TokenStream; - -void ts_init(TokenStream *ts, Tokenizer *tz); -bool ts_peek(TokenStream *ts, Token *t); -bool ts_next(TokenStream *ts, Token *t); - -bool ts_expect(TokenStream *ts, TokenKind k, Token *out); -bool ts_expect_operator(TokenStream *ts, const char *op); -bool ts_expect_identifier(TokenStream *ts, string *out); -bool ts_expect_double(TokenStream *ts, double *out_double); -bool ts_expect_int(TokenStream *ts, int64_t *out_int); \ No newline at end of file diff --git a/shared/data/helpers/token_utils.c b/shared/data/helpers/token_utils.c deleted file mode 100644 index 40044c93..00000000 --- a/shared/data/helpers/token_utils.c +++ /dev/null @@ -1,127 +0,0 @@ -#include "token_utils.h" -#include "std/std.h" - -bool token_is_number(const Token *t) { - return t && t->kind == TOK_NUMBER; -} - -bool token_is_operator_token(const Token *t, const char *op) { - if (!t || t->kind != TOK_OPERATOR) return false; - uint32_t n = (uint32_t)strlen(op); - if (t->length != n) return false; - return strncmp(t->start, op, n) == 0; -} - -bool token_is_negative_number(const Token *op, const Token *num) { - if (!op || !num) return false; - if (!token_is_operator_token(op, "-")) return false; - return token_is_number(num); -} - -bool token_merge_negative_number(const Token *op, const Token *num, string *out) { - if (!token_is_negative_number(op, num)) return false; - *out = string_repeat('\0', 0); - string_append_bytes(out, "-", 1); - string_append_bytes(out, num->start,num->length); - return true; -} - -bool token_to_int64(const Token *t, int64_t *out) { - if (!t || !token_is_number(t)) return false; - string tmp = string_from_literal_length(t->start, t->length); - int64_t v = parse_int64(tmp.data, tmp.length); - string_free(tmp); - *out = v; - return true; -} - -bool token_to_uint64(const Token *t, uint64_t *out) { - if (!t || !token_is_number(t)) return false; - string tmp = string_from_literal_length(t->start, t->length); - uint64_t v= parse_int_u64(tmp.data, tmp.length); - string_free(tmp); - *out = v; - return true; -} - -static bool parse_double_literal(const char *buf, uint32_t len, double *out) { - if (!buf || !len) return false; - - uint32_t pos = 0; - if (buf[pos] < '0' || buf[pos] > '9') return false; - - double ip = 0.0; - while (pos < len) { - char c = buf[pos]; - if (c < '0' || c > '9') break; - ip = ip * 10.0 + (double)(c - '0'); - pos++; - } - - double fp = 0.0; - if (pos < len && buf[pos] == '.') { - uint32_t p2 = pos + 1; - if (p2 < len && buf[p2] >= '0' && buf[p2] <= '9') { - pos = p2; - double base = 0.1; - while (pos < len) { - char c = buf[pos]; - if (c < '0' || c > '9') break; - - fp += (double)(c - '0') * base; - base *= 0.1; - pos++; - } - } - } - - int exp_val = 0; - if (pos < len && (buf[pos] == 'e' || buf[pos] == 'E')) { - pos++; - if (pos >= len) return false; - - bool exp_neg = false; - if (buf[pos] == '+' || buf[pos] == '-') { - if (buf[pos] == '-') exp_neg = true; - pos++; - if (pos >= len) return false; - } - - if (buf[pos] < '0' || buf[pos] > '9') return false; - - while (pos < len) { - char c = buf[pos]; - if (c < '0' || c > '9') break; - exp_val = exp_val * 10 + (c - '0'); - pos++; - } - if (exp_neg) exp_val = -exp_val; - } - - if (pos != len) return false; - - double val = ip + fp; - if (exp_val != 0) { - double y = 1.0; - if (exp_val > 0) { - while (exp_val--) y *= 10.0; - } else { - while (exp_val++) y /= 10.0; - } - val *= y; - } - - *out = val; - return true; -} - -bool token_to_double(const Token *t, double *out) { - if (!t || !token_is_number(t)) return false; - string tmp = string_from_literal_length(t->start, t->length); - double v = 0.0; - bool ok = parse_double_literal(tmp.data, tmp.length, &v); - string_free(tmp); - if (!ok) return false; - *out = v; - return true; -} \ No newline at end of file diff --git a/shared/data/helpers/token_utils.h b/shared/data/helpers/token_utils.h deleted file mode 100644 index 143b0853..00000000 --- a/shared/data/helpers/token_utils.h +++ /dev/null @@ -1,14 +0,0 @@ -#pragma once - -#include "types.h" -#include "std/string.h" -#include "data/tokenizer/tokenizer.h" - -bool token_is_number(const Token *t); -bool token_is_operator_token(const Token *t, const char *op); -bool token_is_negative_number(const Token *op, const Token *num); -bool token_merge_negative_number(const Token *op, const Token *num, string *out); - -bool token_to_int64(const Token *t, int64_t *out); -bool token_to_uint64(const Token *t, uint64_t *out); -bool token_to_double(const Token *t, double *out); \ No newline at end of file diff --git a/shared/data/json.c b/shared/data/json.c deleted file mode 100644 index d962ed49..00000000 --- a/shared/data/json.c +++ /dev/null @@ -1,707 +0,0 @@ -#include "json.h" -#include "std/std.h" -#include "std/string.h" -#include "syscalls/syscalls.h" -#include "data/scanner/scanner.h" -#include "data/tokenizer/tokenizer.h" -#include "helpers/token_stream.h" -#include "helpers/token_utils.h" - -static JsonError json_parse_value(TokenStream *ts, JsonValue **out); - -static JsonError json_parse_string_token(Token *tok, JsonValue **out) { - const char *buf = tok->start; - uint32_t len = tok->length; - if (len < 2 || buf[0] != '"' || buf[len - 1] != '"') return JSON_ERR_INVALID; - - uint32_t pos = 1; - string s = string_repeat('\0', 0); - - while (pos < len) { - char c = buf[pos++]; - if (c == '"') { - JsonValue *v = malloc(sizeof(JsonValue)); - if (!v) { - free_sized(s.data, s.mem_length); - return JSON_ERR_OOM; - } - v->kind = JSON_STRING; - v->u.string = s; - *out = v; - return JSON_OK; - } - if (c == '\\') { - if (pos >= len) { - free_sized(s.data, s.mem_length); - return JSON_ERR_INVALID; - } - char e = buf[pos++]; - char r = e; - if (e == 'b') r = '\b'; - else if (e == 'f') r = '\f'; - else if (e == 'n') r = '\n'; - else if (e == 'r') r = '\r'; - else if (e == 't') r = '\t'; - else if (!(e == '"' || e == '\\' || e == '/')) { - free_sized(s.data, s.mem_length); - return JSON_ERR_INVALID; - } - string_append_bytes(&s, &r, 1); - continue; - } - string_append_bytes(&s, &c, 1); - } - - free_sized(s.data, s.mem_length); - return JSON_ERR_INVALID; -} - -static JsonError json_parse_number_tokens(TokenStream *ts, JsonValue **out){ - Token a, b; - if (!ts_peek(ts, &a)) { - if (ts->tz->failed) return JSON_ERR_INVALID; - return JSON_ERR_INVALID; - } - - bool negative = false; - Token num; - - if (a.kind == TOK_OPERATOR && token_is_operator_token(&a, "-")) { - ts_next(ts, &a); - if (!ts_next(ts, &b)) { - if (ts->tz->failed)return JSON_ERR_INVALID; - return JSON_ERR_INVALID; - } - if (!token_is_number(&b)) return JSON_ERR_INVALID; - negative = true; - num = b; - } else { - if (!ts_next(ts, &a)) { - if (ts->tz->failed) return JSON_ERR_INVALID; - return JSON_ERR_INVALID; - } - if (!token_is_number(&a)) return JSON_ERR_INVALID; - num = a; - } - - bool is_int = true; - for (uint32_t i = 0; i < num.length; i++) { - char c = num.start[i]; - if (c == '.' || c == 'e' || c == 'E') { - is_int = false; - break; - } - } - - if (is_int) { - int64_t iv; - if (!token_to_int64(&num, &iv)) return JSON_ERR_INVALID; - if (negative) iv =-iv; - JsonValue *v = malloc(sizeof(JsonValue)); - if (!v) return JSON_ERR_OOM; - v->kind = JSON_INT; - v->u.integer = iv; - *out = v; - return JSON_OK; - } - - double d; - if (!token_to_double(&num, &d)) return JSON_ERR_INVALID; - if (negative) d = -d; - JsonValue *v = malloc(sizeof(JsonValue)); - if (!v) return JSON_ERR_OOM; - v->kind = JSON_DOUBLE; - v->u.real = d; - *out = v; - return JSON_OK; -} - -static JsonError json_parse_array(TokenStream *ts, JsonValue **out) { - Token t; - if (!ts_expect(ts, TOK_LBRACKET, &t)) return JSON_ERR_INVALID; - - JsonValue *arr = malloc(sizeof(JsonValue)); - if (!arr) return JSON_ERR_OOM; - arr->kind = JSON_ARRAY; - arr->u.array.items = 0; - arr->u.array.count = 0; - - Token p; - if (!ts_peek(ts, &p)) { - json_free(arr); - if (ts->tz->failed) return JSON_ERR_INVALID; - return JSON_ERR_INVALID; - } - - if (p.kind == TOK_RBRACKET) { - ts_next(ts, &p); - *out = arr; - return JSON_OK; - } - - for (;;) { - JsonValue *elem = 0; - JsonError e = json_parse_value(ts, &elem); - if (e != JSON_OK) { - json_free(arr); - return e; - } - - uint32_t n = arr->u.array.count; - JsonValue **tmp = malloc((n + 1) * sizeof(JsonValue *)); - if (!tmp) { - json_free(arr); - json_free(elem); - return JSON_ERR_OOM; - } - - for (uint32_t i = 0; i < n; i++) tmp[i] = arr->u.array.items[i]; - tmp[n] = elem; - - if (arr->u.array.items) free_sized(arr->u.array.items, n * sizeof(JsonValue *)); - arr->u.array.items = tmp; - arr->u.array.count = n + 1; - - if (!ts_peek(ts, &p)) { - json_free(arr); - if (ts->tz->failed) return JSON_ERR_INVALID; - return JSON_ERR_INVALID; - } - - if (p.kind == TOK_RBRACKET) { - ts_next(ts, &p); - break; - } - - if (!ts_expect(ts, TOK_COMMA, &t)) { - json_free(arr); - if (ts->tz->failed) return JSON_ERR_INVALID; - return JSON_ERR_INVALID; - } - } - - *out = arr; - return JSON_OK; -} - -static JsonError json_parse_object(TokenStream *ts, JsonValue **out) { - Token t; - if (!ts_expect(ts, TOK_LBRACE, &t)) return JSON_ERR_INVALID; - - JsonValue *obj =malloc(sizeof(JsonValue)); - if (!obj) return JSON_ERR_OOM; - obj->kind = JSON_OBJECT; - obj->u.object.pairs = 0; - obj->u.object.count = 0; - - Token p; - if (!ts_peek(ts, &p)) { - json_free(obj); - if (ts->tz->failed) return JSON_ERR_INVALID; - return JSON_ERR_INVALID; - } - - if (p.kind == TOK_RBRACE) { - ts_next(ts, &p); - *out = obj; - return JSON_OK; - } - - for (;;) { - Token keytok; - if (!ts_expect(ts, TOK_STRING, &keytok)) { - json_free(obj); - if (ts->tz->failed) return JSON_ERR_INVALID; - return JSON_ERR_INVALID; - } - - if (keytok.length < 2) { - json_free(obj); - return JSON_ERR_INVALID; - } - - string key = string_from_literal_length(keytok.start + 1, keytok.length - 2); - - if (!ts_expect(ts, TOK_COLON, &t)) { - free_sized(key.data, key.mem_length); - json_free(obj); - if (ts->tz->failed) return JSON_ERR_INVALID; - return JSON_ERR_INVALID; - } - - JsonValue *val = 0; - JsonError e = json_parse_value(ts, &val); - if (e != JSON_OK) { - free_sized(key.data, key.mem_length); - json_free(obj); - return e; - } - - uint32_t n = obj->u.object.count; - JsonPair *tmp = malloc((n + 1) * sizeof(JsonPair)); - if (!tmp) { - free_sized(key.data, key.mem_length); - json_free(val); - json_free(obj); - return JSON_ERR_OOM; - } - - for (uint32_t i = 0; i < n; i++) tmp[i] = obj->u.object.pairs[i]; - tmp[n].key = key; - tmp[n].value = val; - - if (obj->u.object.pairs) free_sized(obj->u.object.pairs, n * sizeof(JsonPair)); - obj->u.object.pairs = tmp; - obj->u.object.count = n + 1; - - if (!ts_peek(ts, &p)) { - json_free(obj); - if (ts->tz->failed) return JSON_ERR_INVALID; - return JSON_ERR_INVALID; - } - - if (p.kind == TOK_RBRACE) { - ts_next(ts, &p); - break; - } - - if (!ts_expect(ts, TOK_COMMA, &t)) { - json_free(obj); - if (ts->tz->failed) return JSON_ERR_INVALID; - return JSON_ERR_INVALID; - } - } - - *out = obj; - return JSON_OK; -} - -static JsonError json_parse_value(TokenStream *ts, JsonValue **out) { - Token t; - if (!ts_peek(ts, &t)) { - if (ts->tz->failed) return JSON_ERR_INVALID; - return JSON_ERR_INVALID; - } - - if (t.kind == TOK_STRING) { - ts_next(ts,&t); - return json_parse_string_token(&t, out); - } - - if (t.kind == TOK_NUMBER || (t.kind == TOK_OPERATOR && token_is_operator_token(&t, "-"))) { - return json_parse_number_tokens(ts, out); - } - - if (t.kind == TOK_LBRACE) return json_parse_object(ts, out); - if (t.kind == TOK_LBRACKET) return json_parse_array(ts, out); - - if (t.kind == TOK_IDENTIFIER && t.length == 4 && strncmp(t.start, "true", 4) == 0) { - ts_next(ts, &t); - JsonValue *v = malloc(sizeof(JsonValue)); - if (!v) return JSON_ERR_OOM; - v->kind = JSON_BOOL; - v->u.boolean = true; - *out = v; - return JSON_OK; - } - - if (t.kind == TOK_IDENTIFIER && t.length ==5 &&strncmp(t.start, "false", 5) == 0) { - ts_next(ts, &t); - JsonValue *v = malloc(sizeof(JsonValue)); - if (!v) return JSON_ERR_OOM; - v->kind = JSON_BOOL; - v->u.boolean = false; - *out = v; - return JSON_OK; - } - - if (t.kind == TOK_IDENTIFIER && t.length == 4 && - strncmp(t.start, "null", 4) == 0) { - ts_next(ts, &t); - JsonValue *v = malloc(sizeof(JsonValue)); - if (!v) return JSON_ERR_OOM; - v->kind = JSON_NULL; - *out = v; - return JSON_OK; - } - - return JSON_ERR_INVALID; -} - -JsonError json_parse(const char *buf, uint32_t len, JsonValue **out) { - Scanner s = scanner_make(buf, len); - Tokenizer tz = tokenizer_make(&s); - TokenStream ts; - ts_init(&ts, &tz); - - JsonError e =json_parse_value(&ts, out); - if (e != JSON_OK) return e; - - Token t; - if (!ts_peek(&ts, &t)) { - json_free(*out); - return JSON_ERR_INVALID; - } - if (t.kind != TOK_EOF) { - json_free(*out); - return JSON_ERR_INVALID; - } - - return JSON_OK; -} - -void json_free(JsonValue *v) { - if (!v) return; - - if (v->kind == JSON_STRING) { - free_sized(v->u.string.data, v->u.string.mem_length); - } else if (v->kind == JSON_ARRAY) { - for (uint32_t i = 0; i < v->u.array.count; i++) json_free(v->u.array.items[i]); - if (v->u.array.items) - free_sized(v->u.array.items, v->u.array.count * sizeof(JsonValue *)); - } else if (v->kind == JSON_OBJECT) { - for (uint32_t i = 0; i < v->u.object.count; i++) { - free_sized(v->u.object.pairs[i].key.data, v->u.object.pairs[i].key.mem_length); - json_free(v->u.object.pairs[i].value); - } - if (v->u.object.pairs) - free_sized(v->u.object.pairs, v->u.object.count * sizeof(JsonPair)); - } - - free_sized(v, sizeof(JsonValue)); -} - -bool json_get_bool(const JsonValue *v, bool *out) { - if (!v || v->kind != JSON_BOOL) return false; - *out = v->u.boolean; - return true; -} - -bool json_get_int(const JsonValue *v, int64_t *out) { - if (!v || v->kind != JSON_INT) return false; - *out = v->u.integer; - return true; -} - -bool json_get_double(const JsonValue *v, double *out) { - if (!v || v->kind != JSON_DOUBLE) return false; - *out = v->u.real; - return true; -} - -bool json_get_string(const JsonValue *v, string *out) { - if (!v || v->kind != JSON_STRING) return false; - *out = v->u.string; - return true; -} - -bool json_get_number_as_double(const JsonValue *v, double *out) { - if (!v) return false; - if (v->kind == JSON_DOUBLE) { - *out = v->u.real; - return true; - } - if (v->kind == JSON_INT) { - *out = (double)v->u.integer; - return true; - } - return false; -} - -uint32_t json_array_size(const JsonValue *v) { - if (!v || v->kind != JSON_ARRAY) return 0; - return v->u.array.count; -} - -JsonValue *json_array_get(const JsonValue *v, uint32_t index) { - if (!v || v->kind != JSON_ARRAY) return 0; - if (index >= v->u.array.count) return 0; - return v->u.array.items[index]; -} - -JsonValue *json_obj_get(const JsonValue *obj, const char *key) { - if (!obj || obj->kind != JSON_OBJECT) return 0; - for (uint32_t i = 0; i < obj->u.object.count; i++) { - if (strcmp(obj->u.object.pairs[i].key.data, key) == 0) - return obj->u.object.pairs[i].value; - } - return 0; -} - -JsonValue *json_new_null() { - JsonValue *x = malloc(sizeof(JsonValue)); - if (!x) return 0; - x->kind = JSON_NULL; - return x; -} - -JsonValue *json_new_bool(bool v) { - JsonValue *x = malloc(sizeof(JsonValue)); - if (!x) return 0; - x->kind = JSON_BOOL; - x->u.boolean = v; - return x; -} - -JsonValue *json_new_int(int64_t v) { - JsonValue *x = malloc(sizeof(JsonValue)); - if (!x) return 0; - x->kind = JSON_INT; - x->u.integer = v; - return x; -} - -JsonValue *json_new_double(double v) { - JsonValue *x = malloc(sizeof(JsonValue)); - if (!x) return 0; - x->kind = JSON_DOUBLE; - x->u.real = v; - return x; -} - -JsonValue *json_new_string(const char *data, uint32_t len) { - JsonValue *x = malloc(sizeof(JsonValue)); - if (!x) return 0; - x->kind = JSON_STRING; - x->u.string = string_from_literal_length((char *)data, len); - return x; -} - -JsonValue *json_new_array() { - JsonValue *x = malloc(sizeof(JsonValue)); - if (!x) return 0; - x->kind = JSON_ARRAY; - x->u.array.items = 0; - x->u.array.count = 0; - return x; -} - -JsonValue *json_new_object() { - JsonValue *x = malloc(sizeof(JsonValue)); - if (!x) return 0; - x->kind = JSON_OBJECT; - x->u.object.pairs = 0; - x->u.object.count = 0; - return x; -} - -bool json_array_push(JsonValue *arr, JsonValue *elem) { - if (!arr || arr->kind != JSON_ARRAY) return false; - uint32_t n = arr->u.array.count; - JsonValue **tmp = malloc((n + 1) * sizeof(JsonValue *)); - if (!tmp) return false; - for (uint32_t i = 0; i < n; i++) tmp[i] = arr->u.array.items[i]; - tmp[n] = elem; - if (arr->u.array.items) free_sized(arr->u.array.items, n * sizeof(JsonValue *)); - arr->u.array.items = tmp; - arr->u.array.count = n + 1; - return true; -} - -bool json_obj_set(JsonValue *obj, const char *key, JsonValue *value) { - if (!obj || obj->kind != JSON_OBJECT) return false; - - uint32_t klen = strlen(key); - - for (uint32_t i = 0; i < obj->u.object.count; i++) { - if (strcmp(obj->u.object.pairs[i].key.data, key) == 0) { - free_sized(obj->u.object.pairs[i].key.data, obj->u.object.pairs[i].key.mem_length); - obj->u.object.pairs[i].key = string_from_literal_length((char *)key, klen); - json_free(obj->u.object.pairs[i].value); - obj->u.object.pairs[i].value = value; - return true; - } - } - - string sk = string_from_literal_length((char *)key, klen); - uint32_t n = obj->u.object.count; - - JsonPair *tmp = malloc((n + 1) * sizeof(JsonPair)); - if (!tmp) { - free_sized(sk.data, sk.mem_length); - return false; - } - - for (uint32_t i = 0; i < n; i++) tmp[i] = obj->u.object.pairs[i]; - tmp[n].key = sk; - tmp[n].value = value; - - if (obj-> u.object.pairs) free_sized(obj->u.object.pairs, n * sizeof(JsonPair)); - obj->u.object.pairs = tmp; - obj->u.object.count = n + 1; - - return true; -} - -JsonValue *json_clone(const JsonValue *src) { - if (!src) return 0; - - if (src->kind == JSON_NULL) return json_new_null(); - if (src->kind == JSON_BOOL) return json_new_bool(src->u.boolean); - if (src->kind == JSON_INT) return json_new_int(src->u.integer); - if (src->kind == JSON_DOUBLE) return json_new_double(src->u.real); - if (src->kind == JSON_STRING) return json_new_string(src->u.string.data, src->u.string.length); - - if (src->kind == JSON_ARRAY) { - JsonValue *a = json_new_array(); - if (!a) return 0; - for (uint32_t i = 0; i < src->u.array.count; i++) { - JsonValue *c = json_clone(src->u.array.items[i]); - if (!c) { - json_free(a); - return 0; - } - json_array_push(a, c); - } - return a; - } - - if (src->kind == JSON_OBJECT) { - JsonValue *o = json_new_object(); - if (!o) return 0; - for (uint32_t i = 0; i < src->u.object.count; i++) { - JsonPair *p = &src->u.object.pairs[i]; - JsonValue *c = json_clone(p->value); - if (!c) { - json_free(o); - return 0; - } - json_obj_set(o, p->key.data, c); - } - return o; - } - - return 0; -} - -static void serialize_string(const string *s, string *out) { - string_append_bytes(out, "\"", 1); - for (uint32_t i = 0; i < s->length; i++) { - char c = s->data[i]; - if (c == '"' || c == '\\') { - char b[2] = {'\\', c}; - string_append_bytes(out, b, 2); - } else if (c == '\b') string_append_bytes(out, "\\b", 2); - else if (c == '\f') string_append_bytes(out, "\\f", 2); - else if (c == '\n') string_append_bytes(out, "\\n", 2); - else if (c == '\r') string_append_bytes(out, "\\r", 2); - else if (c == '\t') string_append_bytes(out, "\\t", 2); - else string_append_bytes(out, &c, 1); - } - string_append_bytes(out, "\"", 1); -} - -static void serialize_value(const JsonValue *v, string *out, uint32_t indent, uint32_t level); - -static void serialize_array(const JsonValue *v, string *out, uint32_t indent, uint32_t level) { - string_append_bytes(out, "[", 1); - - uint32_t n = v->u.array.count; - if (n == 0) { - string_append_bytes(out, "]", 1); - return; - } - - if (indent) string_append_bytes(out, "\n", 1); - - for (uint32_t i = 0; i < n; i++) { - if (indent) { - for (uint32_t k = 0; k < (level + 1) * indent; k++) string_append_bytes(out, " ", 1); - } - - serialize_value(v->u.array.items[i], out, indent, level + 1); - - if (i + 1 < n) string_append_bytes(out, ",", 1); - if (indent) string_append_bytes(out, "\n", 1); - } - - if (indent) { - for (uint32_t k = 0; k < level * indent; k++) string_append_bytes(out, " ", 1); - } - - string_append_bytes(out, "]", 1); -} - -static void serialize_object(const JsonValue *v, string *out, uint32_t indent, uint32_t level) { - string_append_bytes(out, "{", 1); - - uint32_t n = v->u.object.count; - if (n == 0) { - string_append_bytes(out, "}", 1); - return; - } - - if (indent) string_append_bytes(out, "\n", 1); - - for (uint32_t i = 0; i < n; i++) { - JsonPair *p = &v->u.object.pairs[i]; - - if (indent) { - for (uint32_t k = 0; k < (level + 1) * indent; k++) string_append_bytes(out, " ", 1); - } - - serialize_string(&p->key, out); - string_append_bytes(out, ":", 1); - if (indent) string_append_bytes(out, " ", 1); - - serialize_value(p->value, out, indent, level + 1); - - if (i + 1 < n) string_append_bytes(out, ",", 1); - if (indent) string_append_bytes(out, "\n", 1); - } - - if (indent) { - for (uint32_t k = 0; k < level * indent; k++) string_append_bytes(out, " ", 1); - } - - string_append_bytes(out, "}", 1); -} - -static void serialize_value(const JsonValue *v, string *out, uint32_t indent, uint32_t level) { - if (v->kind == JSON_NULL) { - string_append_bytes(out, "null", 4); - return; - } - - if (v->kind == JSON_BOOL) { - if (v->u.boolean) string_append_bytes(out, "true", 4); - else string_append_bytes(out, "false", 5); - return; - } - - if (v->kind == JSON_INT) { - string s = string_format("%lli", (long long)v->u.integer); - string_append_bytes(out, s.data, s.length); - free_sized(s.data, s.mem_length); - return; - } - - if (v->kind == JSON_DOUBLE) { - string s = string_format("%.17g", v->u.real); - string_append_bytes(out, s.data, s.length); - free_sized(s.data, s.mem_length); - return; - } - - if (v->kind == JSON_STRING) { - serialize_string(&v->u.string, out); - return; - } - - if (v->kind == JSON_ARRAY) { - serialize_array(v, out, indent, level); - return; - } - - if (v->kind == JSON_OBJECT) { - serialize_object(v, out, indent, level); - return; - } -} - -JsonError json_serialize(const JsonValue *value, string *out, uint32_t indent) { - if (!value || !out) return JSON_ERR_INVALID; - *out = string_repeat('\0', 0); - serialize_value(value, out, indent, 0); - return JSON_OK; -} \ No newline at end of file diff --git a/shared/data/json.h b/shared/data/json.h deleted file mode 100644 index 2deb3e8d..00000000 --- a/shared/data/json.h +++ /dev/null @@ -1,94 +0,0 @@ -#pragma once - -#include "types.h" -#include "std/string.h" - -#ifdef __cplusplus -extern "C" { -#endif - -typedef enum { - JSON_NULL = 0, - JSON_BOOL, - JSON_INT, - JSON_DOUBLE, - JSON_STRING, - JSON_ARRAY, - JSON_OBJECT -} JsonKind; - -struct JsonValue; - -typedef struct { - uint32_t count; - struct JsonValue **items; -} JsonArray; - -typedef struct { - string key; - struct JsonValue *value; -} JsonPair; - -typedef struct { - uint32_t count; - JsonPair *pairs; -} JsonObject; - -typedef struct JsonValue { - JsonKind kind; - union { - bool boolean; - int64_t integer; - double real; - string string; - JsonArray array; - JsonObject object; - } u; -} JsonValue; - -typedef enum { - JSON_OK = 0, - JSON_ERR_INVALID, - JSON_ERR_OOM, - JSON_ERR_TYPE -} JsonError; - -JsonError json_parse(const char *buf, uint32_t len, JsonValue **out); -JsonError json_serialize(const JsonValue *value, string *out, uint32_t indent); -void json_free(JsonValue *v); - -JsonValue *json_obj_get(const JsonValue *obj, const char *key); -static inline bool json_is_null(const JsonValue *v) { return v && v->kind == JSON_NULL; } -static inline bool json_is_bool(const JsonValue *v) { return v && v->kind == JSON_BOOL; } -static inline bool json_is_int(const JsonValue *v) { return v && v->kind == JSON_INT; } -static inline bool json_is_double(const JsonValue *v) { return v && v->kind == JSON_DOUBLE; } -static inline bool json_is_number(const JsonValue *v) { return v && (v->kind == JSON_INT || v->kind == JSON_DOUBLE); } -static inline bool json_is_string(const JsonValue *v) { return v && v->kind == JSON_STRING; } -static inline bool json_is_array(const JsonValue *v) { return v && v->kind == JSON_ARRAY; } -static inline bool json_is_object(const JsonValue *v) { return v && v->kind == JSON_OBJECT; } - -bool json_get_bool(const JsonValue *v, bool *out); -bool json_get_int(const JsonValue *v, int64_t *out); -bool json_get_double(const JsonValue *v, double *out); -bool json_get_string(const JsonValue *v, string *out); -bool json_get_number_as_double(const JsonValue *v, double *out); - -uint32_t json_array_size(const JsonValue *v); -JsonValue *json_array_get(const JsonValue *v, uint32_t index); - -JsonValue *json_new_null(); -JsonValue *json_new_bool(bool v); -JsonValue *json_new_int(int64_t v); -JsonValue *json_new_double(double v); -JsonValue *json_new_string(const char *data, uint32_t len); -JsonValue *json_new_array(); -JsonValue *json_new_object(); - -bool json_array_push(JsonValue *arr, JsonValue *elem); -bool json_obj_set(JsonValue *obj, const char *key, JsonValue *value); - -JsonValue *json_clone(const JsonValue *src); - -#ifdef __cplusplus -} -#endif diff --git a/shared/data/percent.c b/shared/data/percent.c deleted file mode 100644 index 08b65587..00000000 --- a/shared/data/percent.c +++ /dev/null @@ -1,36 +0,0 @@ -#include "percent.h" -#include "std/string.h" - -bool percent_decode(sizedptr in, string *out) { - *out = string_repeat('\0', 0); - const char *buf = (const char*)in.ptr; - uint32_t len = in.size; - - uint32_t i = 0; - while (i < len) { - char c = buf[i]; - - if (c == '%' && i + 2 < len) { - int h1 = hex_val(buf[i+1]); - int h2 = hex_val(buf[i+2]); - if (h1 < 0 || h2 < 0) return false; - - char decoded =(char)((h1 << 4) | h2); - string_append_bytes(out, &decoded, 1); - i += 3; - continue; - } - - if (c == '+') { - char sp = ' '; - string_append_bytes(out, &sp, 1); - i++; - continue; - } - - string_append_bytes(out, &c, 1); - i++; - } - - return true; -} diff --git a/shared/data/percent.h b/shared/data/percent.h deleted file mode 100644 index b061a40a..00000000 --- a/shared/data/percent.h +++ /dev/null @@ -1,14 +0,0 @@ -#pragma once - -#include "types.h" -#include "std/string.h" - -#ifdef __cplusplus -extern "C" { -#endif - -bool percent_decode(sizedptr in, string *out); - -#ifdef __cplusplus -} -#endif diff --git a/shared/data/query_string.c b/shared/data/query_string.c deleted file mode 100644 index ec261ac1..00000000 --- a/shared/data/query_string.c +++ /dev/null @@ -1,66 +0,0 @@ -#include "query_string.h" -#include "std/string.h" -#include "syscalls/syscalls.h" - -void query_parse(const char *buf, uint32_t len, QueryParam **out_params, uint32_t *out_count) { - *out_params = 0; - *out_count = 0; - if (!buf || !len) return; - - uint32_t max_params = 1; //b query_parse - - for (uint32_t i = 0; i < len; i++) if (buf[i] == '&') max_params++; - - QueryParam *params = (QueryParam*)malloc(sizeof(QueryParam) * max_params); - if (!params) return; - - uint32_t count = 0; - uint32_t pos = 0; - - while (pos < len) { - uint32_t seg_start = pos; - while (pos < len && buf[pos] != '&') pos++; - uint32_t seg_end = pos; - - if (seg_end > seg_start) { - uint32_t eq_pos = seg_end; - for (uint32_t i = seg_start; i < seg_end; i++) { - if (buf[i] =='=') { - eq_pos = i; - break; - } - } - - QueryParam *qp = ¶ms[count]; - - if (eq_pos < seg_end) { - qp->key.ptr = (uintptr_t)(buf + seg_start); - qp->key.size = eq_pos - seg_start; - qp->value.ptr = (uintptr_t)(buf + eq_pos + 1); - qp->value.size = seg_end - (eq_pos + 1); - } else { - qp->key.ptr = (uintptr_t)(buf + seg_start); - qp->key.size = seg_end - seg_start; - qp->value.ptr = (uintptr_t)(buf + seg_end); - qp->value.size = 0; - } - - count++; - } - - if (pos < len && buf[pos] == '&') pos++; - } - - *out_params = params; - *out_count = count; -} - -void query_parse_z(const char *buf, QueryParam **out_params, uint32_t *out_count) { - if (!buf) { - *out_params = 0; - *out_count = 0; - return; - } - size_t n = strlen(buf); - query_parse(buf, (uint32_t)n, out_params, out_count); -} diff --git a/shared/data/query_string.h b/shared/data/query_string.h deleted file mode 100644 index a6703169..00000000 --- a/shared/data/query_string.h +++ /dev/null @@ -1,19 +0,0 @@ -#pragma once - -#include "types.h" - -#ifdef __cplusplus -extern "C" { -#endif - -typedef struct { - sizedptr key; - sizedptr value; -} QueryParam; - -void query_parse(const char *buf, uint32_t len, QueryParam **out_params, uint32_t *out_count); -void query_parse_z(const char *buf, QueryParam **out_params, uint32_t *out_count); - -#ifdef __cplusplus -} -#endif diff --git a/shared/data/scanner/scanner.c b/shared/data/scanner/scanner.c deleted file mode 100644 index 02c3b7c9..00000000 --- a/shared/data/scanner/scanner.c +++ /dev/null @@ -1,41 +0,0 @@ -#include "data/scanner/scanner.h" - -bool scan_eof(Scanner *s) { - return s->pos >= s->len; -} - -char scan_peek(Scanner *s) { - if (s->pos >= s->len) return 0; - return s->buf[s->pos]; -} - -char scan_next(Scanner *s) { - if (s->pos >= s->len) return 0; - return s->buf[s->pos++]; -} - -bool scan_match(Scanner *s, char c) { - if (scan_eof(s)) return false; - if (s->buf[s->pos] != c) return false; - s->pos++; - return true; -} - -bool scan_match_string(Scanner *s, const char *str) { - uint32_t i = 0; - while (str[i]) { - if (s->pos + i >= s->len) return false; - if (s->buf[s->pos + i] != str[i]) return false; - i++; - } - s->pos += i; - return true; -} - -void scan_skip_ws(Scanner *s, bool skip_nl) { - while (!scan_eof(s)) { - char c = s->buf[s->pos]; - if (c==' '||(skip_nl && c=='\n')||c=='\t'||c=='\r') s->pos++; - else break; - } -} \ No newline at end of file diff --git a/shared/data/scanner/scanner.h b/shared/data/scanner/scanner.h deleted file mode 100644 index b9824a2a..00000000 --- a/shared/data/scanner/scanner.h +++ /dev/null @@ -1,26 +0,0 @@ -#pragma once -#include "types.h" -#include "std/std.h" - -typedef struct { - const char *buf; - uint32_t len; - uint32_t pos; -} Scanner; - -static inline Scanner scanner_make(const char *buf, uint32_t len) { - Scanner s; - s.buf = buf; - s.len = len; - s.pos = 0; - return s; -} - -bool scan_eof(Scanner *s); -char scan_peek(Scanner *s); -char scan_next(Scanner *s); - -bool scan_match(Scanner *s, char c); -bool scan_match_string(Scanner *s, const char *str); - -void scan_skip_ws(Scanner *s, bool skip_nl); diff --git a/shared/data/tokenizer/tokenizer.c b/shared/data/tokenizer/tokenizer.c deleted file mode 100644 index 6e164551..00000000 --- a/shared/data/tokenizer/tokenizer.c +++ /dev/null @@ -1,439 +0,0 @@ -#include "data/tokenizer/tokenizer.h" - -static void tokenizer_fail(Tokenizer *t, TokenizerError err) { - if (t->failed) return; - - t->failed = true; - t->err = err; - t->err_pos = t->s->pos; -} - -static bool skip_ws_and_comments(Tokenizer *t, Token *out) { - Scanner *s = t-> s; - for (;;) { - scan_skip_ws(s, !t->parse_newline); - if (scan_eof(s)) return false; - - uint32_t pos =s->pos; - - if (scan_match(s, '\n')){ - out->kind = TOK_NEWLINE; - out->start = s->buf + s->pos; - out->length = 1; - out->pos = s->pos; - return true; - } - if (t->comment_type == TOKENIZER_COMMENT_TYPE_SLASH){ - if (scan_match(s, '/')) { - if (scan_match(s, '/')) { - while (!scan_eof(s)) { - char c = scan_next(s); - if (c == '\n' || c == '\r') break; - } - continue; - } else if (scan_match(s, '*')) { - int found = 0; - while (!scan_eof(s)) { - char c = scan_next(s); - if (c == '*' && !scan_eof(s) && scan_peek(s) == '/') { - scan_next(s); - found = 1; - break; - } - } - if (!found) { - tokenizer_fail(t, TOKENIZER_ERR_UNTERMINATED_COMMENT); - return false; - } - continue; - } else { - s->pos = pos; - } - } - } else if (t->comment_type == TOKENIZER_COMMENT_TYPE_HASH){ - if (scan_match(s, '#')) { - while (!scan_eof(s)) { - char c = scan_next(s); - if (c == '\n' || c == '\r') break; - } - continue; - } - } - - break; - } - return false; -} - -static void read_identifier(Scanner *s, Token *tok) { - uint32_t start = s->pos; - scan_next(s); - - while (!scan_eof(s)) { - char c = scan_peek(s); - if (!(is_alnum(c) || c == '_')) break; - scan_next(s); - } - - tok->kind = TOK_IDENTIFIER; - tok->start = s->buf + start; - tok->length = s->pos - start; - tok->pos = start; -} - -static bool read_number(Tokenizer *t, Token *tok) { - Scanner *s = t->s; - uint32_t start = s->pos; - const char *buf = s->buf; - uint32_t len = s->len; - uint32_t pos = start; - - if (pos >= len || !(buf[pos] >= '0' && buf[pos] <= '9')) return false; - - if (buf[pos] == '0' && pos + 1 < len) { - char p = buf[pos + 1]; - - if (p == 'x' || p == 'X') { - pos += 2; - if (pos >= len) return false; - - int ok = 0; - while (pos < len) { - char c = buf[pos]; - if ((c >= '0' && c <= '9') || (c >= 'a' && c <= 'f') || (c >= 'A' && c <= 'F')) { - pos++; - ok = 1; - } else break; - } - if (!ok) return false; - - s->pos = pos; - tok->kind = t->skip_type_check ? TOK_CONST : TOK_NUMBER; - tok->start = buf + start; - tok->length = pos - start; - tok->pos = start; - - return true; - } - - if (p == 'b' || p == 'B') { - pos += 2; - if (pos >= len) return false; - - int ok = 0; - while (pos < len) { - char c = buf[pos]; - if (c == '0' || c == '1') { - pos++; - ok = 1; - } else break; - } - if (!ok) return false; - - s->pos = pos; - tok->kind = t->skip_type_check ? TOK_CONST : TOK_NUMBER; - tok->start = buf + start; - tok->length = pos - start; - tok->pos = start; - - return true; - } - - if (p == 'o' || p == 'O') { - pos += 2; - if (pos >= len) return false; - - int ok = 0; - while (pos < len) { - - char c = buf[pos]; - if (c >= '0' && c <= '7') { - pos++; - ok = 1; - } else break; - } - if (!ok) return false; - - s->pos = pos; - tok->kind = t->skip_type_check ? TOK_CONST : TOK_NUMBER; - tok->start = buf + start; - tok->length = pos - start; - tok->pos= start; - - return true; - } - } - - while (pos = '0' && buf[pos] <= '9') pos++; - - uint32_t int_end = pos; - - if (pos < len && buf[pos] == '.') { - uint32_t p2 = pos + 1; - if (p2 < len && buf[p2] >= '0' && buf[p2] <= '9') { - pos = p2; - while (pos < len && buf[pos] >= '0' && buf[pos] <= '9') pos++; - } else { - pos = int_end; - } - } - - uint32_t mant_end = pos; - - if (pos < len && (buf[pos] == 'e' || buf[pos] == 'E')) { - uint32_t exp_start = pos; - pos++; - if (pos < len && (buf[pos] == '+' || buf[pos] == '-')) pos++; - if (pos < len && (buf[pos] >= '0' && buf[pos] <= '9')) { - while (pos < len && (buf[pos] >= '0' && buf[pos] <= '9')) pos++; - mant_end = pos; - } else { - pos = exp_start; - } - } - - s->pos = mant_end; - tok->kind = t->skip_type_check ? TOK_CONST : TOK_NUMBER; - tok->start = buf + start; - tok->length = mant_end - start; - tok->pos = start; - return true; -} - -static bool read_string(Tokenizer *t, Token *tok) { - Scanner *s = t->s; - uint32_t start = s->pos; - - if (!scan_match(s, '"')) return false; - - while (!scan_eof(s)) { - char c = scan_next(s); - if (c == '"') { - tok->kind = t->skip_type_check ? TOK_CONST : TOK_STRING; - tok->start = s->buf + start; - tok->length = s->pos - start; - tok->pos = start; - return true; - } - - if (c == '\\') { - if (scan_eof(s)) { - tokenizer_fail(t, TOKENIZER_ERR_UNTERMINATED_STRING); - return false; - } - char e = scan_next(s); - if (e == 'u') { - for (int i = 0; i < 4; i++) { - if (scan_eof(s)) { - tokenizer_fail(t, TOKENIZER_ERR_UNTERMINATED_STRING); - return false; - } - char h = scan_next(s); - if (!((h >= '0' && h <= '9') || - (h >= 'a' && h <= 'f') || - (h >= 'A' && h <= 'F'))) { - tokenizer_fail(t, TOKENIZER_ERR_UNTERMINATED_STRING); - return false; - } - } - } else if (!(e == '"' || e == '\\' || e == '/' || - e == 'b' || e == 'f' || e == 'n' || - e == 'r' || e == 't')) { - tokenizer_fail(t, TOKENIZER_ERR_UNTERMINATED_STRING); - return false; - } - } - } - - tokenizer_fail(t, TOKENIZER_ERR_UNTERMINATED_STRING); - return false; -} - -static const char *ops3[] = {">>>", "<<=", ">>=", "===", 0}; -static const char *ops2[] = {"==", "!=", "<=", ">=", "&&", "||", "<<", ">>", "+=", "-=", "*=", "/=", "%=", "&=", "|=", "^=", "::", "->", 0}; -static const char ops1[] = "+-*/%=<>!&|^~?"; - -static bool read_operator(Scanner *s, Token *tok) { - const char *buf = s->buf; - uint32_t len = s->len; - uint32_t pos = s->pos; - - for (int i = 0; ops3[i]; i++) { - const char *op = ops3[i]; - uint32_t n = 3; - if (pos + n <= len) { - uint32_t k = 0; - while (k < n && buf[pos + k] == op[k]) k++; - - if (k == n) { - s->pos = pos + n; - tok->kind = TOK_OPERATOR; - tok->start = buf + pos; - tok->length = n; - tok->pos = pos; - - return true; - } - } - } - - for (int i = 0; ops2[i]; i++) { - const char *op = ops2[i]; - uint32_t n = 0; - while (op[n]) n++; - - if (pos + n <= len) { - uint32_t k = 0; - while (k < n && buf[pos + k] == op[k]) k++; - if (k == n) { - s->pos = pos + n; - tok->kind = TOK_OPERATOR; - tok->start = buf + pos; - tok->length = n; - tok->pos = pos; - - return true; - } - } - } - - if (pos >= len) return false; - char c = buf[pos]; - - for (int i = 0; ops1[i]; i++) { - if (c == ops1[i]) { - s->pos = pos + 1; - tok->kind = TOK_OPERATOR; - tok->start = buf + pos; - tok->length = 1; - tok->pos = pos; - - return true; - } - } - - return false; -} - -static bool read_delim(Scanner *s, Token *tok) { - if (scan_eof(s))return false; - - uint32_t pos = s->pos; - char c = scan_peek(s); - - if (c == '(') { scan_next(s); tok->kind = TOK_LPAREN; } - else if (c == ')'){ scan_next(s); tok->kind = TOK_RPAREN;} - else if (c == '{'){ scan_next(s); tok->kind = TOK_LBRACE; } - else if (c == '}'){ scan_next(s); tok->kind = TOK_RBRACE; } - else if (c == '['){ scan_next(s); tok->kind = TOK_LBRACKET; } - else if (c == ']'){ scan_next(s); tok->kind = TOK_RBRACKET; } - else if (c == ','){ scan_next(s); tok->kind = TOK_COMMA; } - else if (c == ':'){ scan_next(s); tok->kind = TOK_COLON; } - else if (c == ';'){ scan_next(s); tok->kind = TOK_SEMICOLON; } - else if (c == '.'){ scan_next(s); tok->kind = TOK_DOT; } - else return false; - - tok->start = s->buf + pos; - tok->length = 1; - tok->pos =pos; - - return true; -} - -bool tokenizer_next(Tokenizer *t, Token *out) { - if (t->failed) { - out->kind = TOK_INVALID; - out->start = 0; - out->length = 0; - out->pos = t->s->pos; - return false; - } - - if (skip_ws_and_comments(t, out)){ - return true; - } - if (t->failed) { - out->kind = TOK_INVALID; - out->start = 0; - out->length = 0; - out->pos = t->err_pos; - return false; - } - - Scanner *s = t->s; - - if (scan_eof(s)) { - out->kind = TOK_EOF; - out->start = s->buf + s->pos; - out->length = 0; - out->pos = s->pos; - return true; - } - - char c = scan_peek(s); - - if (is_alpha(c) || c == '_') { - read_identifier(s, out); - return true; - } - - if (c >= '0' && c <= '9') { - uint32_t pos_before = s->pos; - if (read_number(t, out)) return true; - - tokenizer_fail(t, TOKENIZER_ERR_INVALID_NUMBER); - out->kind = TOK_INVALID; - out->start = s->buf + pos_before; - out->length = 0; - out->pos = pos_before; - return false; - } - - if (c == '"') { - uint32_t pos_before = s->pos; - if (read_string(t, out)) return true; - - tokenizer_fail(t, TOKENIZER_ERR_UNTERMINATED_STRING); - out->kind = TOK_INVALID; - out->start = s->buf + pos_before; - out->length = 0; - out->pos = pos_before; - return false; - } - - if (read_delim(s, out)) return true; - - if (read_operator(s, out)) return true; - - out->kind = TOK_SYMBOL; - out->start = s->buf + s->pos; - out->length = 1; - out->pos = s->pos; - s->pos++; - return true; -} - -char* token_name(TokenKind kind){ - switch (kind) { - case TOK_EOF: return "eof"; - case TOK_INVALID: return "invalid"; - case TOK_IDENTIFIER: return "identifier"; - case TOK_NUMBER: return "number"; - case TOK_STRING: return "string"; - case TOK_CONST: return "const"; - case TOK_OPERATOR: return "operator"; - case TOK_LPAREN: return "lparen"; - case TOK_RPAREN: return "rparen"; - case TOK_LBRACE: return "lbrace"; - case TOK_RBRACE: return "rbrace"; - case TOK_LBRACKET: return "lbracket"; - case TOK_RBRACKET: return "rbracket"; - case TOK_COMMA: return "comma"; - case TOK_COLON: return "colon"; - case TOK_SEMICOLON: return "semicolon"; - case TOK_DOT: return "dot"; - case TOK_SYMBOL: return "symbol"; - case TOK_NEWLINE: return "newline"; - default: return ""; - } -} \ No newline at end of file diff --git a/shared/data/tokenizer/tokenizer.h b/shared/data/tokenizer/tokenizer.h deleted file mode 100644 index faed6310..00000000 --- a/shared/data/tokenizer/tokenizer.h +++ /dev/null @@ -1,83 +0,0 @@ -#pragma once -#include "types.h" -#include "data/scanner/scanner.h" -#include "std/string_slice.h" - -typedef enum { - TOK_EOF = 0, - TOK_INVALID, - - TOK_IDENTIFIER, - TOK_NUMBER, - TOK_STRING, - TOK_CONST, - - TOK_OPERATOR, - - TOK_LPAREN, - TOK_RPAREN, - TOK_LBRACE, - TOK_RBRACE, - TOK_LBRACKET, - TOK_RBRACKET, - - TOK_COMMA, - TOK_COLON, - TOK_SEMICOLON, - TOK_DOT, - - TOK_SYMBOL, - - TOK_NEWLINE -} TokenKind; - -typedef struct { - TokenKind kind; - const char *start; - uint32_t length; - uint32_t pos; -} Token; - -typedef enum { - TOKENIZER_ERR_NONE = 0, - TOKENIZER_ERR_INVALID_CHAR, - TOKENIZER_ERR_INVALID_NUMBER, - TOKENIZER_ERR_UNTERMINATED_STRING, - TOKENIZER_ERR_UNTERMINATED_COMMENT -} TokenizerError; - -typedef enum { - TOKENIZER_COMMENT_TYPE_SLASH, - TOKENIZER_COMMENT_TYPE_HASH, -} TokenizerComment; - -typedef struct { - Scanner *s; - bool failed; - TokenizerError err; - uint32_t err_pos; - bool skip_type_check; - bool parse_newline; - TokenizerComment comment_type; -} Tokenizer; - -static inline Tokenizer tokenizer_make(Scanner *s) { - Tokenizer t = {}; - t.s = s; - t.failed = false; - t.err = TOKENIZER_ERR_NONE; - t.err_pos = 0; - return t; -} - -static inline bool tokenizer_ok(const Tokenizer *t) { - return !t->failed; -} - -bool tokenizer_next(Tokenizer *t, Token *out); - -static inline string_slice token_to_slice(Token t){ - return (string_slice){ .data = (char*)t.start, .length = t.length }; -} - -char* token_name(TokenKind kind); diff --git a/shared/data/toml.c b/shared/data/toml.c deleted file mode 100644 index 1e8a279f..00000000 --- a/shared/data/toml.c +++ /dev/null @@ -1,92 +0,0 @@ -#include "toml.h" -#include "data/scanner/scanner.h" -#include "data/helpers/token_stream.h" - -void read_toml_value(TokenStream *ts, Token key, toml_handler on_kvp, void *context){ - Token t; - ts_next(ts, &t); - string s = string_from_literal_length(key.start, key.length); - - switch (t.kind){ - case TOK_IDENTIFIER: { - - on_kvp(token_to_slice(key), token_to_slice(t), context); - } - break; - case TOK_STRING: { - - on_kvp(token_to_slice(key), make_string_slice(t.start+1, 0, t.length-2), context); - } - break; - case TOK_NUMBER: { - - on_kvp(token_to_slice(key), token_to_slice(t), context); - } - break; - - case TOK_LBRACKET: { - int depth = 0; - Token t2; - while (ts_next(ts, &t2)) { - if (!t2.kind) return; - if (t2.kind == TOK_LBRACKET) depth++; - if (t2.kind == TOK_RBRACKET) { - if (depth) - depth--; - else { - on_kvp(token_to_slice(key), make_string_slice((char*)t.start, 1, t2.start - t.start - 1), 0); - break; - } - } - } - } - break; - - default: - - break; - } - - string_free(s); - -} - -void read_toml(char *info, toml_handler on_kvp, void *context){ - Scanner s = scanner_make(info, strlen(info)); - Tokenizer tk = tokenizer_make(&s); - tk.comment_type = TOKENIZER_COMMENT_TYPE_HASH; - tk.skip_type_check = false; - TokenStream ts; - ts_init(&ts, &tk); - - Token t; - while (ts_next(&ts, &t)) { - if (!t.kind) break; - - switch (t.kind) { - case TOK_IDENTIFIER:{ - Token op; - if (!ts_expect(&ts, TOK_OPERATOR, &op) || !slice_lit_match(token_to_slice(op), "=", false)){ - return; - } - read_toml_value(&ts, t, on_kvp, context); - } - break; - case TOK_LBRACKET://TODO: in real TOML, these have meaning - { - Token t2; - while (ts_next(&ts, &t2)) { - if (!t2.kind) return; - if (t2.kind == TOK_RBRACKET) break; - } - } - break; - default: - - break; - } - } - - return; - -} \ No newline at end of file diff --git a/shared/data/toml.h b/shared/data/toml.h deleted file mode 100644 index d86019e6..00000000 --- a/shared/data/toml.h +++ /dev/null @@ -1,8 +0,0 @@ -#pragma once - -#include "types.h" -#include "std/string_slice.h" - -typedef void (*toml_handler)(string_slice key, string_slice value, void *context); - -void read_toml(char *info, toml_handler on_kvp, void *context); \ No newline at end of file diff --git a/shared/data/url.c b/shared/data/url.c deleted file mode 100644 index 568f491e..00000000 --- a/shared/data/url.c +++ /dev/null @@ -1,150 +0,0 @@ -#include "url.h" -#include "std/string.h" - -ParsedURL parse_url(const char *buf, uint32_t len) { - ParsedURL r = {0}; - if (!buf || !len) return r; - - uint32_t i = 0; - - if (!is_alpha(buf[i]))return r; - i++; - while (i < len) { - char c= buf[i]; - if (c == ':') break; - - if (!(is_alnum(c) || c == '+' || c == '-' || c == '.')) return r; - i++; - } - - if (i >= len || buf[i] != ':') return r; - - r.scheme.ptr = (uintptr_t)buf; - r.scheme.size = i; - i++; - - if (i + 1 < len && buf[i] =='/' &&buf[i + 1] == '/') { - i += 2; - uint32_t auth_start = i; - uint32_t auth_end = auth_start; - while (auth_end < len) { - char c = buf[auth_end]; - if (c == '/' || c == '?' || c == '#') break; - auth_end++; - } - - if (auth_end > auth_start) { - uint32_t user_end = auth_start; - while (user_end= auth_end) return r; - - if (buf[host_start] == '[') { - uint32_t p = host_start + 1; - while (p < auth_end && buf[p] != ']') p++; - - if (p >= auth_end) return r; - - r.host.ptr = (uintptr_t)(buf + host_start + 1); - r.host.size = p -(host_start + 1); - - p++; - if (p < auth_end && buf[p] == ':') { - p++; - uint32_t v = 0; - int any = 0; - while (p < auth_end) { - char d = buf[p]; - if (!is_digit(d)) return r; - - any = 1; - v = v * 10 + (uint32_t)(d - '0'); - if (v > 65535) return r; - p++; - } - if (!any) return r; - r.port = (uint16_t)v; - } - } else { - uint32_t p = host_start; - while (p < auth_end && buf[p] != ':') p++; - - r.host.ptr = (uintptr_t)(buf + host_start); - r.host.size = p -host_start; - - if (p < auth_end && buf[p] == ':') { - p++; - uint32_t port = 0; - int any = 0; - while (p < auth_end) { - char d = buf[p]; - if (!is_digit(d)) return r; - - any = 1; - port = port * 10 + (uint32_t)(d -'0'); - if (port > 65535) return r; - p++; - } - if (!any) return r; - r.port = (uint16_t)port; - } - } - } - - i = auth_end; - } - - uint32_t path_start = i; - uint32_t path_end = path_start; - while (path_end < len) { - char c = buf[path_end]; - if (c == '?' || c == '#') break; - path_end++; - } - - if (path_end > path_start) { - r.path.ptr = (uintptr_t)(buf + path_start); - r.path.size = path_end - path_start; - } - - i = path_end; - - if (i < len && buf[i] == '?') { - uint32_t qs = i + 1; - uint32_t qe = qs; - while (qe < len && buf[qe] != '#') qe++; - - if (qe > qs) { - r.query.ptr = (uintptr_t)(buf + qs); - r.query.size = qe - qs; - } - i = qe; - } - - if (i < len && buf[i] == '#') { - uint32_t fs = i + 1; - if (fs < len) { - r.fragment.ptr = (uintptr_t)(buf + fs); - r.fragment.size = len - fs; - } - } - - r.ok = true; - return r; -} - -ParsedURL parse_url_z(const char *buf) { - if (!buf) { - ParsedURL r = {0}; - return r; - } - size_t n = strlen(buf); - return parse_url(buf, (uint32_t)n); -} diff --git a/shared/data/url.h b/shared/data/url.h deleted file mode 100644 index db093cf4..00000000 --- a/shared/data/url.h +++ /dev/null @@ -1,25 +0,0 @@ -#pragma once - -#include "types.h" - -#ifdef __cplusplus -extern "C" { -#endif - -typedef struct { - sizedptr scheme; - sizedptr userinfo; - sizedptr host; - uint16_t port; - sizedptr path; - sizedptr query; - sizedptr fragment; - bool ok; -} ParsedURL; - -ParsedURL parse_url(const char *buf, uint32_t len); -ParsedURL parse_url_z(const char *buf); - -#ifdef __cplusplus -} -#endif diff --git a/shared/data/userinfo.c b/shared/data/userinfo.c deleted file mode 100644 index f889018e..00000000 --- a/shared/data/userinfo.c +++ /dev/null @@ -1,29 +0,0 @@ -#include "userinfo.h" -#include "std/string.h" - -ParsedUserinfo parse_userinfo(sizedptr u) { - ParsedUserinfo r = {0}; - if (!u.ptr || u.size == 0) return r; - - const char *buf = (const char*)u.ptr; - uint32_t len = u.size; - - uint32_t sep = len; - for (uint32_t i = 0; i < len; i++) { - if (buf[i] == ':') { - sep = i; - break; - } - } - - if (sep == len) return r; - - r.username.ptr = u.ptr; - r.username.size = sep; - - r.password.ptr = (uintptr_t)(buf + sep+ 1); - r.password.size = len - (sep+ 1); - - r.ok = true; - return r; -} diff --git a/shared/data/userinfo.h b/shared/data/userinfo.h deleted file mode 100644 index da22f4c0..00000000 --- a/shared/data/userinfo.h +++ /dev/null @@ -1,19 +0,0 @@ -#pragma once - -#include "types.h" - -#ifdef __cplusplus -extern "C" { -#endif - -typedef struct { - sizedptr username; - sizedptr password; - bool ok; -} ParsedUserinfo; - -ParsedUserinfo parse_userinfo(sizedptr u); - -#ifdef __cplusplus -} -#endif diff --git a/shared/data_struct/array.hpp b/shared/data_struct/array.hpp deleted file mode 100644 index d39e22d7..00000000 --- a/shared/data_struct/array.hpp +++ /dev/null @@ -1,57 +0,0 @@ -#pragma once - -#include "types.h" - -#include "std/allocator.hpp" -#include "syscalls/syscalls.h" - -//TODO: review allocs & C -template -class Array { -public: - - Array() : items(0), count(0), capacity(0) { - } - - Array(uint32_t capacity) : count(0), capacity(capacity) { - if (capacity == 0) { - items = 0; - return; - } - void *mem = (void*)malloc(sizeof(T) * capacity); - items = reinterpret_cast(mem); - } - - ~Array() { - if (count == 0) return; - for (uint32_t i = 0; i < count; i++) - items[i].~T(); - free_sized(items, sizeof(T) * capacity); - } - - bool add(const T& value) { - if (count >= capacity) return false; - items[count] = value; - count++; - return true; - } - - void empty(){ - if (count == 0) return; - for (uint32_t i = 0; i < count; i++) - items[i].~T(); - memset(items, 0, sizeof(T) * count); - count = 0; - } - - T& operator[](uint32_t i) { return items[i]; } - const T& operator[](uint32_t i) const { return items[i]; } - uint32_t size() const { return count; } - uint32_t max_size() const { return capacity; } - - T* items; - -private: - uint32_t count; - uint32_t capacity; -}; \ No newline at end of file diff --git a/shared/data_struct/chunked_list.c b/shared/data_struct/chunked_list.c deleted file mode 100644 index dddda910..00000000 --- a/shared/data_struct/chunked_list.c +++ /dev/null @@ -1,174 +0,0 @@ -#include "chunked_list.h" -#include "types.h" - -cchunked_list_t* cchunked_list_create(uint64_t chunkSize){ - uintptr_t raw = (uintptr_t)malloc(sizeof(cchunked_node_t) + chunkSize * sizeof(void*)); - if (!raw) return NULL; - - cchunked_list_t* list = (cchunked_list_t*)malloc(sizeof(cchunked_list_t)); - if (!list) { - free_sized((void*)raw, sizeof(cchunked_node_t) + chunkSize * sizeof(void*)); - return NULL; - } - - list->chunkSize = chunkSize; - list->length = 0; - list->head = (cchunked_node_t*)raw; - list->head->count = 0; - list->head->next = NULL; - list->tail = list->head; - return list; -} - -void cchunked_list_destroy(cchunked_list_t* list){ - if (!list) return; - cchunked_node_t* node = list->head; - while (node) { - cchunked_node_t* next = node->next; - free_sized(node, sizeof(cchunked_node_t) + list->chunkSize * sizeof(void*)); - node = next; - } - free_sized(list, sizeof(cchunked_list_t)); -} - -cchunked_list_t* cchunked_list_clone(const cchunked_list_t* list){ - if (!list) return NULL; - cchunked_list_t* clone = cchunked_list_create(list->chunkSize); - if (!clone) return NULL; - - for (cchunked_node_t* it = list->head; it; it = it->next) { - for (uint64_t i = 0; i < it->count; i++) - cchunked_list_push_back(clone, it->data[i]); - } - return clone; -} - -void cchunked_list_push_back(cchunked_list_t* list, void* data){ - if (!list) return; - - if (!list->tail) { - uintptr_t m = (uintptr_t)malloc(sizeof(cchunked_node_t) + list->chunkSize * sizeof(void*)); - if (!m) return; - cchunked_node_t* node = (cchunked_node_t*)m; - node->count = 0; - node->next = NULL; - list->head = list->tail = node; - } - - if (list->tail->count == list->chunkSize) { - uintptr_t m = (uintptr_t)malloc(sizeof(cchunked_node_t) + list->chunkSize * sizeof(void*)); - if (!m) return; - cchunked_node_t* node = (cchunked_node_t*)m; - node->count = 0; - node->next = NULL; - list->tail->next = node; - list->tail = node; - } - - list->tail->data[list->tail->count++] = data; - list->length++; -} - -cchunked_node_t* cchunked_list_insert_after(cchunked_list_t* list, cchunked_node_t* node, void* data){ - if (!list) return NULL; - if (!node) { - cchunked_list_push_back(list, data); - return list->tail; - } - - if (node->count < list->chunkSize) { - node->data[node->count++] = data; - list->length++; - return node; - } - - uintptr_t m = (uintptr_t)malloc(sizeof(cchunked_node_t) + list->chunkSize * sizeof(void*)); - if (!m) return NULL; - cchunked_node_t* new_node = (cchunked_node_t*)m; - new_node->count = 1; - new_node->next = node->next; - new_node->data[0] = data; - - node->next = new_node; - if (list->tail == node) list->tail = new_node; - list->length++; - return new_node; -} - -void* cchunked_list_pop_front(cchunked_list_t* list){ - if (!list || !list->head || list->length == 0) return NULL; - - void* data = list->head->data[0]; - if (list->head->count > 1) { - for (uint64_t i = 1; i < list->head->count; ++i) - list->head->data[i-1] = list->head->data[i]; - list->head->count--; - } else { - cchunked_node_t* old = list->head; - list->head = old->next; - if (!list->head) list->tail = NULL; - free_sized(old, sizeof(cchunked_node_t) + list->chunkSize * sizeof(void*)); - } - - list->length--; - return data; -} - -void* cchunked_list_remove_node(cchunked_list_t* list, cchunked_node_t* node){ - if (!list || !node || !list->head) return NULL; - - if (node == list->head) - return cchunked_list_pop_front(list); - - cchunked_node_t* prev = list->head; - while (prev->next && prev->next != node) prev = prev->next; - if (prev->next != node) return NULL; - - void* data = node->data[0]; - for (uint64_t i = 1; i < node->count; ++i) - node->data[i - 1] = node->data[i]; - node->count--; - list->length--; - - if (node->count == 0) { - prev->next = node->next; - if (list->tail == node) list->tail = prev; - free_sized(node, sizeof(cchunked_node_t) + list->chunkSize * sizeof(void*)); - } - - return data; -} - -void cchunked_list_update(cchunked_list_t* list, cchunked_node_t* node, void* new_data){ - (void)list; - if (node && node->count) - node->data[0] = new_data; -} - -void cchunked_list_update_at(cchunked_list_t* list, cchunked_node_t* node, uint64_t offset, void* new_data){ - if (!list || !node || offset >= node->count) - return; - node->data[offset] = new_data; -} - -uint64_t cchunked_list_length(const cchunked_list_t* list){ - return list ? list->length : 0; -} - -uint64_t cchunked_list_size_bytes(const cchunked_list_t* list){ - if (!list) return 0; - uint64_t nodes = 0; - for (cchunked_node_t* it = list->head; it; it = it->next) nodes++; - return nodes * (sizeof(cchunked_node_t) + list->chunkSize * sizeof(void*)); -} - -void cchunked_list_for_each(const cchunked_list_t* list, void (*func)(void*)){ - if (!list || !func) return; - for (cchunked_node_t* it = list->head; it; it = it->next) - for (uint64_t i = 0; i < it->count; ++i) - func(it->data[i]); -} - -int cchunked_list_is_empty(const cchunked_list_t* list){ - return (!list || list->length == 0) ? 1 : 0; -} diff --git a/shared/data_struct/chunked_list.h b/shared/data_struct/chunked_list.h deleted file mode 100644 index 16f27057..00000000 --- a/shared/data_struct/chunked_list.h +++ /dev/null @@ -1,41 +0,0 @@ -#pragma once -#include "types.h" - -#ifdef __cplusplus -extern "C" { -#endif - -//TODO: review allocs & C -typedef struct cchunked_node { - uint64_t count; - struct cchunked_node* next; - void* data[]; -} cchunked_node_t; - -typedef struct cchunked_list { - uint64_t chunkSize; - uint64_t length; - cchunked_node_t* head; - cchunked_node_t* tail; -} cchunked_list_t; - -void* malloc(size_t size); -void free_sized(void* ptr, size_t size); - -cchunked_list_t* cchunked_list_create(uint64_t chunkSize); -void cchunked_list_destroy(cchunked_list_t* list); -cchunked_list_t* cchunked_list_clone(const cchunked_list_t* list); -void cchunked_list_push_back(cchunked_list_t* list, void* data); -void* cchunked_list_pop_front(cchunked_list_t* list); -cchunked_node_t* cchunked_list_insert_after(cchunked_list_t* list, cchunked_node_t* node, void* data); -void* cchunked_list_remove_node(cchunked_list_t* list, cchunked_node_t* node); -void cchunked_list_update(cchunked_list_t* list, cchunked_node_t* node, void* new_data); -void cchunked_list_update_at(cchunked_list_t* list, cchunked_node_t* node, uint64_t offset, void* new_data); -uint64_t cchunked_list_length(const cchunked_list_t* list); -uint64_t cchunked_list_size_bytes(const cchunked_list_t* list); -void cchunked_list_for_each(const cchunked_list_t* list, void (*func)(void*)); -int cchunked_list_is_empty(const cchunked_list_t* list); - -#ifdef __cplusplus -} -#endif diff --git a/shared/data_struct/chunked_list.hpp b/shared/data_struct/chunked_list.hpp deleted file mode 100644 index dcee3632..00000000 --- a/shared/data_struct/chunked_list.hpp +++ /dev/null @@ -1,181 +0,0 @@ -#pragma once -#include "types.h" -extern "C" { -#include "chunked_list.h" -} - -template -class ChunkedList { -public: - struct Node { - uint64_t count; - Node* next; - T data[]; - }; - - explicit ChunkedList(uint64_t cs) - : head(nullptr), tail(nullptr), length_(0), chunkSize(cs) {} - - ~ChunkedList() { - while (head) { - Node* next = head->next; - ::free_sized(head, sizeof(Node) + chunkSize * sizeof(T)); - head = next; - } - } - - ChunkedList(const ChunkedList& other) - : head(nullptr), tail(nullptr), length_(0), chunkSize(other.chunkSize) { - for (Node* c = other.head; c; c = c->next) { - for (uint64_t i = 0; i < c->count; ++i) { - push_back(c->data[i]); - } - } - } - - ChunkedList& operator=(const ChunkedList& other) { - if (this != &other) { - clear(); - chunkSize = other.chunkSize; - for (Node* c = other.head; c; c = c->next) { - for (uint64_t i = 0; i < c->count; ++i) { - push_back(c->data[i]); - } - } - } - return *this; - } - - void push_back(const T& value) { - if (!tail) allocFirst(); - if (tail->count == chunkSize) allocChunk(); - tail->data[tail->count++] = value; - ++length_; - } - - T pop_front() { - if (!head) return T(); - T val = head->data[0]; - if (head->count > 1) { - for (uint64_t i = 1; i < head->count; ++i) - head->data[i - 1] = head->data[i]; - --head->count; - } else { - Node* old = head; - head = head->next; - ::free_sized(old, sizeof(Node) + chunkSize * sizeof(T)); - if (!head) tail = nullptr; - } - --length_; - return val; - } - - Node* insert_after(Node* node, const T& value) { - if (!node) { - push_back(value); - return tail; - } - if (node->count < chunkSize) { - node->data[node->count++] = value; - ++length_; - return node; - } - Node* n = allocNode(value); - n->next = node->next; - node->next = n; - if (tail == node) tail = n; - ++length_; - return n; - } - - T remove_node(Node* node) { - if (!node || !head) return T(); - if (node == head) { - T val = head->data[0]; - uint64_t removed = head->count; - Node* nxt = head->next; - ::free_sized(head, sizeof(Node) + chunkSize * sizeof(T)); - head = nxt; - if (!head) tail = nullptr; - length_ -= removed; - return val; - } - Node* prev = head; - while (prev->next && prev->next != node) prev = prev->next; - if (prev->next != node) return T(); - T val = node->data[0]; - uint64_t removed = node->count; - prev->next = node->next; - if (tail == node) tail = prev; - ::free_sized(node, sizeof(Node) + chunkSize * sizeof(T)); - length_ -= removed; - return val; - } - - void update(Node* node, const T& value) { - if (node && node->count) node->data[0] = value; - } - - void update_at(Node* node, uint64_t offset, const T& value) { - if (node && offset < node->count) node->data[offset] = value; - } - - uint64_t size() const noexcept { - return length_; - } - - uint64_t size_bytes() const noexcept { - uint64_t nodes = 0; - for (Node* it = head; it; it = it->next) ++nodes; - return nodes * (sizeof(Node) + chunkSize * sizeof(T)); - } - - bool empty() const noexcept { - return length_ == 0; - } - - template - void for_each(Func f) const { - for (Node* it = head; it; it = it->next) { - for (uint64_t i = 0; i < it->count; ++i) { - f(it->data[i]); - } - } - } - -private: - Node* head; - Node* tail; - uint64_t length_; - uint64_t chunkSize; - - Node* allocNode(const T& value) { - uintptr_t raw = ::malloc(sizeof(Node) + chunkSize * sizeof(T)); - Node* n = reinterpret_cast(raw); - n->count = 1; - n->next = nullptr; - n->data[0] = value; - return n; - } - - void allocFirst() { - uintptr_t raw = ::malloc(sizeof(Node) + chunkSize * sizeof(T)); - head = tail = reinterpret_cast(raw); - head->count = 0; - head->next = nullptr; - } - - void allocChunk() { - uintptr_t raw = ::malloc(sizeof(Node) + chunkSize * sizeof(T)); - Node* n = reinterpret_cast(raw); - n->count = 0; - n->next = nullptr; - tail->next = n; - tail = n; - } - - void clear() { - while (head) pop_front(); - } -}; - diff --git a/shared/data_struct/data_struct.hpp b/shared/data_struct/data_struct.hpp deleted file mode 100644 index 43042db9..00000000 --- a/shared/data_struct/data_struct.hpp +++ /dev/null @@ -1,10 +0,0 @@ -#pragma once - -//TODO: review allocs & C -#include "array.hpp" -#include "chunked_list.hpp" -#include "double_linked_list.hpp" -#include "indexmap.hpp" -#include "linked_list.hpp" -#include "queue.hpp" -#include "ring_buffer.hpp" \ No newline at end of file diff --git a/shared/data_struct/double_linked_list.c b/shared/data_struct/double_linked_list.c deleted file mode 100644 index 362138ed..00000000 --- a/shared/data_struct/double_linked_list.c +++ /dev/null @@ -1,181 +0,0 @@ -#include "double_linked_list.h" - -cdouble_linked_list_t* cdouble_linked_list_create() { - uintptr_t raw = (uintptr_t)malloc((uint64_t)sizeof(cdouble_linked_list_t)); - if (!raw) return NULL; - cdouble_linked_list_t* list = (cdouble_linked_list_t*)raw; - list->head = list->tail = NULL; - list->length = 0; - return list; -} - -void cdouble_linked_list_destroy(cdouble_linked_list_t* list) { - if (!list) return; - cdouble_linked_list_node_t* node = list->head; - for (uint64_t i = 0; i < list->length; ++i) { - cdouble_linked_list_node_t* next = node->next; - free_sized(node, sizeof(cdouble_linked_list_node_t)); - node = next; - } - free_sized(list, sizeof(cdouble_linked_list_t)); -} - -cdouble_linked_list_t* cdouble_linked_list_clone(const cdouble_linked_list_t* list) { - if (!list) return NULL; - cdouble_linked_list_t* clone = cdouble_linked_list_create(); - if (!clone) return NULL; - cdouble_linked_list_node_t* it = list->head; - for (uint64_t i = 0; i < list->length; ++i) { - uintptr_t raw = (uintptr_t)malloc(sizeof(cdouble_linked_list_node_t)); - if (raw) { - cdouble_linked_list_node_t* node = (cdouble_linked_list_node_t*)raw; - node->data = it->data; - if (clone->length == 0) { - node->next = node->prev = node; - clone->head = clone->tail = node; - } else { - node->prev = clone->tail; - node->next = clone->head; - clone->tail->next = node; - clone->head->prev = node; - clone->tail = node; - } - ++clone->length; - } - it = it->next; - } - return clone; -} - -void cdouble_linked_list_push_front(cdouble_linked_list_t* list, void* data) { - if (!list) return; - uintptr_t raw = (uintptr_t)malloc(sizeof(cdouble_linked_list_node_t)); - if (!raw) return; - cdouble_linked_list_node_t* node = (cdouble_linked_list_node_t*)raw; - node->data = data; - if (list->length == 0) { - node->next = node->prev = node; - list->head = list->tail = node; - } else { - node->next = list->head; - node->prev = list->tail; - list->head->prev = node; - list->tail->next = node; - list->head = node; - } - ++list->length; -} - -void cdouble_linked_list_push_back(cdouble_linked_list_t* list, void* data) { - if (!list) return; - uintptr_t raw = (uintptr_t)malloc(sizeof(cdouble_linked_list_node_t)); - if (!raw) return; - cdouble_linked_list_node_t* node = (cdouble_linked_list_node_t*)raw; - node->data = data; - if (list->length == 0) { - node->next = node->prev = node; - list->head = list->tail = node; - } else { - node->prev = list->tail; - node->next = list->head; - list->tail->next = node; - list->head->prev = node; - list->tail = node; - } - ++list->length; -} - -void* cdouble_linked_list_pop_front(cdouble_linked_list_t* list) { - if (!list || list->length == 0) return NULL; - cdouble_linked_list_node_t* node = list->head; - void* data = node->data; - if (list->length == 1) { - list->head = list->tail = NULL; - } else { - list->head = node->next; - list->head->prev = list->tail; - list->tail->next = list->head; - } - --list->length; - free_sized(node, sizeof(cdouble_linked_list_node_t)); - return data; -} - -void* cdouble_linked_list_pop_back(cdouble_linked_list_t* list) { - if (!list || list->length == 0) return NULL; - cdouble_linked_list_node_t* node = list->tail; - void* data = node->data; - if (list->length == 1) { - list->head = list->tail = NULL; - } else { - list->tail = node->prev; - list->tail->next = list->head; - list->head->prev = list->tail; - } - --list->length; - free_sized(node, sizeof(cdouble_linked_list_node_t)); - return data; -} - -cdouble_linked_list_node_t* cdouble_linked_list_insert_after(cdouble_linked_list_t* list, cdouble_linked_list_node_t* node, void* data) { - if (!list) return NULL; - if (!node) { - cdouble_linked_list_push_front(list, data); - return list->head; - } - uintptr_t raw = (uintptr_t)malloc(sizeof(cdouble_linked_list_node_t)); - if (!raw) return NULL; - cdouble_linked_list_node_t* new_node = (cdouble_linked_list_node_t*)raw; - new_node->data = data; - new_node->next = node->next; - new_node->prev = node; - node->next->prev = new_node; - node->next = new_node; - if (list->tail == node) list->tail = new_node; - ++list->length; - return new_node; -} - -cdouble_linked_list_node_t* cdouble_linked_list_insert_before(cdouble_linked_list_t* list, cdouble_linked_list_node_t* node, void* data) { - if (!list) return NULL; - if (!node) { - cdouble_linked_list_push_back(list, data); - return list->tail; - } - return cdouble_linked_list_insert_after(list, node->prev, data); -} - -void* cdouble_linked_list_remove(cdouble_linked_list_t* list, cdouble_linked_list_node_t* node) { - if (!list || !node || list->length == 0) return NULL; - if (node == list->head) return cdouble_linked_list_pop_front(list); - if (node == list->tail) return cdouble_linked_list_pop_back(list); - node->prev->next = node->next; - node->next->prev = node->prev; - void* data = node->data; - --list->length; - free_sized(node, sizeof(cdouble_linked_list_node_t)); - return data; -} - -void cdouble_linked_list_update(cdouble_linked_list_t* list, cdouble_linked_list_node_t* node, void* new_data) { - (void)list; - if (node) node->data = new_data; -} - -uint64_t cdouble_linked_list_length(const cdouble_linked_list_t* list) { - return list ? list->length : 0; -} - -uint64_t cdouble_linked_list_size_bytes(const cdouble_linked_list_t* list) { - return list ? list->length * sizeof(cdouble_linked_list_node_t) : 0; -} - -cdouble_linked_list_node_t* cdouble_linked_list_find(cdouble_linked_list_t* list, void* key, int (*cmp)(void*, void*)) { - if (!list || !cmp || list->length == 0) return NULL; - cdouble_linked_list_node_t* it = list->head; - for (uint64_t i = 0; i < list->length; ++i) { - if (cmp(it->data, key) == 0) return it; - it = it->next; - } - return NULL; -} diff --git a/shared/data_struct/double_linked_list.h b/shared/data_struct/double_linked_list.h deleted file mode 100644 index c82657b5..00000000 --- a/shared/data_struct/double_linked_list.h +++ /dev/null @@ -1,41 +0,0 @@ -#pragma once -#include "types.h" - -#ifdef __cplusplus -extern "C" { -#endif - -//TODO: review allocs & C -typedef struct cdouble_linked_list_node { - void* data; - struct cdouble_linked_list_node* next; - struct cdouble_linked_list_node* prev; -} cdouble_linked_list_node_t; - -typedef struct cdouble_linked_list { - cdouble_linked_list_node_t* head; - cdouble_linked_list_node_t* tail; - uint64_t length; -} cdouble_linked_list_t; - -extern void* malloc(size_t size); -extern void free_sized(void* ptr, size_t size); - -cdouble_linked_list_t* cdouble_linked_list_create(); -void cdouble_linked_list_destroy(cdouble_linked_list_t* list); -cdouble_linked_list_t* cdouble_linked_list_clone(const cdouble_linked_list_t* list); -void cdouble_linked_list_push_front(cdouble_linked_list_t* list, void* data); -void cdouble_linked_list_push_back(cdouble_linked_list_t* list, void* data); -void* cdouble_linked_list_pop_front(cdouble_linked_list_t* list); -void* cdouble_linked_list_pop_back(cdouble_linked_list_t* list); -cdouble_linked_list_node_t* cdouble_linked_list_insert_after(cdouble_linked_list_t* list, cdouble_linked_list_node_t* node, void* data); -cdouble_linked_list_node_t* cdouble_linked_list_insert_before(cdouble_linked_list_t* list, cdouble_linked_list_node_t* node, void* data); -void* cdouble_linked_list_remove(cdouble_linked_list_t* list, cdouble_linked_list_node_t* node); -void cdouble_linked_list_update(cdouble_linked_list_t* list, cdouble_linked_list_node_t* node, void* new_data); -uint64_t cdouble_linked_list_length(const cdouble_linked_list_t* list); -uint64_t cdouble_linked_list_size_bytes(const cdouble_linked_list_t* list); -cdouble_linked_list_node_t* cdouble_linked_list_find(cdouble_linked_list_t* list, void* key, int (*cmp)(void*, void*)); - -#ifdef __cplusplus -} -#endif diff --git a/shared/data_struct/double_linked_list.hpp b/shared/data_struct/double_linked_list.hpp deleted file mode 100644 index 7b3cbe88..00000000 --- a/shared/data_struct/double_linked_list.hpp +++ /dev/null @@ -1,216 +0,0 @@ -#pragma once -#include "types.h" - -extern "C" { -#include "double_linked_list.h" -} - -//TODO: review allocs & C -template -class DoubleLinkedList { -private: - struct Node { - T data; - Node* next; - Node* prev; - }; - - Node* head; - Node* tail; - uint64_t length; - - Node* alloc_node(const T& value) { - uintptr_t raw = (uintptr_t)malloc(sizeof(Node)); - if (raw == 0) return nullptr; - Node* n = reinterpret_cast(raw); - n->data = value; - n->next = n->prev = nullptr; - return n; - } - - void free_node(Node* n) { - if (!n) return; - free_sized(n, sizeof(Node)); - } - - static void swap(DoubleLinkedList& a, DoubleLinkedList& b) noexcept { - Node* tmpHead = a.head; - a.head = b.head; - b.head = tmpHead; - - Node* tmpTail = a.tail; - a.tail = b.tail; - b.tail = tmpTail; - - size_t tmpLen = a.length; - a.length = b.length; - b.length = tmpLen; - } - -public: - DoubleLinkedList() : head(nullptr), tail(nullptr), length(0) {} - - DoubleLinkedList(const DoubleLinkedList& other) : head(nullptr), tail(nullptr), length(0) { - if (other.head) { - Node* it = other.head; - do { - push_back(it->data); - it = it->next; - } while (it != other.head); - } - } - - ~DoubleLinkedList() { - while (!empty()) pop_front(); - } - - DoubleLinkedList& operator=(const DoubleLinkedList& other) { - if (this != &other) { - DoubleLinkedList tmp(other); - swap(*this, tmp); - } - return *this; - } - - void push_front(const T& value) { - Node* n = alloc_node(value); - if (!n) return; - if (!head) { - head = tail = n; - n->next = n->prev = n; - } else { - n->next = head; - n->prev = tail; - head->prev = n; - tail->next = n; - head = n; - } - ++length; - } - - void push_back(const T& value) { - Node* n = alloc_node(value); - if (!n) return; - if (!tail) { - head = tail = n; - n->next = n->prev = n; - } else { - n->prev = tail; - n->next = head; - tail->next = n; - head->prev = n; - tail = n; - } - ++length; - } - - T pop_front() { - if (!head) return T(); - Node* n = head; - T val = n->data; - if (head == tail) { - head = tail = nullptr; - } else { - head = head->next; - head->prev = tail; - tail->next = head; - } - --length; - free_node(n); - return val; - } - - T pop_back() { - if (!tail) return T(); - Node* n = tail; - T val = n->data; - if (head == tail) { - head = tail = nullptr; - } else { - tail = tail->prev; - tail->next = head; - head->prev = tail; - } - --length; - free_node(n); - return val; - } - - Node* insert_after(Node* node, const T& value) { - if (!node) { - push_front(value); - return head; - } - Node* n = alloc_node(value); - if (!n) return nullptr; - n->next = node->next; - n->prev = node; - node->next->prev = n; - node->next = n; - if (tail == node) tail = n; - ++length; - return n; - } - - Node* insert_before(Node* node, const T& value) { - if (!node) { - push_back(value); - return tail; - } - return insert_after(node->prev, value); - } - - T remove(Node* node) { - if (!node) return T(); - if (node == head) return pop_front(); - if (node == tail) return pop_back(); - node->prev->next = node->next; - node->next->prev = node->prev; - T val = node->data; - --length; - free_node(node); - return val; - } - - void update(Node* node, const T& value) { - if (node) node->data = value; - } - - uint64_t size() const { - return length; - } - - bool empty() const { - return length == 0; - } - - Node* begin() const { - return head; - } - - Node* end() const { - return nullptr; - } - - template - Node* find(Predicate pred) const { - if (!head) return nullptr; - Node* it = head; - do { - if (pred(it->data)) return it; - it = it->next; - } while (it != head); - return nullptr; - } - - template - void for_each(Func func) const { - if (!head) return; - Node* it = head; - do { - func(it->data); - it = it->next; - } while (it != head); - } -}; - diff --git a/shared/data_struct/hashmap.c b/shared/data_struct/hashmap.c deleted file mode 100644 index 0cac0f0b..00000000 --- a/shared/data_struct/hashmap.c +++ /dev/null @@ -1,241 +0,0 @@ -#include "types.h" -#include "hashmap.h" -#include "std/memory.h" - -static int chm_bytewise_eq(const void* a, uint64_t alen, const void* b, uint64_t blen){ - if (alen!= blen) return 0; - const uint8_t* p= (const uint8_t*)a; - const uint8_t* q = (const uint8_t*)b; - for(uint64_t i = 0; i < alen; i++) if (p[i] != q[i]) return 0; - return 1; -} - -uint64_t chashmap_fnv1a64(const void* data, uint64_t len){ - const uint8_t* bytes = (const uint8_t*)data; - uint64_t h = 0xcbf29ce484222325ULL; - for (uint64_t i = 0; i < len; i++) { - h^= (uint64_t)bytes[i]; - h*= 0x100000001b3ULL; - } - return h; -} - -static void* chm_alloc(const chashmap_t* map, uint64_t sz){ - if (map && map->alloc) return map->alloc(sz); - return malloc(sz); -} - -static void chm_free(const chashmap_t* map, void* ptr, uint64_t sz){ - if (map && map->free){ - map->free(ptr, sz); - return; - } - free_sized(ptr,sz); -} - -static uint64_t chm_next_pow2(uint64_t x){ - if (x<8) return 8; - x--; - x|=x>>1; - x|=x>>2; - x|=x>>4; - x|=x>>8; - x|=x>>16; - x|=x>>32; - return x + 1; -} - -static void chm_update_threshold(chashmap_t* map){ - map->resize_threshold = (map->capacity*3)/4; -} - -chashmap_t* chashmap_create_alloc(uint64_t initial_capacity, void* (*alloc)(size_t size),void (*mfree)(void* ptr, size_t size)){ - uint64_t cap = chm_next_pow2(initial_capacity ? initial_capacity : 8); - chashmap_t* m = (chashmap_t*)alloc((uint64_t)sizeof(chashmap_t)); - - if (!m) return 0; - - m->alloc = alloc; m->free = mfree; - m->hash_fn = chashmap_fnv1a64; - m->keyeq_fn = chm_bytewise_eq; - m->value_dispose = 0; - m->capacity = cap; - m->size = 0; - m->buckets = (chashmap_entry_t**)alloc((uint64_t)sizeof(chashmap_entry_t*)*cap); - - if (!m->buckets) { - m->free(m, (uint64_t)sizeof(chashmap_t)); - return 0; - } - - memset(m->buckets, 0, (uint64_t)sizeof(chashmap_entry_t*)*cap); - chm_update_threshold(m); - return m; -} - -chashmap_t* chashmap_create(uint64_t initial_capacity){ - return chashmap_create_alloc(initial_capacity, malloc, free_sized); -} - -void chashmap_destroy(chashmap_t* map){ - if(!map) return; - - for (uint64_t i = 0; i < map->capacity; i++) { - chashmap_entry_t* e = map->buckets[i]; - while(e){ - chashmap_entry_t* n = e->next; - if(e->key_len>0 && e->key) chm_free(map,e->key,e->key_len); - if(map->value_dispose && e->value) map->value_dispose(e->value); - chm_free(map, e, (uint64_t)sizeof(chashmap_entry_t)); - e = n; - } - } - chm_free(map, map->buckets, (uint64_t)sizeof(chashmap_entry_t*)*map->capacity); - chm_free(map, map, (uint64_t)sizeof(chashmap_t)); -} - -void chashmap_set_allocator(chashmap_t* map, void* (*alloc)(size_t), void (*dealloc)(void*, size_t)){ - if (!map) return; - map->alloc = alloc; - map->free = dealloc; -} - -void chashmap_set_hash(chashmap_t* map, chashmap_hash_fn hash_fn, chashmap_keyeq_fn keyeq_fn){ - if (!map) return; - if (hash_fn) map->hash_fn = hash_fn; - if (keyeq_fn) map->keyeq_fn = keyeq_fn; -} - -void chashmap_set_value_dispose(chashmap_t* map, void (*dispose_fn)(void*)){ - if(!map) return; - map->value_dispose = dispose_fn; -} - -static int chm_resize(chashmap_t* map, uint64_t new_capacity){ - uint64_t ncap = chm_next_pow2(new_capacity); - chashmap_entry_t** nb = (chashmap_entry_t**)chm_alloc(map, (uint64_t)sizeof(chashmap_entry_t*)*ncap); - if (!nb) return 0; - - memset(nb, 0, (uint64_t)sizeof(chashmap_entry_t*)*ncap); - for (uint64_t i = 0; i < map->capacity; i++) { - chashmap_entry_t* e = map->buckets[i]; - while (e) { - chashmap_entry_t* nxt = e->next; - uint64_t idx = e->hash & (ncap-1); - e->next = nb[idx]; - nb[idx] = e; - e = nxt; - } - } - chm_free(map, map->buckets, (uint64_t)sizeof(chashmap_entry_t*)*map->capacity); - map->buckets = nb; - map->capacity = ncap; - chm_update_threshold(map); - - return 1; -} - -int chashmap_put(chashmap_t* map, const void* key, uint64_t key_len, void* value){ - if (!map) return -1; - - if (map->size >= map->resize_threshold){ - if (!chm_resize(map, map->capacity << 1)) return -1; - } - uint64_t h = map->hash_fn(key,key_len); - uint64_t idx = h & (map->capacity-1); - chashmap_entry_t* e = map->buckets[idx]; - - while(e){ - if(e->hash == h && map->keyeq_fn(e->key, e->key_len, key, key_len)){ - e->value = value; - return 0; - } - e = e->next; - } - chashmap_entry_t* ne = (chashmap_entry_t*)chm_alloc(map, (uint64_t)sizeof(chashmap_entry_t)); - if (!ne) return -1; - ne->hash = h; - - if (key_len>0) { - void* k = chm_alloc(map, key_len); - if (!k) { chm_free(map, ne, (uint64_t)sizeof(chashmap_entry_t)); return -1; } - memcpy(k, key, key_len); - ne->key = k; - ne->key_len = key_len; - } else { - ne->key = 0; - ne->key_len = 0; - } - - ne->value = value; - ne->next = map->buckets[idx]; - map->buckets[idx] = ne; - map->size++; - - return 1; -} - -void* chashmap_get(const chashmap_t* map, const void* key, uint64_t key_len){ - if (!map) return 0; - - uint64_t h = map->hash_fn(key,key_len); - uint64_t idx = h & (map->capacity-1); - chashmap_entry_t* e = map->buckets[idx]; - - while(e){ - if(e->hash == h && map->keyeq_fn(e->key, e->key_len, key, key_len)) return e->value; - e = e->next; - } - return 0; -} - -int chashmap_remove(chashmap_t* map, const void* key, uint64_t key_len, void** out_value){ - if (!map) return 0; - - uint64_t h = map->hash_fn(key, key_len); - uint64_t idx = h & (map->capacity-1); - chashmap_entry_t* e = map->buckets[idx]; - chashmap_entry_t* prev = 0; - - while(e){ - if (e->hash == h && map->keyeq_fn(e->key, e->key_len, key, key_len)) { - if (prev) prev->next = e->next; - else map->buckets[idx] = e->next; - - if (out_value) *out_value = e->value; - else if(map->value_dispose && e->value) map->value_dispose(e->value); - - if (e->key_len>0 && e->key) chm_free(map, e->key, e->key_len); - chm_free(map, e, (uint64_t)sizeof(chashmap_entry_t)); - map->size--; - return 1; - } - prev = e; - e = e->next; - } - - return 0; -} - -uint64_t chashmap_size(const chashmap_t* map){ - if(!map) return 0; - return map->size; -} - -uint64_t chashmap_capacity(const chashmap_t* map){ - if(!map) return 0; - return map->capacity; -} - -void chashmap_for_each(const chashmap_t* map, void (*func)(void* key, uint64_t key_len, void* value)){ - if (!map || !func) return; - - for (uint64_t i = 0; i < map->capacity; i++){ - chashmap_entry_t* e = map->buckets[i]; - while(e){ - chashmap_entry_t* next = e->next; - func(e->key, e->key_len, e->value); - e = next; - } - } -} diff --git a/shared/data_struct/hashmap.h b/shared/data_struct/hashmap.h deleted file mode 100644 index 9cae6ce5..00000000 --- a/shared/data_struct/hashmap.h +++ /dev/null @@ -1,51 +0,0 @@ -#pragma once -#include "types.h" - -#ifdef __cplusplus -extern "C" { -#endif - -//TODO: review allocs & C -extern void* malloc(size_t size); -extern void free_sized(void* ptr, size_t size); - -typedef uint64_t (*chashmap_hash_fn)(const void* key, uint64_t len); -typedef int (*chashmap_keyeq_fn)(const void* a, uint64_t alen, const void* b, uint64_t blen); - -typedef struct chashmap_entry { - uint64_t hash; - void* key; - uint64_t key_len; - void* value; - struct chashmap_entry* next; -} chashmap_entry_t; - -typedef struct chashmap { - chashmap_entry_t** buckets; - uint64_t capacity; - uint64_t size; - void* (*alloc)(size_t size); - void (*free)(void* ptr, size_t size); - chashmap_hash_fn hash_fn; - chashmap_keyeq_fn keyeq_fn; - void (*value_dispose)(void* value); - uint64_t resize_threshold; -} chashmap_t; - -chashmap_t* chashmap_create(uint64_t initial_capacity); -chashmap_t* chashmap_create_alloc(uint64_t initial_capacity, void* (*alloc)(size_t size),void (*mfree)(void* ptr, size_t size)); -void chashmap_destroy(chashmap_t* map); -void chashmap_set_allocator(chashmap_t* map, void* (*alloc)(size_t), void (*dealloc)(void*, size_t)); -void chashmap_set_hash(chashmap_t* map, chashmap_hash_fn hash_fn, chashmap_keyeq_fn keyeq_fn); -void chashmap_set_value_dispose(chashmap_t* map, void (*dispose_fn)(void*)); -int chashmap_put(chashmap_t* map, const void* key, uint64_t key_len, void* value); -void* chashmap_get(const chashmap_t* map, const void* key, uint64_t key_len); -int chashmap_remove(chashmap_t* map, const void* key, uint64_t key_len, void** out_value); -uint64_t chashmap_size(const chashmap_t* map); -uint64_t chashmap_capacity(const chashmap_t* map); -void chashmap_for_each(const chashmap_t* map, void (*func)(void* key, uint64_t key_len, void* value)); -uint64_t chashmap_fnv1a64(const void* data, uint64_t len); - -#ifdef __cplusplus -} -#endif diff --git a/shared/data_struct/indexmap.hpp b/shared/data_struct/indexmap.hpp deleted file mode 100644 index 822e876a..00000000 --- a/shared/data_struct/indexmap.hpp +++ /dev/null @@ -1,70 +0,0 @@ -#pragma once - -#include "types.h" - -#include "std/allocator.hpp" -#include "syscalls/syscalls.h" -#include "std/memory.h" - -template -class IndexMap { -public: - - IndexMap() : items(0), count(0), capacity(0) { - } - - IndexMap(const IndexMap&) = delete; - - IndexMap* operator=(const IndexMap& orig){ - this->count = orig.count; - this->capacity = orig.capacity; - void *mem = (void*)malloc(sizeof(T) * (capacity + 1)); - items = reinterpret_cast(mem); - memcpy(this->items, orig.items, sizeof(T) * (capacity + 1)); - default_val = &items[capacity]; - return this; - } - - IndexMap(uint32_t capacity) : count(0), capacity(capacity) { - if (capacity == 0) { - items = 0; - return; - } - void *mem = (void*)malloc(sizeof(T) * (capacity + 1)); - items = reinterpret_cast(mem); - default_val = &items[capacity]; - } - - ~IndexMap() { - if (capacity == 0) return; - for (uint32_t i = 0; i <= capacity; i++) - items[i].~T(); - if (items) free_sized(items, sizeof(T) * (capacity + 1)); - } - - bool add(const uint32_t index, const T& value) { - if (count >= capacity || index >= capacity) return false; - items[index] = value; - count++; - return true; - } - - T& operator[](uint32_t i) { - if (i >= capacity) return *default_val; - return items[i]; - } - const T& operator[](uint32_t i) const { - if (i >= capacity) return *default_val; - return items[i]; - } - uint32_t size() const { return count; } - uint32_t max_size() const { return capacity; } - - T* items; - T* default_val; - -private: - uint32_t count; - uint32_t capacity; -}; -//TEST: when assigning an indexmap (like in xhci's endpoint_map), it gets copied. Make sure the old one gets freed diff --git a/shared/data_struct/linked_list.c b/shared/data_struct/linked_list.c deleted file mode 100644 index 21162e61..00000000 --- a/shared/data_struct/linked_list.c +++ /dev/null @@ -1,140 +0,0 @@ -#include "linked_list.h" -#include "syscalls/syscalls.h" - -clinkedlist_t *clinkedlist_create(){ - uintptr_t mem = (uintptr_t)zalloc(sizeof(clinkedlist_t)); - if((void *)mem == NULL) return NULL; - clinkedlist_t *list = (clinkedlist_t *)mem; - list->head = NULL; - list->tail = NULL; - list->length = 0; - return list; -} - -void* clinkedlist_alloc(clinkedlist_t *list, size_t size){ - if (list->alloc) return list->alloc(size); - return zalloc(size); -} - -void clinkedlist_free(clinkedlist_t *list, void*ptr, size_t size){ - if (list->free) list->free(ptr,size); - return free_sized(ptr,size); -} - -void clinkedlist_destroy(clinkedlist_t *list){ - if(list == NULL) return; - clinkedlist_node_t *node = list->head; - while(node){ - clinkedlist_node_t *next = node->next; - clinkedlist_free(list, node, sizeof(clinkedlist_node_t)); - node = next; - } - clinkedlist_free(list, list, sizeof(clinkedlist_t)); -} - -clinkedlist_t *clinkedlist_clone(const clinkedlist_t *list){ - if(list == NULL) return NULL; - clinkedlist_t *clone = clinkedlist_create(); - if(clone == NULL) return NULL; - clinkedlist_node_t *it = list->head; - while(it){ - if(clone->tail){ - clinkedlist_node_t *new_node = (clinkedlist_node_t *)zalloc(sizeof(clinkedlist_node_t)); - new_node->data = it->data; - new_node->next = NULL; - clone->tail->next = new_node; - clone->tail = new_node; - clone->length++; - } else { - clinkedlist_push_front(clone, it->data); - } - it = it->next; - } - return clone; -} - -void clinkedlist_push_front(clinkedlist_t *list, void *data){ - if(list == NULL) return; - clinkedlist_node_t *node = (clinkedlist_node_t *)clinkedlist_alloc(list, sizeof(clinkedlist_node_t)); - node->data = data; - node->next = list->head; - list->head = node; - if(list->tail == NULL) list->tail = node; - list->length++; -} - -void *clinkedlist_pop_front(clinkedlist_t *list){ - if(list == NULL || list->head == NULL) return NULL; - clinkedlist_node_t *node = list->head; - void *data = node->data; - list->head = node->next; - if (list->head == NULL) list->tail = NULL; - list->length--; - clinkedlist_free(list, node, sizeof(clinkedlist_node_t)); - return data; -} - -clinkedlist_node_t *clinkedlist_insert_after(clinkedlist_t *list, clinkedlist_node_t *node, void *data){ - if(list == NULL) return NULL; - if(node == NULL){ - clinkedlist_push_front(list, data); - return list->head; - } - clinkedlist_node_t *new_node = (clinkedlist_node_t *)clinkedlist_alloc(list, sizeof(clinkedlist_node_t)); - new_node->data = data; - new_node->next = node->next; - node->next = new_node; - if(list->tail == node) list->tail = new_node; - list->length++; - return new_node; -} - -void *clinkedlist_remove(clinkedlist_t *list, clinkedlist_node_t *node){ - if(list == NULL || node == NULL || list->head == NULL) return NULL; - if(node == list->head){ - return clinkedlist_pop_front(list); - } - clinkedlist_node_t *prev = list->head; - while(prev->next && prev->next != node){ - prev = prev->next; - } - if(prev->next != node) return NULL; - prev->next = node->next; - if(node == list->tail) list->tail = prev; - void *data = node->data; - list->length--; - clinkedlist_free(list, node, sizeof(clinkedlist_node_t)); - return data; -} - -void clinkedlist_update(clinkedlist_t *list, clinkedlist_node_t *node, void *new_data){ - (void)list; - if(node) node->data = new_data; -} - -uint64_t clinkedlist_length(const clinkedlist_t *list){ - return list ? list->length : 0; -} - -uint64_t clinkedlist_size_bytes(const clinkedlist_t *list){ - return list ? list->length * sizeof(clinkedlist_node_t) : 0; -} - -clinkedlist_node_t *clinkedlist_find(clinkedlist_t *list, void *key, int (*cmp)(void *, void *)){ - if(list == NULL || cmp == NULL) return NULL; - clinkedlist_node_t *it = list->head; - while(it){ - if(cmp(it->data, key) == 0) return it; - it = it->next; - } - return NULL; -} - -void clinkedlist_for_each(const clinkedlist_t *list, void (*func)(void *)){ - if(list == NULL || func == NULL) return; - clinkedlist_node_t *it = list->head; - while(it){ - func(it->data); - it = it->next; - } -} diff --git a/shared/data_struct/linked_list.h b/shared/data_struct/linked_list.h deleted file mode 100644 index 3f122cd7..00000000 --- a/shared/data_struct/linked_list.h +++ /dev/null @@ -1,42 +0,0 @@ -#pragma once -#include "types.h" - -#ifdef __cplusplus -extern "C" { -#endif - -//TODO: review allocs & C -typedef struct clinkedlist_node { - void *data; - struct clinkedlist_node *next; -} clinkedlist_node_t; - -typedef struct clinkedlist { - clinkedlist_node_t *head; - clinkedlist_node_t *tail; - uint64_t length; - void* (*alloc)(size_t size); - void (*free)(void *ptr, size_t size); -} clinkedlist_t; - -clinkedlist_t *clinkedlist_create(); -void clinkedlist_destroy(clinkedlist_t *list); -clinkedlist_t *clinkedlist_clone(const clinkedlist_t *list); -void clinkedlist_push_front(clinkedlist_t *list, void *data); -void *clinkedlist_pop_front(clinkedlist_t *list); -clinkedlist_node_t *clinkedlist_insert_after(clinkedlist_t *list, clinkedlist_node_t *node, void *data); - -static inline void clinkedlist_push(clinkedlist_t *list, void *data){ - clinkedlist_insert_after(list, list->tail, data); -} - -void *clinkedlist_remove(clinkedlist_t *list, clinkedlist_node_t *node); -void clinkedlist_update(clinkedlist_t *list, clinkedlist_node_t *node, void *new_data); -uint64_t clinkedlist_length(const clinkedlist_t *list); -uint64_t clinkedlist_size_bytes(const clinkedlist_t *list); -clinkedlist_node_t *clinkedlist_find(clinkedlist_t *list, void *key, int (*cmp)(void *, void *)); -void clinkedlist_for_each(const clinkedlist_t *list, void (*func)(void *)); - -#ifdef __cplusplus -} -#endif diff --git a/shared/data_struct/linked_list.hpp b/shared/data_struct/linked_list.hpp deleted file mode 100644 index d0061239..00000000 --- a/shared/data_struct/linked_list.hpp +++ /dev/null @@ -1,146 +0,0 @@ -#pragma once -#include "types.h" - -extern "C" { -#include "linked_list.h" -} - -//TODO: review allocs & C -template -class LinkedList { -public: - struct Node { - T data; - Node* next; - }; - - Node* head = nullptr; - Node* tail = nullptr; - uint64_t length = 0; - - void* (*alloc_func)(size_t) = malloc; - void (*free_func)(void*,size_t) = free_sized; - - Node* alloc_node(const T& value) { - Node* n = reinterpret_cast(alloc_func(sizeof(Node))); - n->data = value; - n->next = nullptr; - return n; - } - - void free_node(Node* n) { - free_func(n); - } - -public: - LinkedList() = default; - - LinkedList(const LinkedList& other) { - for (Node* it = other.head; it; it = it->next) { - push_front(it->data); - } - LinkedList tmp; - while (!empty()) tmp.push_front(pop_front()); - *this = tmp; - } - - ~LinkedList() { - while (!empty()) pop_front(); - } - - LinkedList& operator=(const LinkedList& other) { - if (this != &other) { - while (!empty()) pop_front(); - for (Node* it = other.head; it; it = it->next) { - push_front(it->data); - } - LinkedList tmp; - while (!empty()) tmp.push_front(pop_front()); - head = tmp.head; - tail = tmp.tail; - length = tmp.length; - tmp.head = tmp.tail = nullptr; - tmp.length = 0; - } - return *this; - } - - void push_front(const T& value) { - Node* n = alloc_node(value); - n->next = head; - head = n; - if (!tail) tail = n; - ++length; - } - - T pop_front() { - if (!head) return T(); - Node* n = head; - head = head->next; - if (!head) tail = nullptr; - T val = n->data; - free_node(n); - --length; - return val; - } - - Node* insert_after(Node* node, const T& value) { - if (!node) { - push_front(value); - return head; - } - Node* n = alloc_node(value); - n->next = node->next; - node->next = n; - if (tail == node) tail = n; - ++length; - return n; - } - - T remove(Node* node) { - if (!node) return T(); - if (node == head) return pop_front(); - Node* prev = head; - while (prev && prev->next != node) prev = prev->next; - if (!prev) return T(); - prev->next = node->next; - if (node == tail) tail = prev; - T val = node->data; - free_node(node); - --length; - return val; - } - - void update(Node* node, const T& value) { - if (node) node->data = value; - } - - uint64_t size() const { - return length; - } - - bool empty() const { - return length == 0; - } - - Node* begin() const { - return head; - } - - Node* end() const { - return nullptr; - } - - template - Node* find(Predicate pred) const { - for (Node* it = head; it; it = it->next) { - if (pred(it->data)) return it; - } - return nullptr; - } - - void set_allocator(void* (*alloc)(size_t), void (*dealloc)(void*, size_t)) { - alloc_func = alloc; - free_func = dealloc; - } -}; diff --git a/shared/data_struct/p_queue.c b/shared/data_struct/p_queue.c deleted file mode 100644 index b50ff335..00000000 --- a/shared/data_struct/p_queue.c +++ /dev/null @@ -1,58 +0,0 @@ -#include "p_queue.h" -#include "syscalls/syscalls.h" - -bool p_queue_insert(p_queue_t *root, void* ptr, uint64_t value){ - if (root->size == root->max_size) return false; - root->array[root->size] = (p_queue_item){ptr, value}; - if (value < root->max_priority){ - root->max_priority = value; - root->max_priority_index = root->size; - } - root->size++; - return true; -} - -int p_queue_peek(p_queue_t*root){ - uint64_t max_priority; - int index = 0; - for (int i = 0; i < root->size; i++){ - if (root->array[i].val < max_priority){ - index = i; - max_priority = root->array[i].val; - } - } - return index; -} - -void* p_queue_pop(p_queue_t *root){ - int index = root->max_priority_index; - void *item = root->array[index].ptr; - root->max_priority = UINT64_MAX; - for (int i = 0; i < root->size-1; i++){ - if (i >= index) root->array[i] = root->array[i+1]; - if (root->array[i].val < root->max_priority){ - root->max_priority_index = i; - root->max_priority = root->array[i].val; - } - } - root->size--; - return item; -} - -void p_queue_traverse(p_queue_t *root){ - for (int i = 0; i < root->size; i++){ - printf("[%i] = %i",i, root->array[i].val); - } -} - -p_queue_t* p_queue_create(int max){ - p_queue_t *root = malloc(sizeof(p_queue_t) + (sizeof(p_queue_item) * max)); - root->max_priority = UINT64_MAX; - root->max_size = max; - root->array = (p_queue_item*)((uintptr_t)root + sizeof(p_queue_t)); - return root; -} - -void p_queue_free(p_queue_t *root){ - free_sized(root, sizeof(p_queue_t) + (sizeof(p_queue_item) * root->max_size)); -} \ No newline at end of file diff --git a/shared/data_struct/p_queue.h b/shared/data_struct/p_queue.h deleted file mode 100644 index 51825272..00000000 --- a/shared/data_struct/p_queue.h +++ /dev/null @@ -1,25 +0,0 @@ -#pragma once - -#include "types.h" - -//TODO: completely unoptimized. Heap? - -//lower number = higher priority -typedef struct p_queue_item { - void* ptr; - uint64_t val; -} p_queue_item; - -typedef struct p_queue_t { - p_queue_item *array; - int size, max_size; - uint64_t max_priority; - int max_priority_index; -} p_queue_t; - -bool p_queue_insert(p_queue_t *root, void* ptr, uint64_t value); -int p_queue_peek(p_queue_t*root); -void* p_queue_pop(p_queue_t *root); -void p_queue_traverse(p_queue_t *root); -p_queue_t* p_queue_create(int max); -void p_queue_free(p_queue_t *root); \ No newline at end of file diff --git a/shared/data_struct/queue.c b/shared/data_struct/queue.c deleted file mode 100644 index d34ef812..00000000 --- a/shared/data_struct/queue.c +++ /dev/null @@ -1,69 +0,0 @@ -#include "queue.h" -#include "std/memory.h" - -void cqueue_init(CQueue* q, uint64_t max_capacity, uint64_t elem_size) { - q->buffer = NULL; - q->capacity = max_capacity; - q->max_capacity = max_capacity; - q->elem_size = elem_size; - q->head = q->tail = q->length = 0; - if (max_capacity > 0) { - uintptr_t b = (uintptr_t)malloc(max_capacity * elem_size); - if (b) q->buffer = (void*)b; - } -} - -int32_t cqueue_enqueue(CQueue* q, const void* item) { - if (!q) return 0; - if (q->max_capacity > 0) { - if (q->length == q->capacity) return 0; - } else { - if (q->length == q->capacity) { - uint64_t nc = q->capacity > 0 ? q->capacity * 2 : 4; - uintptr_t nb = (uintptr_t)malloc(nc * q->elem_size); - if (!nb) return 0; - void* newb = (void*)nb; - for (uint64_t i = 0; i < q->length; ++i) { - uint64_t idx = (q->tail + i) % q->capacity; - memcpy((uint8_t*)newb + i * q->elem_size, - (uint8_t*)q->buffer + idx * q->elem_size, - q->elem_size); - } - if (q->buffer) free_sized(q->buffer, q->capacity * q->elem_size); - q->buffer = newb; - q->capacity = nc; - q->head = q->length; - q->tail = 0; - } - } - memcpy((uint8_t*)q->buffer + q->head * q->elem_size, item, q->elem_size); - q->head = (q->head + 1) % q->capacity; - q->length++; - return 1; -} - -int32_t cqueue_dequeue(CQueue* q, void* out) { - if (!q || q->length == 0) return 0; - memcpy(out, (uint8_t*)q->buffer + q->tail * q->elem_size, q->elem_size); - q->tail = (q->tail + 1) % q->capacity; - q->length--; - return 1; -} - -int32_t cqueue_is_empty(const CQueue* q) { - return (!q || q->length == 0) ? 1 : 0; -} - -uint64_t cqueue_size(const CQueue* q) { - return q ? q->length : 0; -} - -void cqueue_clear(CQueue* q) { - if (!q) return; - q->head = q->tail = q->length = 0; -} - -void cqueue_destroy(CQueue* q) { - if (!q) return; - if (q->buffer) free_sized(q->buffer, q->capacity * q->elem_size); -} diff --git a/shared/data_struct/queue.h b/shared/data_struct/queue.h deleted file mode 100644 index 00d721a3..00000000 --- a/shared/data_struct/queue.h +++ /dev/null @@ -1,32 +0,0 @@ -#pragma once -#include "types.h" - -#ifdef __cplusplus -extern "C" { -#endif - -//TODO: review allocs & C -typedef struct CQueue { - void* buffer; - uint64_t capacity; // current queue size - uint64_t max_capacity; // 0 = infinite - uint64_t elem_size; - uint64_t head; - uint64_t tail; - uint64_t length; -} CQueue; - -extern void* malloc(size_t); -extern void free_sized(void*, size_t); - -void cqueue_init(CQueue* q, uint64_t max_capacity, uint64_t elem_size); -int32_t cqueue_enqueue(CQueue* q, const void* item); -int32_t cqueue_dequeue(CQueue* q, void* out); -int32_t cqueue_is_empty(const CQueue* q); -uint64_t cqueue_size(const CQueue* q); -void cqueue_clear(CQueue* q); -void cqueue_destroy(CQueue* q); - -#ifdef __cplusplus -} -#endif diff --git a/shared/data_struct/queue.hpp b/shared/data_struct/queue.hpp deleted file mode 100644 index eedbd3a9..00000000 --- a/shared/data_struct/queue.hpp +++ /dev/null @@ -1,88 +0,0 @@ -#pragma once -#include "types.h" -#include "std/string.h" -#include "std/memory.h" -#include "queue.h" - -//TODO: review allocs & C -template -class Queue { -public: - explicit Queue(uint64_t capacity = 0) { - max_capacity = capacity; - this->capacity = capacity; - if (capacity > 0) { - uintptr_t mem = (uintptr_t)malloc(capacity * sizeof(T)); - if (mem) { - buffer = reinterpret_cast(mem); - } - } - } - - ~Queue() { - if (buffer) { - free_sized(buffer, capacity * sizeof(T)); - } - } - - bool enqueue(const T& value) { - if (max_capacity > 0 && length == capacity) return false; - if (max_capacity == 0 && length == capacity) grow_if_needed(); - if (!buffer) return false; - - buffer[head] = value; - head = (head + 1) % capacity; - ++length; - return true; - } - - bool dequeue(T& out) { - if (length == 0 || !buffer) return false; - out = buffer[tail]; - tail = (tail + 1) % capacity; - --length; - return true; - } - - bool is_empty() const { - return length == 0; - } - - uint64_t size() const { - return length; - } - - void clear() { - head = tail = length = 0; - } - -private: - T* buffer = nullptr; - uint64_t capacity = 0; - uint64_t max_capacity = 0; // 0 infinite - uint64_t head = 0; - uint64_t tail = 0; - uint64_t length = 0; - - void grow_if_needed() { - uint64_t new_cap = (capacity > 0) ? capacity * 2 : 4; - uintptr_t new_mem = (uintptr_t)malloc(new_cap * sizeof(T)); - if (!new_mem) return; - - T* new_buf = reinterpret_cast(new_mem); - for (uint64_t i = 0; i < length; ++i) { - uint64_t idx = (tail + i) % capacity; - new_buf[i] = buffer[idx]; - } - - if (buffer) { - free_sized(buffer, capacity * sizeof(T)); - } - - buffer = new_buf; - capacity = new_cap; - tail = 0; - head = length; - } -}; - diff --git a/shared/data_struct/ring_buffer.c b/shared/data_struct/ring_buffer.c deleted file mode 100644 index f52b5e6b..00000000 --- a/shared/data_struct/ring_buffer.c +++ /dev/null @@ -1,57 +0,0 @@ -#include "ring_buffer.h" -#include "std/memory.h" - -void cring_init(CRingBuffer* rb, void* storage, uint64_t capacity, uint64_t elem_size) { - rb->buffer = storage; - rb->capacity = capacity; - rb->element_size = elem_size; - rb->head = rb->tail = 0; - rb->full = 0; -} - -uint64_t cring_capacity(const CRingBuffer* rb) { - return rb->capacity; -} - -int32_t cring_push(CRingBuffer* rb, const void* item) { - if (rb->full) return 0; - - uint8_t* base = (uint8_t*)rb->buffer; - void* dest = base + (rb->head * rb->element_size); - - for (uint64_t i = 0; i < rb->element_size; ++i) { - ((uint8_t*)dest)[i] = ((const uint8_t*)item)[i]; - } - - rb->head = (rb->head + 1) % rb->capacity; - rb->full = (rb->head == rb->tail); - return 1; -} - -int32_t cring_pop(CRingBuffer* rb, void* out) { - if (!rb->full && (rb->head == rb->tail)) return 0; - - uint8_t* base = (uint8_t*)rb->buffer; - void* src = base + (rb->tail * rb->element_size); - - for (uint64_t i = 0; i < rb->element_size; ++i) { - ((uint8_t*)out)[i] = ((uint8_t*)src)[i]; - } - - rb->tail = (rb->tail + 1) % rb->capacity; - rb->full = 0; - return 1; -} - -int32_t cring_is_empty(const CRingBuffer* rb) { - return (!rb->full && (rb->head == rb->tail)); -} - -int32_t cring_is_full(const CRingBuffer* rb) { - return rb->full; -} - -void cring_clear(CRingBuffer* rb) { - rb->head = rb->tail = 0; - rb->full = 0; -} diff --git a/shared/data_struct/ring_buffer.h b/shared/data_struct/ring_buffer.h deleted file mode 100644 index 541ad44c..00000000 --- a/shared/data_struct/ring_buffer.h +++ /dev/null @@ -1,28 +0,0 @@ -#pragma once -#include "types.h" - -#ifdef __cplusplus -extern "C" { -#endif - -//TODO: review allocs & C -typedef struct CRingBuffer { - void* buffer; - uint64_t capacity; - uint64_t element_size; - uint64_t head; - uint64_t tail; - int32_t full; -} CRingBuffer; - -void cring_init(CRingBuffer* rb, void* storage, uint64_t capacity, uint64_t elem_size); -int32_t cring_push(CRingBuffer* rb, const void* item); -int32_t cring_pop(CRingBuffer* rb, void* out); -int32_t cring_is_empty(const CRingBuffer* rb); -int32_t cring_is_full(const CRingBuffer* rb); -void cring_clear(CRingBuffer* rb); -uint64_t cring_capacity(const CRingBuffer* rb); - -#ifdef __cplusplus -} -#endif diff --git a/shared/data_struct/ring_buffer.hpp b/shared/data_struct/ring_buffer.hpp deleted file mode 100644 index d194a608..00000000 --- a/shared/data_struct/ring_buffer.hpp +++ /dev/null @@ -1,117 +0,0 @@ -#pragma once -#include "types.h" -#include "std/memory.h" - -//TODO: review allocs & C -template -class RingBuffer { -private: - T data[Capacity]; - uint64_t head = 0; - uint64_t tail = 0; - int32_t full = 0; - -public: - RingBuffer() : head(0), tail(0), full(0) {} - - uint64_t push_buf(const T* src, uint64_t n) { - if (!src || !n) return 0; - uint64_t used = size(); - if (used >= Capacity) return 0; - uint64_t avail = Capacity - used; - uint64_t to = (n < avail) ? n : avail; - uint64_t cont = 0; - - if (!full && head < tail) cont = tail - head; - else cont = Capacity - head; - - uint64_t first = (to < cont) ? to : cont; - memcpy(data + head, src, first * sizeof(T)); - head = (head + first) % Capacity; - - uint64_t rem = to - first; - if (rem) { - memcpy(data + head, src + first, rem * sizeof(T)); - head = (head + rem) % Capacity; - } - - full = (head == tail); - return to; - } - - uint64_t pop_buf(T* dst, uint64_t n) { - if (!dst || !n) return 0; - uint64_t used = size(); - if (!used) return 0; - uint64_t to = (n < used) ? n : used; - uint64_t cont = 0; - - if (full || tail >= head) cont = Capacity - tail; - else cont = head - tail; - - uint64_t first = (to < cont) ? to : cont; - memcpy(dst, data + tail, first * sizeof(T)); - tail = (tail + first) % Capacity; - full = 0; - - uint64_t rem = to - first; - if (rem) { - memcpy(dst + first, data + tail, rem * sizeof(T)); - tail = (tail + rem) % Capacity; - } - - return to; - } - - int32_t push(const T& item) { - if (full) return 0; - data[head] = item; - head = (head + 1) % Capacity; - full = (head == tail); - return 1; - } - - int32_t pop(T& out) { - if (is_empty()) return 0; - out = data[tail]; - tail = (tail + 1) % Capacity; - full = 0; - return 1; - } - - int32_t is_empty() const { - return (!full && head == tail); - } - - int32_t is_full() const { - return full; - } - - void clear() { - head = tail = 0; - full = 0; - } - - uint64_t size() const { - if (full) return Capacity; - if (head >= tail) return head - tail; - return Capacity + head - tail; - } - - static constexpr uint64_t capacity() { - return Capacity; - } - - const T& peek() const { - return data[tail]; - } - - const T& at(uint32_t index) const { - return data[(tail + index) % Capacity]; - } - - T& at(uint32_t index) { - return data[(tail + index) % Capacity]; - } -}; - diff --git a/shared/files/buffer.c b/shared/files/buffer.c deleted file mode 100644 index 1e8cf8a1..00000000 --- a/shared/files/buffer.c +++ /dev/null @@ -1,56 +0,0 @@ -#include "buffer.h" -#include "syscalls/syscalls.h" - -buffer buffer_create(size_t size, bool can_grow, bool circular){ - return (buffer){ - .buffer = zalloc(size), - .buffer_size = 0, - .limit = size, - .can_grow = can_grow, - .circular = circular, - .cursor = 0, - }; -} - -void buffer_write(buffer *buf, char* fmt, ...){ - __attribute__((aligned(16))) va_list args; - va_start(args, fmt); - buffer_write_va(buf, fmt, args); - //TODO: circular - va_end(args); -} - -void buffer_write_va(buffer *buf, char* fmt, va_list args){ - size_t n = string_format_va_buf(fmt, buf->buffer+buf->cursor, buf->limit-buf->cursor, args); - buf->cursor += n; - buf->buffer_size += n; - if (buf->can_grow && buf->buffer_size > buf->limit-256){ - size_t new_size = buf->limit * 2; - buf->buffer = realloc_sized(buf->buffer, buf->limit, new_size); - buf->limit = new_size; - } -} - -void buffer_write_const(buffer *buf, char *lit){ - size_t lit_size = strlen(lit); - buffer_write_lim(buf, lit, lit_size); -} - -void buffer_write_lim(buffer *buf, char *lit, size_t lit_size){ - if (buf->limit - buf->buffer_size <= lit_size){ - if (buf->can_grow){ - size_t new_size = buf->limit; - buf->buffer = realloc_sized(buf->buffer, buf->limit, new_size); - buf->limit = new_size; - } else return; - //TODO: circular - } - for (size_t i = 0; i < lit_size; i++){ - buf->buffer[buf->cursor++] = lit[i]; - } - buf->buffer_size += lit_size; -} - -void buffer_write_space(buffer *buf){ - buffer_write_const(buf, " "); -} \ No newline at end of file diff --git a/shared/files/buffer.h b/shared/files/buffer.h deleted file mode 100644 index 45bf9937..00000000 --- a/shared/files/buffer.h +++ /dev/null @@ -1,20 +0,0 @@ -#pragma once - -#include "types.h" -#include "std/args.h" - -typedef struct { - char* buffer; - size_t buffer_size; - size_t limit; - bool can_grow; - bool circular; - uintptr_t cursor; -} buffer; - -buffer buffer_create(size_t size, bool can_grow, bool circular); -void buffer_write(buffer *buf, char* fmt, ...); -void buffer_write_va(buffer *buf, char* fmt, va_list args); -void buffer_write_const(buffer *buf, char *lit); -void buffer_write_lim(buffer *buf, char *lit, size_t size); -void buffer_write_space(buffer *buf); \ No newline at end of file diff --git a/shared/files/fs.h b/shared/files/fs.h deleted file mode 100644 index 7c0a802a..00000000 --- a/shared/files/fs.h +++ /dev/null @@ -1,24 +0,0 @@ -#pragma once - -#define FD_INVALID 0 -#define FD_IN 1 -#define FD_OUT 2 - -typedef struct file { - uint64_t id; - size_t size; - uint64_t cursor; -} file; - -typedef uint64_t file_offset; - -typedef enum SEEK_TYPE { - SEEK_ABSOLUTE, - SEEK_RELATIVE -} SEEK_TYPE; - -typedef enum FS_RESULT { - FS_RESULT_DRIVER_ERROR, - FS_RESULT_SUCCESS, - FS_RESULT_NOTFOUND, -} FS_RESULT; \ No newline at end of file diff --git a/shared/files/helpers.c b/shared/files/helpers.c deleted file mode 100644 index 890dba10..00000000 --- a/shared/files/helpers.c +++ /dev/null @@ -1,20 +0,0 @@ -#include "helpers.h" -#include "syscalls/syscalls.h" - -#ifndef CROSS - -void traverse_directory(char *directory, bool recursive, dir_traverse func){ - print("[FS implementation error] Traverse directory not implemented for [REDACTED]"); -} - -char* get_current_dir(){ - print("[FS implementation error] Current directory not implemented for [REDACTED]"); - return 0; -} - -char* gethomedir(){ - print("[FS implementation error] Home directory not implemented for [REDACTED]"); - return 0; -} - -#endif \ No newline at end of file diff --git a/shared/files/helpers.h b/shared/files/helpers.h deleted file mode 100644 index 9037bca2..00000000 --- a/shared/files/helpers.h +++ /dev/null @@ -1,11 +0,0 @@ -#pragma once - -#include "types.h" - -typedef void (*dir_traverse)(const char *directory, const char* name); - -void traverse_directory(char *directory, bool recursive, dir_traverse func); - -char* get_current_dir(); - -char* gethomedir(); \ No newline at end of file diff --git a/shared/image/bmp.c b/shared/image/bmp.c deleted file mode 100644 index e3b3807b..00000000 --- a/shared/image/bmp.c +++ /dev/null @@ -1,86 +0,0 @@ -#include "bmp.h" -#include "math/math.h" -#include "syscalls/syscalls.h" - -typedef struct bmp_header { - char signature[2]; - uint32_t file_size; - uint32_t rsvd; - uint32_t data_offset; - - //DIB - BITMAPINFOHEADER - uint32_t dib_size; - int32_t width; - int32_t height; - uint16_t planes;//Must be 1 - uint16_t bpp; - uint32_t compression;//Table - uint32_t img_size; - - int32_t horizontal_ppm; - int32_t vertical_ppm; - - uint32_t num_colors;//0 is 2^n - uint32_t important_colors;//0 is all, ignored -}__attribute__((packed)) bmp_header; - -image_info bmp_get_info(void * file, size_t size){ - if (size < sizeof(bmp_header)) return (image_info){0,0}; - bmp_header *header = (bmp_header*)file; - return (image_info){ - .width = header->width, - .height = abs(header->height) - }; -} - -void bmp_read_image(void *file, size_t size, uint32_t *buf){ - if (size < sizeof(bmp_header)){ - printf("Wrong file size"); - return; - } - bmp_header *header = (bmp_header*)file; - if (size < header->data_offset + header->img_size || size < header->file_size){ - printf("Wrong file size"); - return; - } - uintptr_t color_data = (uintptr_t)file + header->data_offset; - uint16_t increment = header->bpp/8; - uint32_t height = abs(header->height); - uint32_t width = (uint32_t)header->width; - bool flipped = header->height > 0; - uint32_t padding = 4 - (((header->bpp/8) * width) % 4); - if (padding == 4) padding = 0; - uint32_t padded = ((header->bpp/8) * width) + padding; - for (uint32_t y = 0; y < height; y++){ - for (uint32_t x = 0; x < (uint32_t)header->width; x++) - buf[(y * header->width) + x] = get_bpp_converted_color(header->bpp, color_data + ((flipped ? height - y - 1 : y) * padded) + x * increment); - } -} - -void* load_bmp(char *path, image_info *info){ - file descriptor = {}; - FS_RESULT res = openf(path, &descriptor); - void *img = 0; - image_info img_info; - if (res == FS_RESULT_SUCCESS){ - void *img_file = (void*)malloc(descriptor.size); - readf(&descriptor, img_file, descriptor.size); - img_info = bmp_get_info(img_file, descriptor.size); - closef(&descriptor); - if (img_info.width > 0 && img_info.height > 0){ - size_t image_size = img_info.width * img_info.height * system_bpp; - img = (void*)malloc(image_size); - bmp_read_image(img_file, descriptor.size, img); - *info = img_info; - return img; - } else { - printf("Wrong image size %i",img_info.width,img_info.height); - *info = (image_info){0, 0}; - return 0; - } - } else { - printf("Failed to open image"); - *info = (image_info){0, 0}; - return 0; - } -} diff --git a/shared/image/bmp.h b/shared/image/bmp.h deleted file mode 100644 index 7f4e23f7..00000000 --- a/shared/image/bmp.h +++ /dev/null @@ -1,9 +0,0 @@ -#pragma once - -#include "types.h" -#include "image.h" - -image_info bmp_get_info(void * file, size_t size); -void bmp_read_image(void *file, size_t size, uint32_t *buf); - -void* load_bmp(char *path, image_info *info); \ No newline at end of file diff --git a/shared/image/image.c b/shared/image/image.c deleted file mode 100644 index 9e1966c5..00000000 --- a/shared/image/image.c +++ /dev/null @@ -1,129 +0,0 @@ -#include "image.h" -#include "std/memory_access.h" -#include "syscalls/syscalls.h" -#include "bmp.h" -#include "png.h" - -uint32_t get_color_bpp(uint16_t bpp, uintptr_t value_ptr){ - switch (bpp) { - case 1: return 0; - - case 4: return 0; - - case 8: return 0; - - case 24: return ARGB(0, read8(value_ptr + 0), read8(value_ptr + 1), read8(value_ptr + 2)); - - case 32: { - uint32_t pix = value_ptr % 8 == 0 ? *(uint32_t*)value_ptr : read_unaligned32((uint32_t*)value_ptr); - pix = (((pix >> 24) & 0xFF) << 24) | (((pix >> 0) & 0xFF) << 16) | (((pix >> 8) & 0xFF) << 8) | (((pix >> 16) & 0xFF) << 0); - return pix; - } - } - return 0; -} - -uint32_t convert_bpp_color(uint16_t bpp, uint32_t color){ - switch (bpp) { - case 1: return 0; - - case 4: return 0; - - case 8: return 0; - - case 24: return (0xFF << 24) | color; - - case 32: return color; - } - return 0; -} - -uint32_t get_bpp_converted_color(uint16_t bpp, uintptr_t value_ptr){ - switch (bpp) { - case 1: return 0; - - case 4: return 0; - - case 8: return 0; - - case 24: return ARGB(0xFF, read8(value_ptr + 2), read8(value_ptr + 1), read8(value_ptr)); - - case 32: return value_ptr % 8 == 0 ? *(uint32_t*)value_ptr : read_unaligned32((uint32_t*)value_ptr); - } - return 0; -} - -#ifndef CROSS - -void* load_image(char *path, image_info *info, IMAGE_FORMATS format){ - file descriptor = {}; - FS_RESULT res = openf(path, &descriptor); - void *img = 0; - image_info img_info; - if (res == FS_RESULT_SUCCESS){ - void *img_file = (void*)malloc(descriptor.size); - readf(&descriptor, img_file, descriptor.size); - switch (format) { - case PNG: - img_info = png_get_info(img_file, descriptor.size); - break; - case BMP: - img_info = bmp_get_info(img_file, descriptor.size); - break; - //Unknown can be handled by reading magic bytes - } - closef(&descriptor); - if (img_info.width > 0 && img_info.height > 0){ - size_t image_size = img_info.width * img_info.height * system_bpp; - img = (void*)malloc(image_size); - switch (format) { - case PNG: - png_read_image(img_file, descriptor.size, img); - break; - case BMP: - bmp_read_image(img_file, descriptor.size, img); - break; - } - *info = img_info; - return img; - } else { - printf("Wrong image size %i",img_info.width,img_info.height); - *info = (image_info){0, 0}; - return 0; - } - } else { - printf("Failed to open image"); - *info = (image_info){0, 0}; - return 0; - } -} - -//TODO: downsize & other interpolations -void* load_image_resized(char *path, image_info *info, IMAGE_FORMATS format, uint32_t new_width, uint32_t new_height){ - image_info old_info = {}; - void *old_img = load_image(path, &old_info, format); - info->width = new_width; - info->height = new_height; - void *new_img = malloc(new_width * new_height * sizeof(uint32_t)); - if (new_width < old_info.width || new_height < old_info.height){ - printf("[IMG warning] image downscaling is not properly implemented or tested. Use at your own risk"); - } - rescale_image(old_info.width, old_info.height, new_width, new_height, old_img, new_img); - free_sized(old_img, old_info.width * old_info.height * sizeof(uint32_t)); - return new_img; -} - -void rescale_image(uint32_t old_width, uint32_t old_height, uint32_t new_width, uint32_t new_height, uint32_t *old_img, uint32_t* new_img){ - - for (uint32_t y = 0; y < new_height; y++){ - uint32_t oy = y * old_height/new_height; - uint32_t *old_row = old_img + (oy * old_width); - uint32_t *new_row = new_img + (y * new_width); - for (uint32_t x = 0; x < new_width; x++){ - uint32_t ox = x * old_width/new_width; - new_row[x] = old_row[ox]; - } - } -} - -#endif diff --git a/shared/image/image.h b/shared/image/image.h deleted file mode 100644 index 4f7edaae..00000000 --- a/shared/image/image.h +++ /dev/null @@ -1,25 +0,0 @@ -#pragma once - -#include "types.h" - -typedef enum IMAGE_FORMATS { - BMP, - PNG -} IMAGE_FORMATS; - -#define ARGB(a,r,g,b) ((a & 0xFF) << 24) | ((r & 0xFF) << 16) | ((g & 0xFF) << 8) | (b & 0xFF) -#define system_bpp 4 - -typedef struct image_info { - uint32_t width, height; -} image_info; - -//TODO: expand image conversion to handle all cases (palette, grayscale, gs-alpha...) -uint32_t get_bpp_converted_color(uint16_t bpp, uintptr_t value_ptr); -uint32_t get_color_bpp(uint16_t bpp, uintptr_t value_ptr); -uint32_t convert_bpp_color(uint16_t bpp, uint32_t color); -void* load_image(char *path, image_info *info, IMAGE_FORMATS format); - -void* load_image_resized(char *path, image_info *info, IMAGE_FORMATS format, uint32_t new_width, uint32_t new_height); - -void rescale_image(uint32_t old_width, uint32_t old_height, uint32_t new_width, uint32_t new_height, uint32_t *old_img, uint32_t* new_img); \ No newline at end of file diff --git a/shared/image/png.c b/shared/image/png.c deleted file mode 100644 index 9d78dcf3..00000000 --- a/shared/image/png.c +++ /dev/null @@ -1,190 +0,0 @@ -#include "png.h" -#include "image.h" -#include "syscalls/syscalls.h" -#include "std/memory_access.h" -#include "std/memory.h" -#include "math/math.h" -#include "compression/deflate.h" - -typedef struct png_chunk_hdr { - uint32_t length; - char type[4]; - //Followed by data and 4 byte crc -} png_chunk_hdr; - -typedef struct png_ihdr { - uint32_t width; - uint32_t height; - uint8_t depth;// (1 byte, values 1, 2, 4, 8, or 16) - uint8_t color_type;// (1 byte, values 0, 2, 3, 4, or 6) - uint8_t compression;// (1 byte, value 0) - uint8_t filter;// (1 byte, value 0) - uint8_t interlace;// (1 byte, values 0 "no interlace" or 1 "Adam7 interlace") -} png_ihdr; - -image_info png_get_info(void * file, size_t size){ - uint64_t header = *(uint64_t*)file; - if (header != 0xA1A0A0D474E5089){ - printf("Wrong PNG header %x",header); - return (image_info){0,0}; - } - uintptr_t p = (uintptr_t)file + sizeof(uint64_t); - png_chunk_hdr *hdr = (png_chunk_hdr*)p; - if (strstart_case(hdr->type, "IHDR",true) != 4){ - printf("Couldn't find png IHDR"); - return (image_info){0,0}; - } - p += sizeof(png_chunk_hdr); - png_ihdr *ihdr = (png_ihdr*)p; - //Check the crc - return (image_info){__builtin_bswap32(ihdr->width),__builtin_bswap32(ihdr->height)}; -} - -uint8_t paeth_byte(uint8_t a, uint8_t b, uint8_t c){ - int16_t p = a + b - c; - uint16_t pa = abs(p - a); - uint16_t pb = abs(p - b); - uint16_t pc = abs(p - c); - - if (pa <= pb && pa <= pc) - return a % 256; - else if (pb <= pc) - return b % 256; - else - return c % 256; -} - -uint32_t paeth_predict(uint32_t a, uint32_t b, uint32_t c) { - uint8_t alpha = paeth_byte((a >> 24) & 0xFF, (b >> 24) & 0xFF, (c >> 24) & 0xFF); - uint8_t red = paeth_byte((a >> 16) & 0xFF, (b >> 16) & 0xFF, (c >> 16) & 0xFF); - uint8_t green = paeth_byte((a >> 8) & 0xFF, (b >> 8) & 0xFF, (c >> 8) & 0xFF); - uint8_t blue = paeth_byte(a & 0xFF, b & 0xFF, c & 0xFF); - return (alpha << 24) | (red << 16) | (green << 8) | blue; -} - -uint32_t png_filter_apply(uint32_t a, uint32_t b){ - uint8_t alpha = (((a >> 24) & 0xFF) + ((b >> 24) & 0xFF)) % 256; - uint8_t red = (((a >> 16) & 0xFF) + ((b >> 16) & 0xFF)) % 256; - uint8_t green = (((a >> 8) & 0xFF) + ((b >> 8) & 0xFF)) % 256; - uint8_t blue = ((a & 0xFF) + (b & 0xFF)) % 256; - return (alpha << 24) | (red << 16) | (green << 8) | blue; -} - -uint32_t png_average_apply(uint32_t a, uint32_t b){ - uint8_t alpha = (((a >> 24) & 0xFF) + ((b >> 24) & 0xFF))/2; - uint8_t red = (((a >> 16) & 0xFF) + ((b >> 16) & 0xFF))/2; - uint8_t green = (((a >> 8) & 0xFF) + ((b >> 8) & 0xFF))/2; - uint8_t blue = ((a & 0xFF) + (b & 0xFF))/2; - return ((alpha % 256) << 24) | ((red % 256) << 16) | ((green % 256) << 8) | (blue % 256); -} - -void png_process_raw(uintptr_t raw_img, uint32_t w, uint32_t h, uint16_t bpp, uint32_t *buf){ - const uint8_t bytes = bpp/8; - for (uint32_t y = 0; y < h; y++){ - uint8_t filter_type = *(uint8_t*)(raw_img + (((w * bytes) + 1) * y)); - for (uint32_t x = 0; x < w; x++){ - uint32_t current = get_color_bpp(bpp, (raw_img + (((w * bytes) + 1) * y) + 1 + (x*bytes))); - // if (y == 0) printf("%.8x",current); - switch (filter_type) { - case 0: - break; - case 1: - if (x > 0) current = png_filter_apply(current,buf[(y * w) + x - 1]); - break; - case 2: - if (y > 0) current = png_filter_apply(current,buf[((y-1) * w) + x]); - break; - case 3: { - uint32_t raw = x == 0 ? 0 : buf[(y * w) + x - 1]; - uint32_t prior = y == 0 ? 0 : buf[((y-1) * w) + x]; - current = png_filter_apply(current, png_average_apply(raw,prior)); - break; - } - case 4: { - uint32_t prev = x == 0 ? 0 : buf[(y * w) + x - 1]; - uint32_t top = y == 0 ? 0 : buf[((y - 1) * w) + x]; - uint32_t diag = y == 0 || x == 0 ? 0 : buf[((y - 1) * w) + x - 1]; - current = png_filter_apply(current, paeth_predict(prev, top, diag)); - break; - } - } - buf[(y * w) + x] = current; - } - } - for (uint32_t i = 0; i < h*w; i++) buf[i] = convert_bpp_color(bpp, buf[i]); -} - -uint16_t png_decode_bpp(png_ihdr *ihdr){ - switch (ihdr->color_type) { - case 0: return ihdr->depth;//Greyscale - case 2: return 3 * ihdr->depth;//TrueColor - case 3: return ihdr->depth;//IndexedColor - case 4: return 2 * ihdr->depth;//GrayScale with Alpha - case 6: return 4 * ihdr->depth;//Truecolor with alpha - } - return 0; -} - -void png_read_image(void *file, size_t size, uint32_t *buf){ - uint64_t header = *(uint64_t*)file; - if (header != 0xA1A0A0D474E5089){ - printf("Wrong PNG header %x",header); - return; - } - printf("File size %x",size); - uintptr_t p = (uintptr_t)file + sizeof(uint64_t); - png_chunk_hdr *hdr; - image_info info = {}; - uintptr_t out_buf = 0; - void *data_buf = 0; - uintptr_t data_cursor = 0; - uint16_t bpp = 0; - deflate_read_ctx ctx = {}; - do { - hdr = (png_chunk_hdr*)p; - uint32_t length = __builtin_bswap32(hdr->length); - if (strstart_case(hdr->type, "IHDR",true) == 4){ - png_ihdr *ihdr = (png_ihdr*)(p + sizeof(png_chunk_hdr)); - bpp = png_decode_bpp(ihdr); - info = (image_info){__builtin_bswap32(ihdr->width),__builtin_bswap32(ihdr->height)}; - } - if (strstart_case(hdr->type, "IDAT",true) == 4){ - if (info.width == 0 || info.height == 0){ - printf("Wrong image size"); - return; - } - if (!out_buf){ - out_buf = (uintptr_t)malloc((info.width * info.height * system_bpp) + info.height);//TODO: bpp might be too big, read image format - ctx.output_buf = (uint8_t*)out_buf; - } - if (!data_buf){ - data_buf = malloc(size); - } - memcpy((void*)((uintptr_t)data_buf + data_cursor), (void*)(p + sizeof(png_chunk_hdr)), length); - data_cursor += length; - // printf("Found some idat %x - %x",p + sizeof(png_chunk_hdr) - (uintptr_t)file, length); - } - p += sizeof(png_chunk_hdr) + __builtin_bswap32(hdr->length) + sizeof(uint32_t); - } while(strstart_case(hdr->type, "IEND",true) != 4); - deflate_decode(data_buf, data_cursor, &ctx); - png_process_raw(out_buf, info.width, info.height, bpp, buf); -} - -void* load_png(char *path, image_info *info){ - file descriptor = {}; - FS_RESULT res = openf(path, &descriptor); - void *img = 0; - void* file_img = malloc(descriptor.size); - readf(&descriptor, file_img, descriptor.size); - if (res != FS_RESULT_SUCCESS){ - closef(&descriptor); - printf("Couldn't open image"); - return 0; - } - closef(&descriptor); - *info = png_get_info(file_img, descriptor.size); - printf("info %ix%i",info->width,info->height); - img = malloc(info->width*info->height*system_bpp); - png_read_image(file_img, descriptor.size, img); - return img; -} diff --git a/shared/image/png.h b/shared/image/png.h deleted file mode 100644 index 8aab7056..00000000 --- a/shared/image/png.h +++ /dev/null @@ -1,9 +0,0 @@ -#pragma once - -#include "types.h" -#include "image.h" - -image_info png_get_info(void * file, size_t size); -void png_read_image(void *file, size_t size, uint32_t *buf); - -void* load_png(char *path, image_info *info); \ No newline at end of file diff --git a/shared/input_keycodes.c b/shared/input_keycodes.c deleted file mode 100644 index 67cf6f7a..00000000 --- a/shared/input_keycodes.c +++ /dev/null @@ -1,5 +0,0 @@ -#include "input_keycodes.h" - -char hid_to_char(unsigned char c){ - return hid_keycode_to_char[c]; -} \ No newline at end of file diff --git a/shared/input_keycodes.h b/shared/input_keycodes.h deleted file mode 100644 index 23ca0f4e..00000000 --- a/shared/input_keycodes.h +++ /dev/null @@ -1,316 +0,0 @@ -/** - * USB HID Keyboard scan codes as per USB spec 1.11 - * plus some additional codes - * - * Created by MightyPork, 2016 - * Public domain - * - * Adapted from: - * https://source.android.com/devices/input/keyboard-devices.html - */ -#pragma once - -#include "types.h" - -/** - * Modifier masks - used for the first byte in the HID report. - * NOTE: The second byte in the report is reserved, 0x00 - */ -#define KEY_MOD_LCTRL 0x01 -#define KEY_MOD_LSHIFT 0x02 -#define KEY_MOD_LALT 0x04 -#define KEY_MOD_LMETA 0x08 -#define KEY_MOD_RCTRL 0x10 -#define KEY_MOD_RSHIFT 0x20 -#define KEY_MOD_RALT 0x40 -#define KEY_MOD_RMETA 0x80 - -/** - * Scan codes - last N slots in the HID report (usually 6). - * 0x00 if no key pressed. - * - * If more than N keys are pressed, the HID reports - * KEY_ERR_OVF in all slots to indicate this condition. - */ - -#define KEY_NONE 0x00 // No key pressed -#define KEY_ERR_OVF 0x01 // Keyboard Error Roll Over - used for all slots if too many keys are pressed ("Phantom key") -// 0x02 // Keyboard POST Fail -// 0x03 // Keyboard Error Undefined -#define KEY_A 0x04 // Keyboard a and A -#define KEY_B 0x05 // Keyboard b and B -#define KEY_C 0x06 // Keyboard c and C -#define KEY_D 0x07 // Keyboard d and D -#define KEY_E 0x08 // Keyboard e and E -#define KEY_F 0x09 // Keyboard f and F -#define KEY_G 0x0a // Keyboard g and G -#define KEY_H 0x0b // Keyboard h and H -#define KEY_I 0x0c // Keyboard i and I -#define KEY_J 0x0d // Keyboard j and J -#define KEY_K 0x0e // Keyboard k and K -#define KEY_L 0x0f // Keyboard l and L -#define KEY_M 0x10 // Keyboard m and M -#define KEY_N 0x11 // Keyboard n and N -#define KEY_O 0x12 // Keyboard o and O -#define KEY_P 0x13 // Keyboard p and P -#define KEY_Q 0x14 // Keyboard q and Q -#define KEY_R 0x15 // Keyboard r and R -#define KEY_S 0x16 // Keyboard s and S -#define KEY_T 0x17 // Keyboard t and T -#define KEY_U 0x18 // Keyboard u and U -#define KEY_V 0x19 // Keyboard v and V -#define KEY_W 0x1a // Keyboard w and W -#define KEY_X 0x1b // Keyboard x and X -#define KEY_Y 0x1c // Keyboard y and Y -#define KEY_Z 0x1d // Keyboard z and Z - -#define KEY_1 0x1e // Keyboard 1 and ! -#define KEY_2 0x1f // Keyboard 2 and @ -#define KEY_3 0x20 // Keyboard 3 and # -#define KEY_4 0x21 // Keyboard 4 and $ -#define KEY_5 0x22 // Keyboard 5 and % -#define KEY_6 0x23 // Keyboard 6 and ^ -#define KEY_7 0x24 // Keyboard 7 and & -#define KEY_8 0x25 // Keyboard 8 and * -#define KEY_9 0x26 // Keyboard 9 and ( -#define KEY_0 0x27 // Keyboard 0 and ) - -#define KEY_ENTER 0x28 // Keyboard Return (ENTER) -#define KEY_ESC 0x29 // Keyboard ESCAPE -#define KEY_BACKSPACE 0x2a // Keyboard DELETE (Backspace) -#define KEY_TAB 0x2b // Keyboard Tab -#define KEY_SPACE 0x2c // Keyboard Spacebar -#define KEY_MINUS 0x2d // Keyboard - and _ -#define KEY_EQUAL 0x2e // Keyboard = and + -#define KEY_LEFTBRACE 0x2f // Keyboard [ and { -#define KEY_RIGHTBRACE 0x30 // Keyboard ] and } -#define KEY_BACKSLASH 0x31 // Keyboard \ and | -#define KEY_HASHTILDE 0x32 // Keyboard Non-US # and ~ -#define KEY_SEMICOLON 0x33 // Keyboard ; and : -#define KEY_APOSTROPHE 0x34 // Keyboard ' and " -#define KEY_GRAVE 0x35 // Keyboard ` and ~ -#define KEY_COMMA 0x36 // Keyboard , and < -#define KEY_DOT 0x37 // Keyboard . and > -#define KEY_SLASH 0x38 // Keyboard / and ? -#define KEY_CAPSLOCK 0x39 // Keyboard Caps Lock - -#define KEY_F1 0x3a // Keyboard F1 -#define KEY_F2 0x3b // Keyboard F2 -#define KEY_F3 0x3c // Keyboard F3 -#define KEY_F4 0x3d // Keyboard F4 -#define KEY_F5 0x3e // Keyboard F5 -#define KEY_F6 0x3f // Keyboard F6 -#define KEY_F7 0x40 // Keyboard F7 -#define KEY_F8 0x41 // Keyboard F8 -#define KEY_F9 0x42 // Keyboard F9 -#define KEY_F10 0x43 // Keyboard F10 -#define KEY_F11 0x44 // Keyboard F11 -#define KEY_F12 0x45 // Keyboard F12 - -#define KEY_SYSRQ 0x46 // Keyboard Print Screen -#define KEY_SCROLLLOCK 0x47 // Keyboard Scroll Lock -#define KEY_PAUSE 0x48 // Keyboard Pause -#define KEY_INSERT 0x49 // Keyboard Insert -#define KEY_HOME 0x4a // Keyboard Home -#define KEY_PAGEUP 0x4b // Keyboard Page Up -#define KEY_DELETE 0x4c // Keyboard Delete Forward -#define KEY_END 0x4d // Keyboard End -#define KEY_PAGEDOWN 0x4e // Keyboard Page Down -#define KEY_RIGHT 0x4f // Keyboard Right Arrow -#define KEY_LEFT 0x50 // Keyboard Left Arrow -#define KEY_DOWN 0x51 // Keyboard Down Arrow -#define KEY_UP 0x52 // Keyboard Up Arrow - -#define KEY_NUMLOCK 0x53 // Keyboard Num Lock and Clear -#define KEY_KPSLASH 0x54 // Keypad / -#define KEY_KPASTERISK 0x55 // Keypad * -#define KEY_KPMINUS 0x56 // Keypad - -#define KEY_KPPLUS 0x57 // Keypad + -#define KEY_KPENTER 0x58 // Keypad ENTER -#define KEY_KP1 0x59 // Keypad 1 and End -#define KEY_KP2 0x5a // Keypad 2 and Down Arrow -#define KEY_KP3 0x5b // Keypad 3 and PageDn -#define KEY_KP4 0x5c // Keypad 4 and Left Arrow -#define KEY_KP5 0x5d // Keypad 5 -#define KEY_KP6 0x5e // Keypad 6 and Right Arrow -#define KEY_KP7 0x5f // Keypad 7 and Home -#define KEY_KP8 0x60 // Keypad 8 and Up Arrow -#define KEY_KP9 0x61 // Keypad 9 and Page Up -#define KEY_KP0 0x62 // Keypad 0 and Insert -#define KEY_KPDOT 0x63 // Keypad . and Delete - -#define KEY_102ND 0x64 // Keyboard Non-US \ and | -#define KEY_COMPOSE 0x65 // Keyboard Application -#define KEY_POWER 0x66 // Keyboard Power -#define KEY_KPEQUAL 0x67 // Keypad = - -#define KEY_F13 0x68 // Keyboard F13 -#define KEY_F14 0x69 // Keyboard F14 -#define KEY_F15 0x6a // Keyboard F15 -#define KEY_F16 0x6b // Keyboard F16 -#define KEY_F17 0x6c // Keyboard F17 -#define KEY_F18 0x6d // Keyboard F18 -#define KEY_F19 0x6e // Keyboard F19 -#define KEY_F20 0x6f // Keyboard F20 -#define KEY_F21 0x70 // Keyboard F21 -#define KEY_F22 0x71 // Keyboard F22 -#define KEY_F23 0x72 // Keyboard F23 -#define KEY_F24 0x73 // Keyboard F24 - -#define KEY_OPEN 0x74 // Keyboard Execute -#define KEY_HELP 0x75 // Keyboard Help -#define KEY_PROPS 0x76 // Keyboard Menu -#define KEY_FRONT 0x77 // Keyboard Select -#define KEY_STOP 0x78 // Keyboard Stop -#define KEY_AGAIN 0x79 // Keyboard Again -#define KEY_UNDO 0x7a // Keyboard Undo -#define KEY_CUT 0x7b // Keyboard Cut -#define KEY_COPY 0x7c // Keyboard Copy -#define KEY_PASTE 0x7d // Keyboard Paste -#define KEY_FIND 0x7e // Keyboard Find -#define KEY_MUTE 0x7f // Keyboard Mute -#define KEY_VOLUMEUP 0x80 // Keyboard Volume Up -#define KEY_VOLUMEDOWN 0x81 // Keyboard Volume Down -// 0x82 Keyboard Locking Caps Lock -// 0x83 Keyboard Locking Num Lock -// 0x84 Keyboard Locking Scroll Lock -#define KEY_KPCOMMA 0x85 // Keypad Comma -// 0x86 Keypad Equal Sign -#define KEY_RO 0x87 // Keyboard International1 -#define KEY_KATAKANAHIRAGANA 0x88 // Keyboard International2 -#define KEY_YEN 0x89 // Keyboard International3 -#define KEY_HENKAN 0x8a // Keyboard International4 -#define KEY_MUHENKAN 0x8b // Keyboard International5 -#define KEY_KPJPCOMMA 0x8c // Keyboard International6 -// 0x8d Keyboard International7 -// 0x8e Keyboard International8 -// 0x8f Keyboard International9 -#define KEY_HANGEUL 0x90 // Keyboard LANG1 -#define KEY_HANJA 0x91 // Keyboard LANG2 -#define KEY_KATAKANA 0x92 // Keyboard LANG3 -#define KEY_HIRAGANA 0x93 // Keyboard LANG4 -#define KEY_ZENKAKUHANKAKU 0x94 // Keyboard LANG5 -// 0x95 Keyboard LANG6 -// 0x96 Keyboard LANG7 -// 0x97 Keyboard LANG8 -// 0x98 Keyboard LANG9 -// 0x99 Keyboard Alternate Erase -// 0x9a Keyboard SysReq/Attention -// 0x9b Keyboard Cancel -// 0x9c Keyboard Clear -// 0x9d Keyboard Prior -// 0x9e Keyboard Return -// 0x9f Keyboard Separator -// 0xa0 Keyboard Out -// 0xa1 Keyboard Oper -// 0xa2 Keyboard Clear/Again -// 0xa3 Keyboard CrSel/Props -// 0xa4 Keyboard ExSel - -// 0xb0 Keypad 00 -// 0xb1 Keypad 000 -// 0xb2 Thousands Separator -// 0xb3 Decimal Separator -// 0xb4 Currency Unit -// 0xb5 Currency Sub-unit -#define KEY_KPLEFTPAREN 0xb6 // Keypad ( -#define KEY_KPRIGHTPAREN 0xb7 // Keypad ) -// 0xb8 Keypad { -// 0xb9 Keypad } -// 0xba Keypad Tab -// 0xbb Keypad Backspace -// 0xbc Keypad A -// 0xbd Keypad B -// 0xbe Keypad C -// 0xbf Keypad D -// 0xc0 Keypad E -// 0xc1 Keypad F -// 0xc2 Keypad XOR -// 0xc3 Keypad ^ -// 0xc4 Keypad % -// 0xc5 Keypad < -// 0xc6 Keypad > -// 0xc7 Keypad & -// 0xc8 Keypad && -// 0xc9 Keypad | -// 0xca Keypad || -// 0xcb Keypad : -// 0xcc Keypad # -// 0xcd Keypad Space -// 0xce Keypad @ -// 0xcf Keypad ! -// 0xd0 Keypad Memory Store -// 0xd1 Keypad Memory Recall -// 0xd2 Keypad Memory Clear -// 0xd3 Keypad Memory Add -// 0xd4 Keypad Memory Subtract -// 0xd5 Keypad Memory Multiply -// 0xd6 Keypad Memory Divide -// 0xd7 Keypad +/- -// 0xd8 Keypad Clear -// 0xd9 Keypad Clear Entry -// 0xda Keypad Binary -// 0xdb Keypad Octal -// 0xdc Keypad Decimal -// 0xdd Keypad Hexadecimal - -#define KEY_LEFTCTRL 0xe0 // Keyboard Left Control -#define KEY_LEFTSHIFT 0xe1 // Keyboard Left Shift -#define KEY_LEFTALT 0xe2 // Keyboard Left Alt -#define KEY_LEFTMETA 0xe3 // Keyboard Left GUI -#define KEY_RIGHTCTRL 0xe4 // Keyboard Right Control -#define KEY_RIGHTSHIFT 0xe5 // Keyboard Right Shift -#define KEY_RIGHTALT 0xe6 // Keyboard Right Alt -#define KEY_RIGHTMETA 0xe7 // Keyboard Right GUI - -#define KEY_MEDIA_PLAYPAUSE 0xe8 -#define KEY_MEDIA_STOPCD 0xe9 -#define KEY_MEDIA_PREVIOUSSONG 0xea -#define KEY_MEDIA_NEXTSONG 0xeb -#define KEY_MEDIA_EJECTCD 0xec -#define KEY_MEDIA_VOLUMEUP 0xed -#define KEY_MEDIA_VOLUMEDOWN 0xee -#define KEY_MEDIA_MUTE 0xef -#define KEY_MEDIA_WWW 0xf0 -#define KEY_MEDIA_BACK 0xf1 -#define KEY_MEDIA_FORWARD 0xf2 -#define KEY_MEDIA_STOP 0xf3 -#define KEY_MEDIA_FIND 0xf4 -#define KEY_MEDIA_SCROLLUP 0xf5 -#define KEY_MEDIA_SCROLLDOWN 0xf6 -#define KEY_MEDIA_EDIT 0xf7 -#define KEY_MEDIA_SLEEP 0xf8 -#define KEY_MEDIA_COFFEE 0xf9 -#define KEY_MEDIA_REFRESH 0xfa -#define KEY_MEDIA_CALC 0xfb - -#ifndef __cplusplus -//TODO: properly handle keypad -static const char hid_keycode_to_char[256] = { - [0x04] = 'a', [0x05] = 'b', [0x06] = 'c', [0x07] = 'd', - [0x08] = 'e', [0x09] = 'f', [0x0A] = 'g', [0x0B] = 'h', - [0x0C] = 'i', [0x0D] = 'j', [0x0E] = 'k', [0x0F] = 'l', - [0x10] = 'm', [0x11] = 'n', [0x12] = 'o', [0x13] = 'p', - [0x14] = 'q', [0x15] = 'r', [0x16] = 's', [0x17] = 't', - [0x18] = 'u', [0x19] = 'v', [0x1A] = 'w', [0x1B] = 'x', - [0x1C] = 'y', [0x1D] = 'z', - [0x1E] = '1', [0x1F] = '2', [0x20] = '3', [0x21] = '4', - [0x22] = '5', [0x23] = '6', [0x24] = '7', [0x25] = '8', - [0x26] = '9', [0x27] = '0', - [0x28] = '\n', [0x2C] = ' ', [0x2D] = '-', [0x2E] = '=', - [0x2F] = '[', [0x30] = ']', [0x31] = '\\', [0x33] = ';', - [0x34] = '\'', [0x35] = '`', [0x36] = ',', [0x37] = '.', - [0x38] = '/', [0x58] = '\n', -}; -#else -extern "C" { -#endif -char hid_to_char(unsigned char c); - -static inline bool printable(unsigned char c){ - return c >= 'A' && c <='z'; -} - -#ifdef __cplusplus -} -#endif \ No newline at end of file diff --git a/shared/keyboard_input.h b/shared/keyboard_input.h deleted file mode 100644 index f115d1ff..00000000 --- a/shared/keyboard_input.h +++ /dev/null @@ -1,25 +0,0 @@ -#pragma once - -#include "types.h" - -#ifdef __cplusplus -extern "C" { -#endif - -typedef struct { - uint8_t modifier; - uint8_t rsvd; - char keys[6]; -} keypress; - -typedef enum in_event_type { KEY_RELEASE, KEY_PRESS, MOD_RELEASE, MOD_PRESS } in_event_type; - -typedef struct { - in_event_type type; - char key; - char modifier; -} kbd_event; - -#ifdef __cplusplus -} -#endif \ No newline at end of file diff --git a/shared/math/aabb2.c b/shared/math/aabb2.c deleted file mode 100644 index 864a4606..00000000 --- a/shared/math/aabb2.c +++ /dev/null @@ -1,69 +0,0 @@ -#include "aabb2.h" -#include "math.h" - -bool aabb2_line_intersect(aabb2 bb, vector2 origin, vector2 dir, float *t_hit) -{ - vector2 t_min = (vector2) {-INFINITY, -INFINITY}; - vector2 t_max = (vector2) { INFINITY, INFINITY}; - - // vertical (x_min...x_max) slab of AABB intersecting with line - if (dir.x != 0.0f) { - float invx = 1.0f / dir.x; - float t1 = (bb.min.x - origin.x) * invx; - float t2 = (bb.max.x - origin.x) * invx; - t_min.x = minf(t1, t2); - t_max.x = maxf(t1, t2); - } else { - if ((origin.x < bb.min.x) || (origin.x > bb.max.x)) return false; - } - - // horizontal (y_min...y_max) slab of AABB intersecting with line - if (dir.y != 0.0f) { - float invy = 1.0f / dir.y; - float t1 = (bb.min.y - origin.y) * invy; - float t2 = (bb.max.y - origin.y) * invy; - t_min.y = minf(t1, t2); - t_max.y = maxf(t1, t2); - } else { - // horizontal case (check if line is outside) - if ((origin.y < bb.min.y) || (origin.y > bb.max.y)) return false; - } - - // enter and exit intersection (if ray was an infinite line) - float t_enter = maxf(t_min.x, t_min.y); - float t_exit = minf(t_max.x, t_max.y); - - // limit line to ray (t=0..1) and check interval validity - if (minf(t_exit, 1.0f) < maxf(t_enter, 0.0f)) return false; - - // select first valid hit (if we want to know) - // * entry: origin outside AABB - // * exit: origin inside AABB - if (t_hit) *t_hit = (t_enter >= 0.0f) ? t_enter : t_exit; - - return true; -} - -bool aabb2_check_movement(aabb2 moving_bb, aabb2 static_bb, vector2 dir, float *t_hit){ - // basically equivalent to - // * reduce moving AABB to ray/line segment (with center as origin) - // * and expand static AABB symmetrically by mABB size - // * collision/intersection test - vector2 mbb_half_size = vector2_scale(vector2_sub(moving_bb.max, moving_bb.min), 0.5f); - aabb2 expanded_sbb = (aabb2){ - vector2_sub(static_bb.min, mbb_half_size), - vector2_add(static_bb.max, mbb_half_size) - }; - ray2 reduced_mbb = (ray2){ - vector2_scale(vector2_add(moving_bb.min, moving_bb.max), 0.5f), - dir - }; - bool collision = aabb2_ray_intersect(expanded_sbb, reduced_mbb, t_hit); - if (!collision || !t_hit) return false; - - if (float_zero(*t_hit)){ - - } - - return true; -} \ No newline at end of file diff --git a/shared/math/aabb2.h b/shared/math/aabb2.h deleted file mode 100644 index 1c7cac70..00000000 --- a/shared/math/aabb2.h +++ /dev/null @@ -1,28 +0,0 @@ -#pragma once -#include "types.h" -#include "vector.h" - -// axis aligned bounding box, 2D -typedef struct aabb2 { - vector2 min; - vector2 max; -} aabb2; - -typedef struct ray2 { - vector2 origin; - vector2 dir; -} ray2; - -bool aabb2_line_intersect(aabb2 bb, vector2 origin, vector2 dir, float *t_hit); -static inline bool aabb2_ray_intersect(aabb2 bb, ray2 ray, float *t_hit){ - return aabb2_line_intersect(bb, ray.origin, ray.dir, t_hit); -} - -bool aabb2_check_movement(aabb2 moving_bb, aabb2 static_bb, vector2 dir, float *t_hit); - -static inline bool aabb2_check_collision(aabb2 bb1, aabb2 bb2) { - // collision = NOT (no gap left or no gap right or no gap top or no gap bottom) - // use "NOT(a OR b OR ...) = NOT(a) AND NOT(b) ...": - return (bb1.min.x < bb2.max.x) && (bb2.min.x < bb1.max.x) && - (bb1.min.y < bb2.max.y) && (bb2.min.y < bb1.max.y); -} \ No newline at end of file diff --git a/shared/math/math.h b/shared/math/math.h deleted file mode 100644 index 78a089ae..00000000 --- a/shared/math/math.h +++ /dev/null @@ -1,110 +0,0 @@ -#pragma once - -#include "rng.h" - -#ifdef __cplusplus -extern "C" { -#endif - -#ifndef INFINITY -#define INFINITY __builtin_inff() -#endif - -static inline int min(int a, int b){ - return a < b ? a : b; -} - -static inline float minf(float a, float b){ - return a < b ? a : b; -} - -static inline int max(int a, int b){ - return a > b ? a : b; -} - -static inline float maxf(float a, float b){ - return a > b ? a : b; -} - -static inline int abs(int n){ - return n < 0 ? -n : n; -} - -static inline float absf(float n){ - return n < 0 ? -n : n; -} - -static inline float clampf(float v, float min, float max){ - float t = v < min ? min : v; - return t > max ? max : t; -} - -static inline int sign(int x) { - return x < 0 ? -1 : 1; -} - -static inline int signf(float x) { - return x < 0 ? -1 : 1; -} - -static inline int lerp(int i, int start, int end, int steps) { - return start + (end - start) * i / steps; -} - -static inline bool float_zero(float a){ - const float epsilon = 1e-6f; - return absf(a) < epsilon; -} - -static inline float lerpf(float a, float b, float t) { - // Exact, monotonic, bounded, determinate, and (for a=b=0) consistent: - if((a<=0 && b>=0) || (a>=0 && b<=0)) return t*b + (1-t)*a; - - if(t==1) return b; // exact - // Exact at t=0, monotonic except near t=1, - // bounded, determinate, and consistent: - const float x = a + t*(b-a); - return (t>1) == (b>a) ? max(b,x) : min(b,x); // monotonic near t=1 -} - -static inline double ceil(double val){ - uint64_t whole = (uint64_t)val; - double frac = val - (double)whole; - - return frac > 0 ? whole + 1 : whole; -} - -static inline double floor(double val){ - return (uint64_t)val; -} - -static inline int64_t abs_i64(int64_t v){ - return v < 0 ? -v : v; -} - -static inline int64_t clamp_i64(int64_t v, int64_t lo, int64_t hi){ - if (v < lo) return lo; - if (v > hi) return hi; - return v; -} - -static uint64_t sqrt_u64(uint64_t x){ - uint64_t op = x; - uint64_t res = 0; - uint64_t one = 1ULL << 62; - while (one > op) one >>= 2; - while (one != 0) { - if (op >= res + one) { - op -= res + one; - res = (res >> 1) + one; - } else { - res >>= 1; - } - one >>= 2; - } - return res; -} - -#ifdef __cplusplus -} -#endif \ No newline at end of file diff --git a/shared/math/rng.c b/shared/math/rng.c deleted file mode 100644 index 65ddb510..00000000 --- a/shared/math/rng.c +++ /dev/null @@ -1,95 +0,0 @@ -#include "rng.h" -#include "std/memory.h" - -void rng_seed(rng_t* rng, uint64_t seed){ - uint64_t z = seed + 0x9E3779B97F4A7C15; - z = (z ^ (z >> 30)) * 0xBF58476D1CE4E5B9; - z = (z ^ (z >> 27)) *0x94D049BB133111EB; - rng->s0 = z ^ (z >> 31); - - z = seed + 0x9E3779B97F4A7C15 + 1; - z = (z ^ (z >> 30)) *0xBF58476D1CE4E5B9; - z = (z ^ (z >> 27))*0x94D049BB133111EB; - rng->s1 = z ^ (z >> 31); -} - -uint64_t rng_next64(rng_t* rng){ - uint64_t s0 = rng->s0; - uint64_t s1 = rng->s1; - uint64_t result = s0 + s1; - - s1 ^= s0; - rng->s0 = rotl(s0, 55)^s1^(s1 << 14); - rng->s1 = rotl(s1, 36); - - return result; -} - -uint32_t rng_next32(rng_t* rng){ - return (uint32_t)(rng_next64(rng) >> 32); -} - -uint16_t rng_next16(rng_t* rng){ - return (uint16_t)(rng_next64(rng) >> 48); -} - -float rng_next01f(rng_t* rng){ - return (float)rng_next16(rng)/UINT16_MAX; -} - -uint8_t rng_next8(rng_t* rng){ - return (uint8_t)(rng_next64(rng) >> 56); -} - -uint64_t rng_between64(rng_t* rng, uint64_t min, uint64_t max){ - if (max <= min) return min; - return rng_next64(rng) % (max - min) + min; -} - -uint32_t rng_between32(rng_t* rng, uint32_t min, uint32_t max){ - if (max <= min) return min; - return rng_next64(rng) % (max - min) + min; -} - -uint16_t rng_between16(rng_t* rng, uint16_t min, uint16_t max){ - if (max <= min) return min; - return (uint16_t)(rng_next64(rng) % (max - min)) + min; -} - -uint8_t rng_between8(rng_t* rng, uint8_t min, uint8_t max){ - if (max <= min) return min; - return (uint8_t)(rng_next64(rng) % (max - min)) + min; -} - -void rng_fill64(rng_t* rng, uint64_t* dst, size_t count){ - for (uint32_t i = 0; i < count; i++) - dst[i] = rng_next64(rng); -} - -void rng_fill32(rng_t* rng, uint32_t* dst, size_t count){ - for (uint32_t i = 0; i < count; i++) - dst[i] = rng_next32(rng); -} - -void rng_fill16(rng_t* rng, uint16_t* dst, size_t count){ - for (uint32_t i = 0; i < count; i++) - dst[i] = rng_next16(rng); -} - -void rng_fill8(rng_t* rng, uint8_t* dst, size_t count){ - for (uint32_t i = 0; i < count; i++) - dst[i] = rng_next8(rng); -} - -void rng_fill_buf(rng_t* rng, void* dest, size_t count) { - uint64_t *d64 = (uint64_t *)dest; - - uint64_t blocks = count / 32; - rng_fill64(rng, dest, blocks); - - uint64_t remaining = (count % 32) / 8; - for (uint64_t i = 0; i < remaining; i++) d64[i] = rng_next64(rng);; - - uint8_t *d8 = (uint8_t *)(d64 + remaining); - for (uint64_t i = 0; i < count % 8; i++) d8[i] = rng_next8(rng); -} diff --git a/shared/math/rng.h b/shared/math/rng.h deleted file mode 100644 index c3af0f3a..00000000 --- a/shared/math/rng.h +++ /dev/null @@ -1,42 +0,0 @@ -#pragma once - -#include "types.h" - -#ifdef __cplusplus -extern "C" { -#endif - -//xoroshiro128+, pseudorandom -typedef struct { - uint64_t s0; - uint64_t s1; -} rng_t; - -static inline uint64_t rotl(uint64_t x, int k){ - return (x << k)|(x >> (64 - k)); -} - -void rng_seed(rng_t* rng, uint64_t seed); - -float rng_next01f(rng_t* rng); - -uint8_t rng_next8(rng_t* rng); -uint16_t rng_next16(rng_t* rng); -uint32_t rng_next32(rng_t* rng); -uint64_t rng_next64(rng_t* rng); - -uint8_t rng_between8(rng_t* rng, uint8_t min, uint8_t max); -uint16_t rng_between16(rng_t* rng, uint16_t min, uint16_t max); -uint32_t rng_between32(rng_t* rng, uint32_t min, uint32_t max); -uint64_t rng_between64(rng_t* rng, uint64_t min, uint64_t max); - -void rng_fill8(rng_t* rng, uint8_t* dst, size_t count); -void rng_fill16(rng_t* rng, uint16_t* dst, size_t count); -void rng_fill32(rng_t* rng, uint32_t* dst, size_t count); -void rng_fill64(rng_t* rng, uint64_t* dst, size_t count); -void rng_fill_buf(rng_t* rng, void* dst, size_t count); - -#ifdef __cplusplus -} -#endif - diff --git a/shared/math/vector.h b/shared/math/vector.h deleted file mode 100644 index 2ac5fc5c..00000000 --- a/shared/math/vector.h +++ /dev/null @@ -1,212 +0,0 @@ -#pragma once -#include "types.h" -#include "math.h" -#if defined(__x86_64__) -#include "ammintrin.h" -#endif - -typedef int8_t int8x8_t __attribute__((vector_size(8))); -typedef int8_t int8x16_t __attribute__((vector_size(16))); -typedef uint8_t uint8x8_t __attribute__((vector_size(8))); -typedef uint8_t uint8x16_t __attribute__((vector_size(16))); -typedef int16_t int16x4_t __attribute__((vector_size(8))); -typedef int16_t int16x8_t __attribute__((vector_size(16))); -typedef uint16_t uint16x4_t __attribute__((vector_size(8))); -typedef uint16_t uint16x8_t __attribute__((vector_size(16))); -typedef int32_t int32x2_t __attribute__((vector_size(8))); -typedef int32_t int32x4_t __attribute__((vector_size(16))); -typedef uint32_t uint32x2_t __attribute__((vector_size(8))); -typedef uint32_t uint32x4_t __attribute__((vector_size(16))); -typedef int64_t int64x1_t __attribute__((vector_size(8))); -typedef int64_t int64x2_t __attribute__((vector_size(16))); -typedef uint64_t uint64x1_t __attribute__((vector_size(8))); -typedef uint64_t uint64x2_t __attribute__((vector_size(16))); -typedef float float32x2_t __attribute__((vector_size(8))); -typedef float float32x4_t __attribute__((vector_size(16))); -typedef uint8_t poly8x8_t __attribute__((vector_size(8))); -typedef uint8_t poly8x16_t __attribute__((vector_size(16))); -typedef uint16_t poly16x4_t __attribute__((vector_size(8))); -typedef uint16_t poly16x8_t __attribute__((vector_size(16))); -typedef uint64_t poly64x1_t __attribute__((vector_size(8))); -typedef uint64_t poly64x2_t __attribute__((vector_size(16))); - -typedef struct { int8x8_t val[2]; } int8x8x2_t; -typedef struct { int8x8_t val[3]; } int8x8x3_t; -typedef struct { int8x8_t val[4]; } int8x8x4_t; -typedef struct { int8x16_t val[2]; } int8x16x2_t; -typedef struct { int8x16_t val[3]; } int8x16x3_t; -typedef struct { int8x16_t val[4]; } int8x16x4_t; -typedef struct { uint8x8_t val[2]; } uint8x8x2_t; -typedef struct { uint8x8_t val[3]; } uint8x8x3_t; -typedef struct { uint8x8_t val[4]; } uint8x8x4_t; -typedef struct { uint8x16_t val[2]; } uint8x16x2_t; -typedef struct { uint8x16_t val[3]; } uint8x16x3_t; -typedef struct { uint8x16_t val[4]; } uint8x16x4_t; -typedef struct { int16x4_t val[2]; } int16x4x2_t; -typedef struct { int16x4_t val[3]; } int16x4x3_t; -typedef struct { int16x4_t val[4]; } int16x4x4_t; -typedef struct { int16x8_t val[2]; } int16x8x2_t; -typedef struct { int16x8_t val[3]; } int16x8x3_t; -typedef struct { int16x8_t val[4]; } int16x8x4_t; -typedef struct { uint16x4_t val[2]; } uint16x4x2_t; -typedef struct { uint16x4_t val[3]; } uint16x4x3_t; -typedef struct { uint16x4_t val[4]; } uint16x4x4_t; -typedef struct { uint16x8_t val[2]; } uint16x8x2_t; -typedef struct { uint16x8_t val[3]; } uint16x8x3_t; -typedef struct { uint16x8_t val[4]; } uint16x8x4_t; -typedef struct { int32x2_t val[2]; } int32x2x2_t; -typedef struct { int32x2_t val[3]; } int32x2x3_t; -typedef struct { int32x2_t val[4]; } int32x2x4_t; -typedef struct { int32x4_t val[2]; } int32x4x2_t; -typedef struct { int32x4_t val[3]; } int32x4x3_t; -typedef struct { int32x4_t val[4]; } int32x4x4_t; -typedef struct { uint32x2_t val[2]; } uint32x2x2_t; -typedef struct { uint32x2_t val[3]; } uint32x2x3_t; -typedef struct { uint32x2_t val[4]; } uint32x2x4_t; -typedef struct { uint32x4_t val[2]; } uint32x4x2_t; -typedef struct { uint32x4_t val[3]; } uint32x4x3_t; -typedef struct { uint32x4_t val[4]; } uint32x4x4_t; -typedef struct { int64x1_t val[2]; } int64x1x2_t; -typedef struct { int64x1_t val[3]; } int64x1x3_t; -typedef struct { int64x1_t val[4]; } int64x1x4_t; -typedef struct { int64x2_t val[2]; } int64x2x2_t; -typedef struct { int64x2_t val[3]; } int64x2x3_t; -typedef struct { int64x2_t val[4]; } int64x2x4_t; -typedef struct { uint64x1_t val[2]; } uint64x1x2_t; -typedef struct { uint64x1_t val[3]; } uint64x1x3_t; -typedef struct { uint64x1_t val[4]; } uint64x1x4_t; -typedef struct { uint64x2_t val[2]; } uint64x2x2_t; -typedef struct { uint64x2_t val[3]; } uint64x2x3_t; -typedef struct { uint64x2_t val[4]; } uint64x2x4_t; -typedef struct { float32x2_t val[2]; } float32x2x2_t; -typedef struct { float32x2_t val[3]; } float32x2x3_t; -typedef struct { float32x2_t val[4]; } float32x2x4_t; -typedef struct { float32x4_t val[2]; } float32x4x2_t; -typedef struct { float32x4_t val[3]; } float32x4x3_t; -typedef struct { float32x4_t val[4]; } float32x4x4_t; -typedef struct { poly8x8_t val[2]; } poly8x8x2_t; -typedef struct { poly8x8_t val[3]; } poly8x8x3_t; -typedef struct { poly8x8_t val[4]; } poly8x8x4_t; -typedef struct { poly8x16_t val[2]; } poly8x16x2_t; -typedef struct { poly8x16_t val[3]; } poly8x16x3_t; -typedef struct { poly8x16_t val[4]; } poly8x16x4_t; -typedef struct { poly16x4_t val[2]; } poly16x4x2_t; -typedef struct { poly16x4_t val[3]; } poly16x4x3_t; -typedef struct { poly16x4_t val[4]; } poly16x4x4_t; -typedef struct { poly16x8_t val[2]; } poly16x8x2_t; -typedef struct { poly16x8_t val[3]; } poly16x8x3_t; -typedef struct { poly16x8_t val[4]; } poly16x8x4_t; -typedef struct { poly64x1_t val[2]; } poly64x1x2_t; -typedef struct { poly64x1_t val[3]; } poly64x1x3_t; -typedef struct { poly64x1_t val[4]; } poly64x1x4_t; -typedef struct { poly64x2_t val[2]; } poly64x2x2_t; -typedef struct { poly64x2_t val[3]; } poly64x2x3_t; -typedef struct { poly64x2_t val[4]; } poly64x2x4_t; - -static __inline__ __attribute__((always_inline)) float32x2_t vld1_f32_b(const float* p) { return *(const float32x2_t*)p; } -static __inline__ __attribute__((always_inline)) void vst1_f32_b(float* p, float32x2_t v) { *(float32x2_t*)p = v; } -static __inline__ __attribute__((always_inline)) float32x2_t vmul_f32_b(float32x2_t a, float32x2_t b) { return a * b; } - -static __inline__ __attribute__((always_inline)) float32x2_t vpadd_f32_b(float32x2_t a, float32x2_t b){ -#if defined(__APPLE__) - return (float32x2_t)__builtin_neon_vpadd_v((int8x8_t)a, (int8x8_t)b, 9); -#elif defined(__aarch64__) - return __builtin_aarch64_faddpv2sf(a, b); -#elif defined(__ARM_NEON) || defined(__ARM_NEON__) - return (float32x2_t)__builtin_neon_vpaddv2sf(a, b); -#elif defined(__x86_64__) - return (float32x2_t){a[0] + b[0], a[1] + b[1]}; -#else -# error "no vpadd_f32_b builtin" -#endif -} - -static __inline__ __attribute__((always_inline)) float32x2_t vmax_f32_b(float32x2_t a, float32x2_t b){ -#if defined(__APPLE__) - return (float32x2_t)__builtin_neon_vmax_v((int8x8_t)a, (int8x8_t)b, 9); -#elif defined(__aarch64__) - return __builtin_aarch64_fmax_nanv2sf(a, b); -#elif defined(__ARM_NEON) || defined(__ARM_NEON__) - return (float32x2_t)__builtin_neon_vmaxfv2sf(a, b); -#elif defined(__x86_64__) - return a;//TODO: not implemented -#else -# error "no vmax_f32_b builtin" -#endif -} - -static __inline__ __attribute__((always_inline)) float32x2_t vdup_n_f32_b(float x){ -#if defined(__APPLE__) - return (float32x2_t){ x, x }; -#elif defined(__aarch64__) - return (float32x2_t){ x, x }; -#elif defined(__ARM_NEON) || defined(__ARM_NEON__) - return (float32x2_t)__builtin_neon_vdup_nv2sf(x); -#elif defined(__x86_64__) - return (float32x2_t){ x, x }; -#else -# error "no vdup_n_f32_b builtin" -#endif -} - -static __inline__ __attribute__((always_inline)) float32x2_t vrsqrte_f32_b(float32x2_t s){ -#if defined(__APPLE__) - return (float32x2_t)__builtin_neon_vrsqrte_v((int8x8_t)s, 9); -#elif defined(__aarch64__) - return __builtin_aarch64_rsqrtev2sf(s); -#elif defined(__ARM_NEON) || defined(__ARM_NEON__) - return (float32x2_t)__builtin_neon_vrsqrtev2sf(s); -#elif defined(__x86_64__) - float32x4_t r =_mm_rsqrt_ps((float32x4_t){s[0],s[1],0,0}); - return (float32x2_t){r[0],r[1]}; -#else -# error "no vrsqrte_f32_b builtin" -#endif -} - -typedef struct vector2 { - float x,y; -} vector2; - -static __inline__ __attribute__((always_inline)) float vmagnitude_vector2(float32x2_t v) -{ - float32x2_t sq = vmul_f32_b(v, v); - float32x2_t s = vpadd_f32_b(sq, sq); - s = vmax_f32_b(s, vdup_n_f32_b(1e-20f)); - float32x2_t rinv = vrsqrte_f32_b(s); - return 1.f/rinv[0]; -} - -static inline float vector2_magnitude(vector2 v) -{ - float32x2_t xy = vld1_f32_b(&v.x); // [x, y] - return vmagnitude_vector2(xy); -} -static inline vector2 vector2_sub(vector2 a, vector2 b){ - return (vector2){a.x-b.x,a.y-b.y}; -} - -static inline vector2 vector2_add(vector2 a, vector2 b){ - return (vector2){a.x+b.x,a.y+b.y}; -} - -static inline vector2 vector2_norm(vector2 in){ - float len = vector2_magnitude(in); - return (vector2){in.x/len,in.y/len}; -} - -static inline vector2 vector2_scale(vector2 in, float s){ - return (vector2){ in.x * s, in.y * s}; -} - -static inline bool vector2_zero(vector2 a){ - return float_zero(a.x) && float_zero(a.y); -} - -static inline float dot_product(vector2 a, vector2 b) { - return (a.x*b.x) + (a.y*b.y); -} - -static inline vector2 vector2_lerp(vector2 a, vector2 b, float f){ - return (vector2){ lerpf(a.x, b.x, f), lerpf(a.y, b.y, f)}; -} \ No newline at end of file diff --git a/shared/mouse_input.h b/shared/mouse_input.h deleted file mode 100644 index df6fc1cf..00000000 --- a/shared/mouse_input.h +++ /dev/null @@ -1,28 +0,0 @@ -#pragma once - -#include "types.h" -#include "ui/graphic_types.h" - -#ifdef __cplusplus -extern "C" { -#endif - -typedef struct { - uint8_t buttons; - int8_t x; - int8_t y; - int8_t scroll; -} mouse_input; - -typedef struct { - mouse_input raw; - gpu_point position; -} mouse_data; - -static inline bool mouse_button_down(mouse_data* m, uint8_t button){ - return (m->raw.buttons >> button) & 1; -} - -#ifdef __cplusplus -} -#endif \ No newline at end of file diff --git a/shared/net/checksums.c b/shared/net/checksums.c deleted file mode 100644 index e9bcdbcc..00000000 --- a/shared/net/checksums.c +++ /dev/null @@ -1,53 +0,0 @@ -#include "checksums.h" - -uint16_t checksum16(const uint16_t *data, size_t len) { - uint32_t sum = 0; - for (size_t i = 0; i < len; i++) sum += data[i]; - while (sum >> 16) sum = (sum & 0xFFFF) + (sum >> 16); - return (uint16_t)~sum; -} - -uint16_t checksum16_pipv4(uint32_t src_ip, - uint32_t dst_ip, - uint8_t protocol, - const uint8_t *payload, - uint16_t length) -{ - uint32_t sum = 0; - - sum += (src_ip >> 16) & 0xFFFF; - sum += src_ip & 0xFFFF; - sum += (dst_ip >> 16) & 0xFFFF; - sum += dst_ip & 0xFFFF; - sum += protocol; - sum += length; - - for (uint16_t i = 0; i + 1 < length; i += 2) - sum += (payload[i] << 8) | payload[i + 1]; - - if (length & 1) - sum += payload[length - 1] << 8; - - while (sum >> 16) - sum = (sum & 0xFFFF) + (sum >> 16); - - return (uint16_t)~sum; -} - -uint16_t checksum16_pipv6(const uint8_t src_ip[16], - const uint8_t dst_ip[16], - uint8_t protocol, - const uint8_t *payload, - uint32_t length) -{ - uint32_t sum = 0; - for (int i=0;i<16;i+=2) sum += (uint32_t)((src_ip[i] << 8) | src_ip[i+1]); - for (int i=0;i<16;i+=2) sum += (uint32_t)((dst_ip[i] << 8) | dst_ip[i+1]); - sum += (length >> 16) & 0xFFFF; - sum += length & 0xFFFF; - sum += protocol; - for (uint32_t i = 0; i + 1 < length; i += 2) sum += (uint32_t)((payload[i] << 8) | payload[i + 1]); - if (length & 1) sum += (uint32_t)(payload[length - 1] << 8); - while (sum >> 16) sum = (sum & 0xFFFF) + (sum >> 16); - return (uint16_t)~sum; -} \ No newline at end of file diff --git a/shared/net/checksums.h b/shared/net/checksums.h deleted file mode 100644 index 47f3a834..00000000 --- a/shared/net/checksums.h +++ /dev/null @@ -1,23 +0,0 @@ -#pragma once -#include "types.h" - -#ifdef __cplusplus -extern "C" { -#endif -uint16_t checksum16(const uint16_t *data, size_t len); - -uint16_t checksum16_pipv4(uint32_t src_ip, - uint32_t dst_ip, - uint8_t protocol, - const uint8_t *payload, - uint16_t length); - -uint16_t checksum16_pipv6(const uint8_t src_ip[16], - const uint8_t dst_ip[16], - uint8_t protocol, - const uint8_t *payload, - uint32_t length); - -#ifdef __cplusplus -} -#endif diff --git a/shared/net/network_types.h b/shared/net/network_types.h deleted file mode 100644 index 52b8eaf0..00000000 --- a/shared/net/network_types.h +++ /dev/null @@ -1,49 +0,0 @@ -#pragma once - -#ifdef __cplusplus -extern "C" { -#endif - -#include "types.h" - -typedef enum { - IP_VER4 = 4, - IP_VER6 = 6 -} ip_version_t; - -typedef struct net_l4_endpoint { - ip_version_t ver; - uint8_t ip[16]; - uint16_t port; -} net_l4_endpoint; - -typedef enum { - PROTO_UDP = 0, - PROTO_TCP = 1 -} protocol_t; - -typedef enum Socket_Role { - SOCKET_CLIENT, - SOCKET_SERVER, -} Socket_Role; - -typedef struct SocketHandle { - uint16_t id; - net_l4_endpoint connection; - protocol_t protocol; -} SocketHandle; - -typedef enum { - IP_TX_AUTO = 0, - IP_TX_BOUND_L2 = 1, - IP_TX_BOUND_L3 = 2 -} ip_tx_scope_t; - -typedef struct { - uint8_t index; - ip_tx_scope_t scope; -} ip_tx_opts_t; - -#ifdef __cplusplus -} -#endif \ No newline at end of file diff --git a/shared/net/socket_types.h b/shared/net/socket_types.h deleted file mode 100644 index 06a249ff..00000000 --- a/shared/net/socket_types.h +++ /dev/null @@ -1,56 +0,0 @@ -#pragma once -#include "types.h" -#include "net/network_types.h" - -#ifdef __cplusplus -extern "C" { -#endif - -typedef enum { - BIND_L3 = 0, - BIND_L2 = 1, - BIND_IP = 2, - BIND_ANY = 3 -} SockBindKind; - -typedef enum { - DST_ENDPOINT = 0, - DST_DOMAIN = 1 -} SockDstKind; - -typedef enum { - SOCK_OPT_DEBUG = 1u << 0, - SOCK_OPT_KEEPALIVE = 1u << 1, - SOCK_OPT_BUF_SIZE = 1u << 2, - SOCK_OPT_DONTFRAG = 1u << 3, - SOCK_OPT_TTL = 1u << 4, - SOCK_OPT_MCAST_JOIN = 1u << 5 -} SockOptFlags; - -typedef enum { - SOCK_DBG_LOW = 0, - SOCK_DBG_MEDIUM = 1, - SOCK_DBG_ALL = 2 -} SockDebugLevel; - -typedef struct SocketExtraOptions { - uint32_t flags; - SockDebugLevel debug_level; - uint32_t buf_size; - uint32_t keepalive_ms; - uint8_t ttl; - ip_version_t mcast_ver; - uint8_t mcast_group[16]; -} SocketExtraOptions; - -typedef struct SockBindSpec{ - SockBindKind kind; - ip_version_t ver; - uint8_t l3_id; - uint8_t ifindex; - uint8_t ip[16]; -} SockBindSpec; - -#ifdef __cplusplus -} -#endif diff --git a/shared/std/allocator.cpp b/shared/std/allocator.cpp deleted file mode 100644 index 897eede4..00000000 --- a/shared/std/allocator.cpp +++ /dev/null @@ -1,31 +0,0 @@ -#include "allocator.hpp" -#include "syscalls/syscalls.h" - -void* operator new(size_t size, void* ptr) noexcept { - return ptr; -} - -void* operator new(size_t size) { - return (void*)malloc(size); -} - -void* operator new[](size_t size) { - return (void*)malloc(size); -} - -//TODO: properly implement these -void operator delete(void* ptr) noexcept { - free_sized(ptr, 0); -} - -void operator delete[](void* ptr) noexcept { - free_sized(ptr, 0); -} - -void operator delete(void* ptr, size_t size) noexcept { - free_sized(ptr, size); -} - -void operator delete[](void* ptr, size_t size) noexcept { - free_sized(ptr, size); -} diff --git a/shared/std/allocator.hpp b/shared/std/allocator.hpp deleted file mode 100644 index 6ec46ac1..00000000 --- a/shared/std/allocator.hpp +++ /dev/null @@ -1,12 +0,0 @@ -#pragma once -#include "types.h" - -void* operator new(size_t size); -void* operator new(size_t size, void* ptr) noexcept; -void* operator new[](size_t size); - -void operator delete(void* ptr) noexcept; -void operator delete[](void* ptr) noexcept; - -void operator delete(void* ptr, size_t size) noexcept; -void operator delete[](void* ptr, size_t size) noexcept; diff --git a/shared/std/args.h b/shared/std/args.h deleted file mode 100644 index 228a79d1..00000000 --- a/shared/std/args.h +++ /dev/null @@ -1,15 +0,0 @@ -#pragma once - -#ifndef CROSS - -typedef __builtin_va_list va_list; -#define va_start(ap, last) __builtin_va_start(ap, last) -#define va_arg(ap, type) __builtin_va_arg(ap, type) -#define va_end(ap) __builtin_va_end(ap) -#define va_copy(dest, src) __builtin_va_copy(dest, src) - -#else - -#include - -#endif diff --git a/shared/std/memory.c b/shared/std/memory.c deleted file mode 100644 index 7eef7dae..00000000 --- a/shared/std/memory.c +++ /dev/null @@ -1,282 +0,0 @@ -#include "memory.h" - -int memcmp(const void *s1, const void *s2, size_t count) { - const unsigned char *a = s1; - const unsigned char *b = s2; - for (size_t i = 0; i < count; i++) { - if (a[i] != b[i]) return a[i] - b[i]; - } - return 0; -} - -void* memset32(void* dest, uint32_t val, size_t count) { - uint8_t *d8 = (uint8_t *)dest; - uint64_t pattern = ((uint64_t)val << 32) | val; - - while (((uintptr_t)d8 & 7) % 8 != 0 && count > 0) { - *d8++ = (uint8_t)(val & 0xFF); - count--; - val = (val << 24) | (val >> 8); - } - - size_t blocks = count / 128; - uint64_t *d64 = (uint64_t *)d8; - for (size_t i = 0; i < blocks; i++) { - *(d64++) = pattern; - *(d64++) = pattern; - *(d64++) = pattern; - *(d64++) = pattern; - *(d64++) = pattern; - *(d64++) = pattern; - *(d64++) = pattern; - *(d64++) = pattern; - *(d64++) = pattern; - *(d64++) = pattern; - *(d64++) = pattern; - *(d64++) = pattern; - *(d64++) = pattern; - *(d64++) = pattern; - *(d64++) = pattern; - *(d64++) = pattern; - } - - count %= 128; - if (count >= 8) { - for (size_t i = 0; i < count / 8; i++) { - *d64++ = pattern; - } - count %= 8; - } - d8 = (uint8_t *)d64; - if (count >= 4) { - *((uint32_t *)d8) = val; - d8 += 4; - count -= 4; - } - if (count >= 2) { - *((uint16_t *)d8) = ((val & 0xFF) << 8) | (val & 0xFF); - d8 += 2; - count -= 2; - } - if (count == 1) - *d8 = val & 0xFF; - - return dest; -} - -void* memset(void* dest, int byte, size_t count) { - byte = byte & 0xFF; - uint8_t *d8 = (uint8_t *)dest; - - while (((uintptr_t)d8 & 7) && count > 0) { - *d8++ = byte; - count--; - } - - if (count >= 8) { - uint64_t pattern = 0; - for (int i = 0; i < 8; i++) { - pattern <<= 8; - pattern |= byte; - } - size_t blocks = count / 8; - for (size_t i = 0; i < blocks; i++) { - *((uint64_t *)d8) = pattern; - d8 += 8; - } - count %= 8; - } - - if (count >= 4) { - uint32_t pattern32 = byte; - pattern32 |= pattern32 << 8; - pattern32 |= pattern32 << 16; - *((uint32_t *)d8) = pattern32; - d8 += 4; - count -= 4; - } - - if (count >= 2) { - uint16_t pattern16 = (uint16_t)byte | ((uint16_t)byte << 8); - *((uint16_t *)d8) = pattern16; - d8 += 2; - count -= 2; - } - - if (count == 1) { - *d8 = byte; - } - - return dest; -} - -void* memcpy(void *dest, const void *src, size_t count) { - uint8_t *d8 = (uint8_t *)dest; - const uint8_t *s8 = (const uint8_t *)src; - - while (count > 0 && (((uintptr_t)d8 & 7) != 0 || ((uintptr_t)s8 & 7) != 0)) { - *d8++ = *s8++; - count--; - } - - size_t blocks = count / 128; - uint64_t *d64 = (uint64_t *)d8; - const uint64_t *s64 = (const uint64_t *)s8; - for (size_t i = 0; i < blocks; i++) { - *d64++ = *s64++; - *d64++ = *s64++; - *d64++ = *s64++; - *d64++ = *s64++; - *d64++ = *s64++; - *d64++ = *s64++; - *d64++ = *s64++; - *d64++ = *s64++; - *d64++ = *s64++; - *d64++ = *s64++; - *d64++ = *s64++; - *d64++ = *s64++; - *d64++ = *s64++; - *d64++ = *s64++; - *d64++ = *s64++; - *d64++ = *s64++; - } - - count %= 128; - if (count >= 8) { - for (size_t i = 0; i < count / 8; i++) { - *d64++ = *s64++; - } - count %= 8; - } - d8 = (uint8_t *)d64; - s8 = (uint8_t *)s64; - if (count >= 4) { - *(uint32_t *)d8 = *(uint32_t *)s8; - d8 += 4; - s8 += 4; - count -= 4; - } - if (count >= 2) { - *(uint16_t *)d8 = *(uint16_t *)s8; - d8 += 2; - s8 += 2; - count -= 2; - } - if (count == 1) - *d8 = *s8; - - return dest; -} - -void memreverse(void *ptr, size_t n) { - if (n <= 1) return; - - uint8_t *l = (uint8_t*)ptr; - uint8_t *r = l + n - 1; - - while (((uintptr_t)l & 7) &&l < r) { - uint8_t t = *l; - *l++ = *r; - *r-- = t; - } - - while (((uintptr_t)r & 7) && l < r) { - uint8_t t = *l; - *l++ = *r; - *r-- = t; - } - - while ((size_t)(r - l + 1) >= 16) { - uint64_t *pl = (uint64_t*)l; - uint64_t *pr = (uint64_t*)(r-7); - - uint64_t vl = *pl; - uint64_t vr = *pr; - - *pl = bswap64(vr); - *pr = bswap64(vl); - - l += 8; - r -= 8; - } - - while (l < r) { - uint8_t t = *l; - *l++ = *r; - *r-- = t; - } -} -void* memmove(void *dest, const void *src, size_t count) { - if (dest == src || count == 0) return dest; - - uint8_t *d8 = (uint8_t *)dest; - const uint8_t *s8 = (const uint8_t *)src; - - if (d8 < s8 || d8 >= s8 + count) { - return memcpy(dest, src, count); - } else { - d8 += count; - s8 += count; - - while (count > 0 && (((uintptr_t)d8 & 7) != 0 || ((uintptr_t)s8 & 7) != 0)) { - --d8; --s8; - *d8 = *s8; - --count; - } - - size_t blocks = count / 128; - uint64_t *d64 = (uint64_t *)d8; - const uint64_t *s64 = (const uint64_t *)s8; - for (size_t i = 0; i < blocks * 16; i++) { - --d64; --s64; - *d64 = *s64; - } - - count %= 128; - if (count >= 8) { - size_t q = count / 8; - for (size_t i = 0; i < q; i++) { - --d64; --s64; - *d64 = *s64; - } - count %= 8; - } - - d8 = (uint8_t *)d64; - s8 = (const uint8_t *)s64; - - if (count >= 4) { - d8 -= 4; s8 -= 4; - *(uint32_t *)d8 = *(const uint32_t *)s8; - count -= 4; - } - if (count >= 2) { - d8 -= 2; s8 -= 2; - *(uint16_t *)d8 = *(const uint16_t *)s8; - count -= 2; - } - if (count == 1) { - --d8; --s8; - *d8 = *s8; - } - - return dest; - } -} - -void* memmem(const void* haystack, size_t haystack_len, const void* needle, size_t needle_len) { - if(!haystack || !needle) return 0; - if(!needle_len) return (void*)haystack; - if(haystack_len < needle_len) return 0; - - const unsigned char* h = (const unsigned char*)haystack; - const unsigned char* n = (const unsigned char*)needle; - - size_t last = haystack_len - needle_len; - for(size_t i = 0; i <= last; i++) { - if(h[i] != n[0]) continue; - if(!memcmp(h + i, n, needle_len)) return (void*)(h+i); - } - - return 0; -} diff --git a/shared/std/memory.h b/shared/std/memory.h deleted file mode 100644 index 1fa658a3..00000000 --- a/shared/std/memory.h +++ /dev/null @@ -1,17 +0,0 @@ -#ifdef __cplusplus -extern "C" { -#endif - -#include "types.h" - -int memcmp(const void *s1, const void *s2, size_t count); -void* memset(void* dest, int byte, size_t count); -void* memset32(void* dest, uint32_t val, size_t count); -void* memcpy(void *dest, const void *src, size_t count); -void memreverse(void *ptr, size_t n); -void* memmove(void *dest, const void *src, size_t count); -void* memmem(const void* haystack, size_t haystack_len, const void* needle, size_t needle_len); - -#ifdef __cplusplus -} -#endif diff --git a/shared/std/memory_access.c b/shared/std/memory_access.c deleted file mode 100644 index 24c33846..00000000 --- a/shared/std/memory_access.c +++ /dev/null @@ -1 +0,0 @@ -#include "memory_access.h" diff --git a/shared/std/memory_access.h b/shared/std/memory_access.h deleted file mode 100644 index db61b657..00000000 --- a/shared/std/memory_access.h +++ /dev/null @@ -1,52 +0,0 @@ -#pragma once - -#include "types.h" - -#define read8(addr) (*(volatile uint8_t*)(addr)) -#define write8(addr, value) (*(volatile uint8_t*)(addr) = (value)) - -#define read16(addr) (*(volatile uint16_t*)(addr)) -#define write16(addr, value) (*(volatile uint16_t*)(addr) = (value)) - -#define read32(addr) (*(volatile uint32_t*)(addr)) -#define write32(addr, value) (*(volatile uint32_t*)(addr) = (value)) - -#define read64(addr) (*(volatile uint64_t*)(addr)) -#define write64(addr, value) (*(volatile uint64_t*)(addr) = (value)) - -#ifdef __cplusplus -extern "C" { -#endif - -static inline uint16_t read_unaligned16(const uint16_t *up) { - uint8_t *p = (uint8_t*)up; - return (uint16_t)p[0] | ((uint16_t)p[1] << 8); -} - -static inline uint32_t read_unaligned32(const void *up) { - uint8_t *p = (uint8_t*)up; - return (uint32_t)p[0] | ((uint32_t)p[1] << 8) | ((uint32_t)p[2] << 16) | ((uint32_t)p[3] << 24); -} - -static inline uint64_t read_unaligned64(const uint64_t *up) { - uint8_t *p = (uint8_t*)up; - return (uint64_t)p[0] | ((uint64_t)p[1] << 8) | ((uint64_t)p[2] << 16) | ((uint64_t)p[3] << 24) | ((uint64_t)p[4] << 32) | ((uint64_t)p[5] << 40) | ((uint64_t)p[6] << 48) | ((uint64_t)p[7] << 56); -} - -static inline void write_unaligned32(uint32_t *up, uint32_t value) { - uint8_t *p = (uint8_t*)up; - p[0] = (uint8_t)(value & 0xFF); - p[1] = (uint8_t)((value >> 8) & 0xFF); - p[2] = (uint8_t)((value >> 16) & 0xFF); - p[3] = (uint8_t)((value >> 24) & 0xFF); -} - -static inline void write_unaligned16(uint16_t *up, uint16_t value){ - uint8_t *p = (uint8_t*)up; - p[0] = (uint8_t)(value & 0xFF); - p[1] = (uint8_t)((value >> 8) & 0xFF); -} - -#ifdef __cplusplus -} -#endif \ No newline at end of file diff --git a/shared/std/std.h b/shared/std/std.h deleted file mode 100644 index 9b9a749e..00000000 --- a/shared/std/std.h +++ /dev/null @@ -1,12 +0,0 @@ -#pragma once - -#ifdef __cplusplus -#include "allocator.hpp" -#include "data_struct/data_struct.hpp" -#endif -#include "types.h" -#include "../syscalls/syscalls.h" -#include "args.h" -#include "memory.h" -#include "string.h" -#include "math/math.h" \ No newline at end of file diff --git a/shared/std/string.c b/shared/std/string.c deleted file mode 100644 index d3c9a3f5..00000000 --- a/shared/std/string.c +++ /dev/null @@ -1,1280 +0,0 @@ -#include "std/string.h" -#include "syscalls/syscalls.h" -#include "std/memory.h" -#include "types.h" -#include "string_slice.h" - -#define TRUNC_MARKER "[…]" - -//TODO move these in a dedicated helper file -static inline void append_char(char **p, size_t *rem, char c, int *truncated) { - if (*rem > 1) { - **p = c; - (*p)++; - (*rem)--; - } else { - *truncated = 1; - } -} - -static inline void append_strn(char **p, size_t *rem, const char *s, size_t n, int *truncated) { - for (size_t i = 0; i < n; i++) { - append_char(p, rem, s[i], truncated); - if (*truncated) break; - } -} - -static inline void append_block(char **p, size_t *rem, const char *s, size_t n, int *truncated) { - if (n == 0) return; - if (*rem <= 1) { - *truncated = 1; - return; - } - size_t can = *rem - 1; - size_t w = (n <= can) ? n : can; - memcpy(*p, s, w); - *p += w; - *rem -= w; - if (w < n) *truncated = 1; -} - -static inline void append_repeat(char **p, size_t *rem, char c, size_t n, int *truncated) { - if (n == 0) return; - if (*rem <= 1) { - *truncated = 1; - return; - } - size_t can = *rem - 1; - size_t w = (n <= can) ? n : can; - - if (w <= 16) { - for (size_t i = 0; i < w; ++i) (*p)[i] = c; - *p += w; - } else { - char blk[32]; - for (size_t i = 0; i < sizeof(blk); ++i) blk[i] = c; - size_t t = w; - while (t >= 32) { - memcpy(*p, blk, 32); - *p += 32; - t -= 32; - } - if (t >= 16) { - memcpy(*p, blk, 16); - *p += 16; - t -= 16; - } - if (t) { - memcpy(*p, blk, t); - *p += t; - } - } - - *rem -= w; - if (w < n) *truncated = 1; -} - -static inline uint32_t u64_to_dec(char *tmp, uint64_t v) { - uint32_t parts[3]; - uint32_t np = 0; - while (v >= 1000000000ULL) { - uint64_t q = v / 1000000000ULL; - uint32_t r = (uint32_t)(v - q * 1000000000ULL); - parts[np++] = r; - v = q; - } - uint32_t n = 0; - uint32_t h = (uint32_t)v; - do { - tmp[n++] = (char)('0' + (h % 10)); - h /= 10; - } while (h); - - memreverse(tmp, n); - while (np) { - uint32_t x = parts[--np]; - char buf9[9]; - for (int i = 8; i >= 0; --i) { - buf9[i] = (char)('0' + (x % 10)); - x /= 10; - } - memcpy(tmp + n, buf9, 9); - n += 9; - } - return n; -} - -uint32_t u64_to_base(char *tmp, uint64_t v, unsigned base, int upper) { - const char *hx = upper ? "0123456789ABCDEF" : "0123456789abcdef"; - uint32_t n = 0; - - if (base == 16) { - int started = 0; - for (int i = 60; i >= 0; i -= 4) { - uint8_t nib = (uint8_t)((v >> i) & 0xF); - if (!started) { - if (!nib) continue; - started = 1; - } - tmp[n++] = hx[nib]; - } - if (!n) tmp[n++] = '0'; - return n; - } else if (base == 8) { - int started = 0; - for (int i = 63; i >= 0; i -= 3) { - uint8_t tri = (uint8_t)((v >> i) & 0x7); - if (!started) { - if (!tri) continue; - started = 1; - } - tmp[n++] = (char)('0' + tri); - } - if (!n) tmp[n++] = '0'; - return n; - } else if (base == 2) { - int started = 0; - for (int i = 63; i >= 0; --i) { - uint8_t bit = (uint8_t)((v >> i) & 1u); - if (!started) { - if (!bit) continue; - started = 1; - } - tmp[n++] = (char)('0' + bit); - } - if (!n) tmp[n++] = '0'; - return n; - } - - do { - tmp[n++] = "0123456789abcdef"[v % base]; - v /= base; - } while (v && n < 65); - memreverse(tmp, n); - return n; -} - -static inline void emit_padded(char **restrict p, size_t *restrict rem, - const char *restrict buf, uint32_t len, - int width, int flag_minus, int *restrict truncated) { - if (width < 0) width = 0; - uint32_t pad = (width > (int)len) ? (uint32_t)width - len : 0; - if (pad > (uint32_t)2147483647) pad = (uint32_t)2147483647; - if (!flag_minus) append_repeat(p, rem, ' ', pad, truncated); - append_block(p, rem, buf, len, truncated); - if (flag_minus) append_repeat(p, rem, ' ', pad, truncated); -} - -size_t strlen_max(const char *s, uint32_t max_length){ - if (s == NULL) return 0; - - size_t len = 0; - while ((max_length == 0 || len < max_length) && s[len]) len++; - - return len; -} - -string string_from_literal(const char *literal){ - if (literal == NULL) return (string){ .data = NULL, .length = 0, .mem_length = 0}; - - uint32_t len = strlen(literal); - char *buf = (char*)malloc(len + 1); - if (!buf) return (string){ .data = NULL, .length = 0, .mem_length = 0 }; - - for (uint32_t i = 0; i < len; i++) buf[i] = literal[i]; - - buf[len] = '\0'; - return (string){ .data = buf, .length = len, .mem_length = len + 1 }; -} - -string string_repeat(char symbol, uint32_t amount){ - char *buf = (char*)malloc(amount + 1); - if (!buf) return (string){0}; - memset(buf, symbol, amount); - buf[amount] = 0; - return (string){ .data = buf, .length = amount, .mem_length = amount+1 }; -} - -string string_tail(const char *array, uint32_t max_length){ - - if (array == NULL) return (string){ .data = NULL, .length = 0, .mem_length = 0 }; - - uint32_t len = strlen(array); - int offset = (int)len - (int)max_length; - if (offset < 0) offset = 0; - - uint32_t adjusted_len = len - offset; - char *buf = (char*)malloc(adjusted_len + 1); - if (!buf) return (string){ .data = NULL, .length = 0, .mem_length = 0 }; - - for (uint32_t i = 0; i < adjusted_len; i++) buf[i] = array[offset + i]; - - buf[adjusted_len] = '\0'; - return (string){.data = buf, .length = adjusted_len, .mem_length = adjusted_len + 1 }; -} - -string string_from_literal_length(const char *array, uint32_t max_length){ - if (array == NULL) return (string){.data = NULL, .length = 0, .mem_length= 0 }; - - uint32_t len = strlen_max(array, max_length); - char *buf = (char*)malloc(len + 1); - if(!buf) return (string){ .data = NULL, .length = 0, .mem_length=0 }; - - for (uint32_t i = 0; i < len; i++) buf[i] = array[i]; - - buf[len] = '\0'; - return (string){ .data = buf, .length = len, .mem_length = len+1}; -} - -string string_from_char(const char c){ - char *buf = (char*)malloc(2); - if (!buf) return (string){0}; - buf[0] = c; - buf[1] = 0; - return (string){.data = buf, .length = 1, .mem_length = 2}; -} - -uint32_t parse_hex(uint64_t value, char* buf){ - uint32_t len = 0; - buf[len++] = '0'; - buf[len++] = 'x'; - bool started = false; - for (uint32_t i = 60;; i -= 4) { - uint8_t nibble = (value >> i) & 0xF; - char curr_char = nibble < 10 ? '0' + nibble : 'A' + (nibble - 10); - if (started || curr_char != '0' || i == 0) { - started = true; - buf[len++] = curr_char; - } - - if (i == 0) break; - } - - buf[len] = 0; - return len; -} - -string string_from_hex(uint64_t value){ - char *buf = (char*)malloc(18); - if (!buf) return (string){0}; - uint32_t len = parse_hex(value, buf); - return (string){ .data = buf, .length = len, .mem_length = 18 }; -} - -uint32_t parse_bin(uint64_t value, char* buf){ - uint32_t len = 0; - buf[len++] = '0'; - buf[len++] = 'b'; - bool started = false; - for (uint32_t i = 63;; i --){ - char bit = (value >> i) & 1 ? '1' : '0'; - if (started || bit != '0' || i == 0){ - started = true; - buf[len++] = bit; - } - - if (i == 0) break; - } - - buf[len] = 0; - return len; -} - -string string_from_bin(uint64_t value){ - char *buf = (char*)malloc(66); - if (!buf) return (string){0}; - uint32_t len = parse_bin(value, buf); - return (string){ .data = buf, .length = len, .mem_length = 66 }; -} - -bool string_equals(string a, string b){ - return strcmp(a.data,b.data) == 0; -} - -string string_replace(const char *str, char orig, char repl){ - size_t str_size = strlen(str); - char *buf = (char*)malloc(str_size+1); - for (size_t i = 0; i < str_size && str[i]; i++){ - buf[i] = str[i] == orig ? repl : str[i]; - } - buf[str_size] = 0; - return (string){ .data = buf, .length = str_size, .mem_length = str_size + 1}; -} - -string string_format(const char *fmt, ...){ - if (fmt == NULL) return (string){ .data = NULL, .length = 0, .mem_length = 0}; - - __attribute__((aligned(16))) va_list args; - va_start(args, fmt); - string result = string_format_va(fmt, args); - va_end(args); - return result; -} - -string string_format_va(const char *fmt, va_list args){ - char *buf = (char*)malloc(STRING_MAX_LEN); - if (!buf) return (string){0}; - size_t len = string_format_va_buf(fmt, buf, STRING_MAX_LEN, args); - return (string){ .data = buf, .length = len, .mem_length = STRING_MAX_LEN }; -} - -size_t string_format_buf(char *out, size_t cap, const char *fmt, ...){ - __attribute__((aligned(16))) va_list args; - va_start(args, fmt); - size_t size = string_format_va_buf(fmt, out, cap, args); - va_end(args); - return size; -} - -size_t string_format_va_buf(const char *restrict fmt, char *restrict out, size_t cap, va_list args) { - char *p = out; - size_t rem = cap ? cap : 1; - int truncated_all = 0; - - for (uint32_t i = 0; fmt && fmt[i] && rem > 1;) { - if (fmt[i] != '%') { - uint32_t j = i; - while (fmt[j] && fmt[j] != '%') j++; - append_block(&p, &rem, fmt + i, (uint32_t)(j - i), &truncated_all); - i = j; - continue; - } - - i++; - - unsigned flags = 0; - for (;;) { - char c = fmt[i]; - int done = 0; - switch (c) { - case '-': flags |= 1u << 0; i++; break; - case '+': flags |= 1u << 1; i++; break; - case ' ': flags |= 1u << 2; i++; break; - case '0': flags |= 1u << 3; i++; break; - case '#': flags |= 1u << 4; i++; break; - default: done = 1; break; - } - if (done) break; - } - int flag_minus = (flags & (1u << 0)) != 0; - int flag_plus = (flags & (1u << 1)) != 0; - int flag_space = (flags & (1u << 2)) != 0; - int flag_zero = (flags & (1u << 3)) != 0; - int flag_hash = (flags & (1u << 4)) != 0; - - int width = 0, width_star = 0; - if (fmt[i] == '*') { - width_star = 1; - i++; - } else { - while (fmt[i] >= '0' && fmt[i] <= '9') { - width = width * 10 + (fmt[i] - '0'); - i++; - } - } - - int precision_set = 0, precision = 0; - if (fmt[i] == '.') { - i++; - precision_set = 1; - if (fmt[i] == '*') { - precision = va_arg(args, int); - i++; - } else { - while (fmt[i] >= '0' && fmt[i] <= '9') { - precision = precision * 10 + (fmt[i] - '0'); - i++; - } - } - } - if (precision_set && precision < 0) precision_set = 0; - int had_precision = precision_set; - - enum { LEN_DEF, LEN_HH, LEN_H, LEN_L, LEN_LL, LEN_Z, LEN_T, LEN_J } len = LEN_DEF; - switch (fmt[i]) { - case 'h': if (fmt[i + 1] == 'h') { len = LEN_HH; i += 2; } else { len = LEN_H; i++; } break; - case 'l': if (fmt[i + 1] == 'l') { len = LEN_LL; i += 2; } else { len = LEN_L; i++; } break; - case 'z': len = LEN_Z; i++; break; - case 't': len = LEN_T; i++; break; - case 'j': len = LEN_J; i++; break; - default: break; - } - - if (width_star) { - width = va_arg(args, int); - if (width < 0) { - flag_minus = 1; - width = -width; - } - } - if (!fmt[i]) { - append_char(&p, &rem, '%', &truncated_all); - break; - } - char spec = fmt[i++]; - - if (spec == '%') { - uint32_t pad = (width > 1) ? (uint32_t)(width - 1) : 0; - if (pad > (uint32_t)2147483647) pad = (uint32_t)2147483647; - if (!flag_minus) append_repeat(&p, &rem, ' ', pad, &truncated_all); - append_char(&p, &rem, '%', &truncated_all); - if (flag_minus) append_repeat(&p, &rem, ' ', pad, &truncated_all); - continue; - } - - if (!flag_plus && !flag_space && !flag_zero && !flag_hash && !had_precision && width == 0) { - if (spec == 's') { - const char *s = va_arg(args, char *); if (!s) s = "(null)"; - append_block(&p, &rem, s, strlen(s), &truncated_all); - continue; - } else if (spec == 'c') { - int ch = va_arg(args, int); - append_char(&p, &rem, (char)ch, &truncated_all); - continue; - } - } - - char numtmp[66]; - char sbuf[256]; - const char *obuf = sbuf; - uint32_t outlen = 0; - int is_num = 0; - int negative = 0; - uint32_t k = 0; - - switch (spec) { - case 'c': { - int ch = va_arg(args, int); - char one = (char)ch; - emit_padded(&p, &rem, &one, 1, width, flag_minus, &truncated_all); - } continue; - - case 's': { - const char *s = va_arg(args, char *); - if (!s) s = "(null)"; - uint32_t sl = strlen(s); - if (precision_set && (uint32_t)precision < sl) sl = (uint32_t)precision; - emit_padded(&p, &rem, s, sl, width, flag_minus, &truncated_all); - } continue; - - case 'S': { - const string sv = va_arg(args, string); - const char *s = sv.data ? sv.data : "(null)"; - uint32_t sl = sv.data ? sv.length : 6; - if (precision_set && (uint32_t)precision < sl) sl = (uint32_t)precision; - emit_padded(&p, &rem, s, sl, width, flag_minus, &truncated_all); - } continue; - - case 'v': { - const string_slice sv = va_arg(args, string_slice); - append_strn(&p, &rem, sv.data, sv.length, &truncated_all); - } continue; - - case 'p': { - uintptr_t v = (uintptr_t)va_arg(args, void *); - uint64_t x = (uint64_t)v; - for (int nib = 15; nib >= 0; --nib) sbuf[15 - nib] = "0123456789abcdef"[(x >> (nib * 4)) & 0xF]; - obuf = sbuf; outlen = 16; is_num = 1; - } break; - - case 'b': case 'o': case 'u': case 'x': case 'X': case 'd': case 'i': { - int base = 10; - switch (spec) { - case 'b': base = 2; break; - case 'o': base = 8; break; - case 'x': case 'X': base = 16; break; - default: base = 10; break; - } - int upper = (spec == 'X'); - int is_signed = (spec == 'd' || spec == 'i'); - uint64_t u = 0; - - if (is_signed) { - int64_t sv; - switch (len) { - case LEN_HH: sv = (signed char)va_arg(args, int); break; - case LEN_H: sv = (short)va_arg(args, int); break; - case LEN_L: sv = va_arg(args, long); break; - case LEN_LL: sv = va_arg(args, long long); break; - case LEN_Z: sv = (long long)va_arg(args, size_t); break; - case LEN_T: sv = (long long)va_arg(args, intptr_t); break; - case LEN_J: sv = va_arg(args, int64_t); break; - default: sv = va_arg(args, int); break; - } - if (base == 10) { - char dtmp[32]; - negative = (sv < 0); - uint64_t mag = negative ? (uint64_t)(-(sv + 1)) + 1 : (uint64_t)sv; - uint32_t dn = u64_to_dec(dtmp, mag); - obuf = dtmp; - outlen = dn; - } else { - u = (uint64_t)sv; - uint32_t n = u64_to_base(numtmp, u, (unsigned)base, upper); - obuf = numtmp; - outlen = n; - negative = (sv < 0); - } - } else { - switch (len) { - case LEN_HH: u = (unsigned char)va_arg(args, int); break; - case LEN_H: u = (unsigned short)va_arg(args, int); break; - case LEN_L: u = va_arg(args, unsigned long); break; - case LEN_LL: u = va_arg(args, unsigned long long); break; - case LEN_Z: u = (uint64_t)va_arg(args, size_t); break; - case LEN_T: u = (uint64_t)va_arg(args, uintptr_t); break; - case LEN_J: u = (uint64_t)va_arg(args, uint64_t); break; - default: u = va_arg(args, unsigned int); break; - } - if (base == 10) { - char dtmp[32]; - uint32_t dn = u64_to_dec(dtmp, u); - obuf = dtmp; - outlen = dn; - } else { - uint32_t n = u64_to_base(numtmp, u, (unsigned)base, upper); - obuf = numtmp; - outlen = n; - } - } - - if (precision_set && (uint32_t)precision == 0 && outlen == 1 && obuf[0] == '0') outlen = 0; - is_num = 1; - } break; - - case 'f': case 'F': case 'e': case 'E': case 'g': case 'G': case 'a': case 'A': { - double dv = va_arg(args, double); - int upper = (spec == 'F' || spec == 'E' || spec == 'G' || spec == 'A'); - - uint64_t bits; memcpy(&bits, &dv, sizeof(bits)); - int is_nan = ((bits & 0x7FF0000000000000ULL) == 0x7FF0000000000000ULL) && (bits & 0x000FFFFFFFFFFFFFULL); - int is_inf = ((bits & 0x7FFFFFFFFFFFFFFFULL) == 0x7FF0000000000000ULL); - int is_zero = ((bits << 1) == 0); - int signbit = (int)((bits >> 63) & 1); - negative = signbit; - if (negative) dv = -dv; - - if (is_nan) { - if (upper) { - sbuf[0] = 'N'; - sbuf[1] = 'A'; - sbuf[2] = 'N'; - }else { - sbuf[0] = 'n'; - sbuf[1] = 'a'; - sbuf[2] = 'n'; - } - obuf = sbuf; - outlen = 3; - is_num = 1; - break; - } else if (is_inf) { - if (upper) { - sbuf[0] = 'I'; - sbuf[1] = 'N'; - sbuf[2] = 'F'; - } else { - sbuf[0] = 'i'; - sbuf[1] = 'n'; - sbuf[2] = 'f'; - } - obuf = sbuf; - outlen = 3; - is_num = 1; - break; - } - - if (!precision_set) precision = 6; - if (precision < 0) precision = 0; - - if (spec == 'a' || spec == 'A') { - int neg_local = (int)((bits >> 63) & 1); - uint64_t exp = (bits >> 52) & 0x7FFULL; - uint64_t frac = (bits & 0xFFFFFFFFFFFFFULL); - negative = neg_local; - - if ((exp | frac) == 0) { - k = 0; - sbuf[k++] = '0'; - sbuf[k++] = 'x'; - sbuf[k++] = '0'; - if (precision > 0) { - sbuf[k++] = '.'; - for (int z = 0; z < precision && k < sizeof(sbuf); z++) sbuf[k++] = '0'; - } else if (flag_hash) sbuf[k++] = '.'; - sbuf[k++] = upper ? 'P' : 'p'; - sbuf[k++] = '+'; - sbuf[k++] = '0'; - obuf = sbuf; - outlen = k; - } else { - int e = 0; - uint64_t mant = 0; - if (exp == 0) { - e = -1022; - mant = frac; - while (mant && (mant & (1ULL << 52)) == 0) { - mant <<= 1; - e--; - } - } else { - e = (int)exp - 1023; - mant = (1ULL << 52) | frac; - } - - uint64_t hex_frac = mant & ((1ULL << 52) - 1); - k = 0; - sbuf[k++] = '0'; - sbuf[k++] = 'x'; - sbuf[k++] = '1'; - if (precision > 0) { - sbuf[k++] = '.'; - for (int d = 0; d < precision && k < sizeof(sbuf); d++) { - uint8_t nib = (uint8_t)((hex_frac >> (52 - 4 - 4 * d)) & 0xF); - sbuf[k++] = upper ? "0123456789ABCDEF"[nib] : "0123456789abcdef"[nib]; - } - } else if (flag_hash) sbuf[k++] = '.'; - sbuf[k++] = upper ? 'P' : 'p'; - sbuf[k++] = (e >= 0) ? '+' : '-'; - char etmp[32]; - uint32_t en = u64_to_dec(etmp, (uint64_t)(e >= 0 ? e : -e)); - for (uint32_t t = 0; t < en && k < sizeof(sbuf); t++) sbuf[k++] = etmp[t]; - obuf = sbuf; - outlen = k; - } - is_num = 1; - } else if (spec == 'f' || spec == 'F') { - uint64_t scale = 1; - int prec = precision; - if (prec > 9) prec = 9; - for (int d = 0; d < prec; d++) scale *= 10ull; - uint64_t whole = (uint64_t)dv; - double fr = dv - (double)whole; - uint64_t F = 0; - if (prec > 0) { - double x = fr * (double)scale; - uint64_t xi = (uint64_t)x; - double fp = x - (double)xi; - const double eps = 1e-12; - if (fp > 0.5 + eps || (fp > 0.5 - eps && fp < 0.5 + eps && (xi & 1))) xi++; - F = xi; - } - if (prec > 0 && F >= scale) { - whole += 1; - F -= scale; - } - - char dtmp[32]; - uint32_t dn = u64_to_dec(dtmp, whole); - k = 0; - for (uint32_t t0 = 0; t0 < dn && k < sizeof(sbuf); t0++) sbuf[k++] = dtmp[t0]; - if ((precision > 0 || flag_hash) && k < sizeof(sbuf)) sbuf[k++] = '.'; - if (precision > 0) { - char ftmp[16]; - for (int d = prec - 1; d >= 0; d--) { - ftmp[d] = (char)('0' + (F % 10)); - F /= 10; - } - for (int d = 0; d < prec && k < sizeof(sbuf); d++) sbuf[k++] = ftmp[d]; - } - obuf = sbuf; - outlen = k; - is_num = 1; - } else { - if (is_zero) { - if (spec == 'e' || spec == 'E') { - int prec = precision; - if (prec > 9) prec = 9; - k = 0; sbuf[k++] = '0'; - if ((precision > 0 || flag_hash) && k < sizeof(sbuf)) sbuf[k++] = '.'; - for (int d = 0; d < prec && k < sizeof(sbuf); d++) sbuf[k++] = '0'; - sbuf[k++] = (spec == 'E' ? 'E' : 'e'); - sbuf[k++] = '+'; - sbuf[k++] = '0'; - sbuf[k++] = '0'; - obuf = sbuf; - outlen = k; - is_num = 1; - } else if (spec == 'g' || spec == 'G') { - int p_sig = precision == 0 ? 1 : precision; - if (!flag_hash) { - sbuf[0] = '0'; - k = 1; - } else { - sbuf[0] = '0'; - sbuf[1] = '.'; - k = 2; - for (int d = 1; d < p_sig && k < sizeof(sbuf); d++) sbuf[k++] = '0'; - } - obuf = sbuf; - outlen = k; - is_num = 1; - } - break; - } - - int bexp = (int)((bits >> 52) & 0x7FFULL) - 1023; - int dec_est = (int)((((int64_t)bexp) * 1233) >> 12); - int aexp = dec_est < 0 ? -dec_est : dec_est; - double base = 10.0, pow10 = 1.0, acc = 1.0; - int t = aexp; - while (t) { - if (t & 1) acc *= base; - base *= base; t >>= 1; - } - pow10 = acc; - double m = dv; - if (dec_est > 0) m /= pow10; - else if (dec_est < 0) m *= pow10; - int exp10 = dec_est; - if (m >= 10.0) { - m /= 10.0; - exp10++; - } - else if (m < 1.0) { - m *= 10.0; - exp10--; - } - - if (spec == 'e' || spec == 'E') { - int prec = precision; - if (prec > 9) prec = 9; - uint64_t scale = 1; - for (int d = 0; d < prec; d++) scale *= 10ull; - uint64_t W = (uint64_t)m; - double fr = m - (double)W; - uint64_t F = 0; - if (prec > 0) { - double x = fr * (double)scale; - uint64_t xi = (uint64_t)x; - double fp = x - (double)xi; - const double eps = 1e-12; - if (fp > 0.5 + eps || (fp > 0.5 - eps && fp < 0.5 + eps && (xi & 1))) xi++; - F = xi; - } - if (prec > 0 && F >= scale) { - W += 1; - F -= scale; - if (W >= 10) { - W = 1; - exp10++; - } - } - char dtmp[32]; - uint32_t dn = u64_to_dec(dtmp, W); - k = 0; - for (uint32_t t0 = 0; t0 < dn && k < sizeof(sbuf); t0++) sbuf[k++] = dtmp[t0]; - if ((precision > 0 || flag_hash) && k < sizeof(sbuf)) sbuf[k++] = '.'; - if (precision > 0) { - char ftmp[16]; - for (int d = prec - 1; d >= 0; d--) { - ftmp[d] = (char)('0' + (F % 10)); - F /= 10; - } - for (int d = 0; d < prec && k < sizeof(sbuf); d++) sbuf[k++] = ftmp[d]; - } - sbuf[k++] = (spec == 'E' ? 'E' : 'e'); - sbuf[k++] = (exp10 >= 0) ? '+' : '-'; - uint32_t aexp2 = (uint32_t)(exp10 >= 0 ? exp10 : -exp10); - char etmp[32]; - uint32_t en = u64_to_dec(etmp, aexp2); - if (en < 2) sbuf[k++] = '0'; - for (uint32_t t0 = 0; t0 < en && k < sizeof(sbuf); t0++) sbuf[k++] = etmp[t0]; - obuf = sbuf; - outlen = k; - is_num = 1; - } else if (spec == 'g' || spec == 'G') { - int p_sig = precision == 0 ? 1 : precision; - int use_e = (exp10 < -4 || exp10 >= p_sig); - - if (use_e) { - int prc = p_sig - 1; - if (!precision_set) prc = 6 - 1; - if (prc < 0) prc = 0; - if (prc > 9) prc = 9; - uint64_t scale = 1; - for (int d = 0; d < prc; d++) scale *= 10ull; - uint64_t W = (uint64_t)m; - double fr = m - (double)W; - uint64_t F = 0; - if (prc > 0) { - double x = fr * (double)scale; - uint64_t xi = (uint64_t)x; - double fp = x - (double)xi; - const double eps = 1e-12; - if (fp > 0.5 + eps || (fp > 0.5 - eps && fp < 0.5 + eps && (xi & 1))) xi++; - F = xi; - } - if (prc > 0 && F >= scale) { - W += 1; - F -= scale; - if (W >= 10) { - W = 1; - exp10++; - } - } - char dtmp[32]; - uint32_t dn = u64_to_dec(dtmp, W); - k = 0; - for (uint32_t t0 = 0; t0 < dn && k < sizeof(sbuf); t0++) sbuf[k++] = dtmp[t0]; - if ((prc > 0 || flag_hash) && k < sizeof(sbuf)) sbuf[k++] = '.'; - if (prc > 0) { - char ftmp[16]; - for (int d = prc - 1; d >= 0; d--) { - ftmp[d] = (char)('0' + (F % 10)); - F /= 10; - } - for (int d = 0; d < prc && k < sizeof(sbuf); d++) sbuf[k++] = ftmp[d]; - } - if (!flag_hash && prc > 0) { - while (k > 0 && sbuf[k - 1] == '0') k--; - if (k > 0 && sbuf[k - 1] == '.') k--; - } - sbuf[k++] = (spec == 'G' ? 'E' : 'e'); - sbuf[k++] = (exp10 >= 0) ? '+' : '-'; - uint32_t aexp2 = (uint32_t)(exp10 >= 0 ? exp10 : -exp10); - char etmp[32]; - uint32_t en = u64_to_dec(etmp, aexp2); - if (en < 2) sbuf[k++] = '0'; - for (uint32_t t0 = 0; t0 < en && k < sizeof(sbuf); t0++) sbuf[k++] = etmp[t0]; - obuf = sbuf; - outlen = k; - is_num = 1; - } else { - int pr = p_sig - 1 - exp10; - if (pr < 0) pr = 0; - if (!precision_set) pr = 6; - if (pr > 9) pr = 9; - uint64_t scale = 1; - for (int d = 0; d < pr; d++) scale *= 10ull; - uint64_t whole = (uint64_t)dv; - double fr = dv - (double)whole; - uint64_t F = 0; - if (pr > 0) { - double x = fr * (double)scale; - uint64_t xi = (uint64_t)x; - double fp = x - (double)xi; - const double eps = 1e-12; - if (fp > 0.5 + eps || (fp > 0.5 - eps && fp < 0.5 + eps && (xi & 1))) xi++; - F = xi; - } - if (pr > 0 && F >= scale) { - whole += 1; - F -= scale; - } - char dtmp[32]; - uint32_t dn = u64_to_dec(dtmp, whole); - k = 0; - for (uint32_t t0 = 0; t0 < dn && k < sizeof(sbuf); t0++) sbuf[k++] = dtmp[t0]; - if ((pr > 0 || flag_hash) && k < sizeof(sbuf)) sbuf[k++] = '.'; - if (pr > 0) { - char ftmp[16]; - for (int d = pr - 1; d >= 0; d--) { - ftmp[d] = (char)('0' + (F % 10)); - F /= 10; - } - for (int d = 0; d < pr && k < sizeof(sbuf); d++) sbuf[k++] = ftmp[d]; - } - if (!flag_hash && pr > 0) - { - while (k > 0 && sbuf[k - 1] == '0') k--; - if (k > 0 && sbuf[k - 1] == '.') k--; - } - obuf = sbuf; - outlen = k; - is_num = 1; - } - } - } - } break; - - default: - append_char(&p, &rem, '%', &truncated_all); - append_char(&p, &rem, spec, &truncated_all); - continue; - } - - uint32_t zero_prec = 0, zero_width = 0, left_spaces = 0, right_spaces = 0; - int need_sign = 0; - char signch = 0; - - int allow_sign = (spec == 'd' || spec == 'i' || spec == 'f' || spec == 'F' || spec == 'e' || spec == 'E' || spec == 'g' || spec == 'G' || spec == 'a' || spec == 'A'); - if (is_num && allow_sign) { - if (negative) need_sign = 1, signch = '-'; - else if (flag_plus) need_sign = 1, signch = '+'; - else if (flag_space) need_sign = 1, signch = ' '; - } - - const char *prefix = NULL; - uint32_t plen = 0; - int is_int_spec = (spec == 'd' || spec == 'i' || spec == 'u' || spec == 'o' || spec == 'x' || spec == 'X' || spec == 'b' || spec == 'p'); - - if (is_int_spec && spec != 'p') { - if (had_precision && (uint32_t)precision > outlen) zero_prec = (uint32_t)precision - outlen; - } - if (spec == 'p') { - prefix = "0x"; - plen = 2; - } - else switch (spec) { - case 'b': if (!flag_hash && outlen > 0) { - prefix = "0b"; - plen = 2; - } break; - case 'x': if (!flag_hash && !(outlen == 0 || (outlen == 1 && obuf[0] == '0'))) { - prefix = "0x"; - plen = 2; - } break; - case 'X': if (!flag_hash && !(outlen == 0 || (outlen == 1 && obuf[0] == '0'))) { - prefix = "0X"; - plen = 2; - } break; - case 'o': - if (flag_hash) { - if (outlen == 0) { - prefix = "0"; - plen = 1; - } - else if (zero_prec == 0 && obuf[0] != '0') { - prefix = "0"; - plen = 1; - } - } - break; - default: break; - } - - int pad_zero = 0; - if (!flag_minus) pad_zero = (!is_int_spec ? flag_zero : (flag_zero && !had_precision)); - - uint32_t sign_len = (need_sign ? 1u : 0u); - uint32_t base_len = sign_len + plen + zero_prec + outlen; - - if (pad_zero) { - if (width > (int)base_len) zero_width = (uint32_t)width - base_len; - } else { - if (width > (int)base_len) left_spaces = (uint32_t)width - base_len; - } - if (flag_minus) { - if (width > (int)base_len) right_spaces = (uint32_t)width - base_len; - } - if (left_spaces > (uint32_t)2147483647) left_spaces = (uint32_t)2147483647; - if (right_spaces > (uint32_t)2147483647) right_spaces = (uint32_t)2147483647; - if (zero_width > (uint32_t)2147483647) zero_width = (uint32_t)2147483647; - - append_repeat(&p, &rem, ' ', left_spaces, &truncated_all); - if (need_sign) append_char(&p, &rem, signch, &truncated_all); - if (plen) append_block(&p, &rem, prefix, plen, &truncated_all); - append_repeat(&p, &rem, '0', zero_width, &truncated_all); - append_repeat(&p, &rem, '0', zero_prec, &truncated_all); - append_block(&p, &rem, obuf, outlen, &truncated_all); - append_repeat(&p, &rem, ' ', right_spaces, &truncated_all); - - if (truncated_all) break; - } - - if (truncated_all) { - size_t w = (size_t)(p - out); - const char *m = TRUNC_MARKER; - size_t ml = strlen(m); - if (w >= ml) { - for (size_t i = 0; i < ml; i++) p[-(intptr_t)ml + i] = m[i]; - } else if (w) { - size_t off = ml - w; - for (size_t i = 0; i < w; i++) p[-(intptr_t)w + i] = m[off + i]; - } - } - - if (cap > 0 && out) *p = 0; - return (size_t)(p - out); -} - -int tolower(int c){ - if (c >= 'A' && c <= 'Z') return c + 'a' - 'A'; - return c; -} - -int toupper(int c){ - if (c >= 'a' && c <= 'z') return c - ('a' - 'A'); - return c; -} - -int strcmp_case(const char *a, const char *b, bool case_insensitive){ - if (a == NULL && b == NULL) return 0; - if (a == NULL) return -1; - if (b == NULL) return 1; - - while (*a && *b){ - char ca = *a; - char cb = *b; - if (case_insensitive){ - ca = tolower((unsigned char)ca); - cb = tolower((unsigned char)cb); - } - if (ca != cb) return ca - cb; - a++; b++; - } - if (case_insensitive) return tolower((unsigned char)*a) - tolower((unsigned char)*b); - - return (unsigned char)*a - (unsigned char)*b; -} - -int strncmp_case(const char *a, const char *b, bool case_insensitive, size_t max){ - if (a == NULL && b == NULL) return 0; - if (a == NULL) return -1; - if (b == NULL) return 1; - - for (size_t i = 0; i < max && *a && *b; i++, a++, b++){ - char ca = *a; - char cb = *b; - if (case_insensitive){ - ca = tolower((unsigned char)ca); - cb = tolower((unsigned char)cb); - } - if (ca != cb || i == max - 1) return ca - cb; - } - if (case_insensitive) return tolower((unsigned char)*a) - tolower((unsigned char)*b); - - return (unsigned char)*a - (unsigned char)*b; -} - -int strstart_case(const char *a, const char *b, bool case_insensitive){ - int index = 0; - if (!a || !b) return 0; - while (*a && *b){ - char ca = *a; - char cb = *b; - - if (case_insensitive){ - ca = tolower(ca); - cb = tolower(cb); - } - - if (ca != cb) return index; - a++; b++; index++; - } - return index; -} - -int strindex(const char *a, const char *b){ - for (int i = 0; a[i]; i++){ - int j = 0; - while (b[j] && a[i + j] == b[j]) j++; - if (!b[j]) return i; - } - return -1; -} - -int strend_case(const char *a, const char *b, bool case_insensitive){ - while (*a && *b){ - char ca = case_insensitive ? tolower((unsigned char)*a) : *a; - char cb = case_insensitive ? tolower((unsigned char)*b) : *b; - - if (ca == cb){ - const char *pa = a, *pb = b; - while (1){ - char cpa = case_insensitive ? tolower((unsigned char)*pa) : *pa; - char cpb = case_insensitive ? tolower((unsigned char)*pb) : *pb; - - if (!cpa) return cpb; - if (cpa != cpb) break; - - pa++; pb++; - } - } - a++; - } - return 1; -} - -bool strcont(const char *a, const char *b){ - while (*a){ - const char *p = a, *q = b; - while (*p && *q && *p == *q){ - p++; q++; - } - if (*q == 0) return 1; - a++; - } - return 0; -} - -int count_occurrences(const char* str, char c){ - int count = 0; - while (*str) { - if (*str == c) count++; - str++; - } - return count; -} - -bool utf16tochar(uint16_t* str_in, char* out_str, size_t max_len){ - size_t out_i = 0; - for (size_t i = 0; i < max_len && str_in[i]; i++){ - uint16_t wc = str_in[i]; - out_str[out_i++] = (wc <= 0x7F) ? (char)(wc & 0xFF) : '?'; - } - out_str[out_i++] = '\0'; - return true; -} - -uint64_t parse_hex_u64(const char* str, size_t size){ - uint64_t result = 0; - for (uint32_t i = 0; i < size; i++){ - char c = str[i]; - uint8_t digit = 0; - if (i == 1 && (c == 'x' || c == 'X')) result = 0; - else if (i == 0 && c == '#') result = 0; - else if (c >= '0' && c <= '9') digit = c - '0'; - else if (c >= 'a' && c <= 'f') digit = c - 'a' + 10; - else if (c >= 'A' && c <= 'F') digit = c - 'A' + 10; - else break; - result = (result << 4) | digit; - } - return result; -} - -uint64_t parse_int_u64(const char* str, size_t size){ - uint64_t result = 0; - for (uint32_t i = 0; i < size; i++){ - char c = str[i]; - uint8_t digit = 0; - if (c >= '0' && c <= '9') digit = c - '0'; - else break; - result = (result * 10) + digit; - } - return result; -} - -int64_t parse_int64(const char* str, size_t size){ - uint64_t result = 0; - bool neg = false; - for (uint32_t i = 0; i < size; i++){ - char c = str[i]; - uint8_t digit = 0; - if (i == 0 && c == '-') neg = true; - else if (c >= '0' && c <= '9') digit = c - '0'; - else break; - result = (result * 10) + digit; - } - return neg ? -result : result; -} - -string string_from_const(const char *lit) -{ - uint32_t len = strlen(lit); - char* nlit = malloc(len+1); - strncpy(nlit, lit, len+1); - return (string){ nlit, len, len + 1}; -} - -string string_concat(string a, string b) -{ - uint32_t len = a.length + b.length; - char *dst = (char *)malloc(len + 1); - if (!dst) return (string){0}; - memcpy(dst, a.data, a.length); - memcpy(dst + a.length, b.data, b.length); - dst[len] = 0; - return (string){ dst, len, len +1 }; -} - -void string_concat_inplace(string *dest, string src) -{ - if (!dest || !src.data) return; - - uint32_t new_len = dest->length + src.length; - uint32_t new_cap = new_len + 1; - - char *dst = (char *)malloc(new_cap); - if (!dst) return; - - if (dest->data && dest->length) { - memcpy(dst, dest->data, dest->length); - } - memcpy(dst + dest->length, src.data, src.length); - dst[new_len] = '\0'; - if (dest->data) { - free_sized(dest->data, dest->mem_length); - } - dest->data = dst; - dest->length = new_len; - dest->mem_length = new_cap; -} - -void string_append_bytes(string *dest, const void *buf, uint32_t len) -{ - if (!len) return; - string tmp = { (char *)buf, len, len }; - string_concat_inplace(dest, tmp); -} - -const char* seek_to(const char *string, char character){ - while (*string != character && *string != '\0') - string++; - if (*string == character) string++; - return string; -} - -char* strncpy(char* dst, const char* src, size_t cap){ - size_t i=0; - if (!dst || !src || cap==0) return 0; - while (i UINT32_MAX) return false; - *out = (uint32_t)v; - return true; -} - - -char* strcasestr(const char* haystack, const char* needle) { - if (!haystack) return 0; - if (!needle) return (char*)haystack; - if (!*needle) return (char*)haystack; - - for (const char* h = haystack; *h; h++) { - const char* hp = h; - const char* np = needle; - - while (*hp && *np) { - char a = tolower(*hp); - char b = tolower(*np); - if (a != b) break; - hp++; - np++; - } - - if (!*np) return (char*)h; - } - - return 0; -} - -void strcat_buf(const char *a, const char *b, char *dest){ - while (*a) *dest++ = *a++; - while (*b) *dest++ = *b++; - *dest = 0; -} - -char* strcat_new(const char *a, const char *b){ - char* dest = (char*)malloc(strlen(a) + strlen(b) + 1); - strcat_buf(a,b,dest); - return dest; -} - -string string_replace_character(char* original, char symbol, char *value){ - size_t fulllen = strlen(original); - const char *next = seek_to(original, symbol); - if (next == original+fulllen){ - return string_from_literal(original); - } - string_slice start = make_string_slice(original, 0, next-original-1); - return string_format("%v%s%s",start, value, next); -} \ No newline at end of file diff --git a/shared/std/string.h b/shared/std/string.h deleted file mode 100644 index 03ee2c4d..00000000 --- a/shared/std/string.h +++ /dev/null @@ -1,105 +0,0 @@ -#pragma once - -#include "types.h" -#include "args.h" - -#ifdef __cplusplus -extern "C" { -#endif - -#define STRING_MAX_LEN 256 - -typedef struct { - char *data; - uint32_t length; - uint32_t mem_length; -} string; - -typedef struct string_list { - uint32_t count; - char array[]; -} string_list; -static inline bool is_alpha(char c) { - return ((c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z')); -} - -static inline bool is_digit(char c) { - return (c >= '0' && c <= '9'); -} - -static inline bool is_alnum(char c) { - return is_alpha(c) || is_digit(c); -} - -static inline int32_t str_has_char(const char* s, uint32_t n, char c){ - for (uint32_t i = 0; i < n && s[i] != '\0'; i++) if (s[i] == c) return i; - return -1; -} - -extern void free_sized(void*,size_t); - -static inline int hex_val(char c) { - if (is_digit(c)) return c - '0'; - if (c >= 'a' && c <= 'f') return 10 + (c - 'a'); - if (c >= 'A' && c <= 'F') return 10 + (c - 'A'); - return -1; -} - -uint32_t u64_to_base(char *tmp, uint64_t v, unsigned base, int upper); -size_t strlen_max(const char *s, uint32_t max_length); -static inline size_t strlen(const char *s) { return strlen_max(s,0); } -string string_from_literal(const char *literal); -string string_from_literal_length(const char *array, uint32_t max_length); -string string_from_char(const char c); -string string_from_hex(uint64_t value); -bool string_equals(string a, string b); -string string_replace(const char *str, char orig, char repl); -string string_format(const char *fmt, ...); //TODO __attribute__((format(printf, 1, 2))); -size_t string_format_buf(char *out, size_t cap, const char *fmt, ...); //TODO __attribute__((format(printf, 3, 4))); -string string_format_va(const char *fmt, va_list args); //TODO __attribute__((format(printf, 1, 0))); -size_t string_format_va_buf(const char *fmt, char *out, size_t cap, va_list args); //TODO __attribute__((format(printf, 1, 0))); -string string_tail(const char *array, uint32_t max_length); -string string_repeat(char symbol, uint32_t amount); - -static inline void string_free(string str){ - if (str.data && str.mem_length) free_sized(str.data, str.mem_length); -} - -int tolower(int c); -int toupper(int c); - -int strcmp_case(const char *a, const char *b, bool case_insensitive); -static inline int strcmp(const char *a, const char *b){ return strcmp_case(a, b, false); } -int strncmp_case(const char *a, const char *b, bool case_insensitive, size_t length); -static inline int strncmp(const char *a, const char *b, size_t length) { return strncmp_case(a,b, false, length); } -bool strcont(const char *a, const char *b); -int strstart_case(const char *a, const char *b, bool case_insensitive); -static inline int strstart(const char *a, const char *b) { return strstart_case(a,b,false); } -int strend_case(const char *a, const char *b, bool case_insensitive); -static inline int strend(const char *a, const char *b) { return strend_case(a,b,false); } -int strindex(const char *a, const char *b); -int count_occurrences(const char* str, char c); - -uint64_t parse_hex_u64(const char* str, size_t size); -uint64_t parse_int_u64(const char* str, size_t size); -int64_t parse_int64(const char* str, size_t size); - -bool utf16tochar(uint16_t* str_in, char* out_str, size_t max_len); - -void strcat_buf(const char *a, const char *b, char *dest); -char* strcat_new(const char *a, const char *b); -//@DEPRECATED -string string_from_const(const char *literal); -string string_concat(string a, string b); -void string_concat_inplace(string *dest, string src); -void string_append_bytes(string *dest, const void *buf, uint32_t len); -const char* seek_to(const char *string, char character); -char* strncpy(char* dst, const char* src, size_t cap); -bool parse_uint32_dec(const char *s, uint32_t *out); -char* strcasestr(const char* haystack, const char* needle); - -string string_replace_character(char* original, char symbol, char *value); - -#ifdef __cplusplus -} -#endif \ No newline at end of file diff --git a/shared/std/string_slice.c b/shared/std/string_slice.c deleted file mode 100644 index 9ba19524..00000000 --- a/shared/std/string_slice.c +++ /dev/null @@ -1,8 +0,0 @@ -#include "string_slice.h" -#include "math/math.h" - -string_slice make_string_slice(const char* buf, size_t start, size_t length){ - if (strlen(buf) <= start) return (string_slice){}; - length = min(strlen(buf+start),length); - return (string_slice){.data = (char*)buf + start, .length = length }; -} diff --git a/shared/std/string_slice.h b/shared/std/string_slice.h deleted file mode 100644 index 405358bc..00000000 --- a/shared/std/string_slice.h +++ /dev/null @@ -1,27 +0,0 @@ -#pragma once -#include "string.h" - -typedef struct { - char *data; - size_t length; -} string_slice; - -string_slice make_string_slice(const char* buf, size_t start, size_t length); -static inline string_slice slice_from_lit(const char* buf){ - return make_string_slice(buf, 0, strlen(buf)); -} -static inline string string_from_slice(string_slice slice){ - return string_from_literal_length(slice.data, slice.length); -} - -static inline bool slices_equal(string_slice sl1, string_slice sl2, bool case_insensitive){ - if (sl1.length != sl2.length) return false; - for (size_t i = 0; i < sl1.length; i++) - if (sl1.data[i] != sl2.data[i] && (!case_insensitive || tolower(sl1.data[i]) != tolower(sl2.data[i]))) return false; - return true; -} - -static inline bool slice_lit_match(string_slice sl, const char *lit, bool case_insensitive){ - return slices_equal(sl, make_string_slice(lit,0,strlen(lit)), case_insensitive); -} - diff --git a/shared/syscalls/syscall_codes.h b/shared/syscalls/syscall_codes.h deleted file mode 100644 index a7b3b063..00000000 --- a/shared/syscalls/syscall_codes.h +++ /dev/null @@ -1,41 +0,0 @@ -#pragma once - -#define MALLOC_CODE 0 -#define FREE_CODE 1 - -#define PRINTL_CODE 3 - -#define READ_KEY_CODE 10 -#define REGISTER_SHORTCUT_CODE 11 -#define READ_SHORTCUT_CODE 12 -#define GET_MOUSE_STATUS_CODE 13 -#define READ_EVENT_CODE 14 - -#define REQUEST_DRAW_CTX_CODE 20 -#define GPU_FLUSH_DATA_CODE 21 -#define GPU_CHAR_SIZE_CODE 23 -#define RESIZE_DRAW_CTX_CODE 24 - -#define SLEEP_CODE 30 -#define HALT_CODE 31 -#define EXEC_CODE 32 - -#define GET_TIME_CODE 40 - -#define SOCKET_CREATE_CODE 50 -#define SOCKET_BIND_CODE 51 -#define SOCKET_CONNECT_CODE 52 -#define SOCKET_LISTEN_CODE 53 -#define SOCKET_ACCEPT_CODE 54 -#define SOCKET_SEND_CODE 55 -#define SOCKET_RECEIVE_CODE 56 -#define SOCKET_CLOSE_CODE 57 - -#define FILE_OPEN_CODE 60 -#define FILE_READ_CODE 61 -#define FILE_WRITE_CODE 62 -#define FILE_CLOSE_CODE 63 -#define FILE_SIMPLE_READ_CODE 64 -#define FILE_SIMPLE_WRITE_CODE 65 - -#define DIR_LIST_CODE 70 \ No newline at end of file diff --git a/shared/syscalls/syscalls.c b/shared/syscalls/syscalls.c deleted file mode 100644 index 1c32ee10..00000000 --- a/shared/syscalls/syscalls.c +++ /dev/null @@ -1,109 +0,0 @@ -#include "syscalls.h" -#include "std/string.h" -#include "math/math.h" -#include "std/memory.h" - -static char log_buf[1024]; - -int print(const char *fmt, ...){ - __attribute__((aligned(16))) va_list args; - va_start(args, fmt); - size_t n = string_format_va_buf(fmt, log_buf, sizeof(log_buf), args); - va_end(args); - if (n >= sizeof(log_buf)) log_buf[sizeof(log_buf)-1] = '\0'; - printl(log_buf); -#ifndef CROSS - file fd2 = { .id = 2 }; - writef(&fd2, log_buf, strlen(log_buf)); -#endif - return 0; -} - -int printf(const char *fmt, ...){ - __attribute__((aligned(16))) va_list args; - va_start(args, fmt); - char li[256]; - size_t n = string_format_va_buf(fmt, li, sizeof(li), args); - va_end(args); - if (n >= sizeof(li)) li[sizeof(li)-1] = '\0'; - printl(li); -#ifndef CROSS - file fd2 = { .id = 2 }; - writef(&fd2, li, strlen(li)); -#endif - return 0; -} - -void seek(file *descriptor, int64_t offset, SEEK_TYPE type){ - uint64_t new_cursor = descriptor->cursor; - switch (type) { - case SEEK_ABSOLUTE: - new_cursor = (uint64_t)offset; - break; - case SEEK_RELATIVE: - new_cursor += offset; - break; - } - if (new_cursor > descriptor->size) return;//TODO: check what happens if we intentionally mess with the descriptor size before changing - descriptor->cursor = new_cursor; -} - -void* realloc_sized(void* old_ptr, size_t old_size, size_t new_size){ - void* new_ptr = malloc(new_size); - memcpy(new_ptr, old_ptr, min(old_size,new_size)); - free_sized(old_ptr, old_size); - return new_ptr; -} - -#ifndef CROSS - -void begin_drawing(draw_ctx *ctx){ - -} - -void destroy_draw_ctx(draw_ctx *ctx){ - -} - -bool should_close_ctx(){ - return false; -} - -void* calloc(size_t nitems, size_t size){ - return malloc(nitems * size); -} - -void* zalloc(size_t size){ - return malloc(size); -} - -char *read_full_file(const char *path){ - - file fd = {}; - if (openf(path, &fd) != FS_RESULT_SUCCESS) return false; - char *fcontent = (char*)malloc(fd.size + 1); - - readf(&fd, fcontent, fd.size); - - closef(&fd); - - return fcontent; -} - -bool write_full_file(const char *path, void* buf, size_t size){ - file fd = {}; - if (openf(path, &fd) != FS_RESULT_SUCCESS) return false; - - size_t res = writef(&fd, buf, size); - - closef(&fd); - - return res > 0; -} - -int system(const char *command){ - print("[SYS implementation error] system not implemented"); - return -1; -} - -#endif diff --git a/shared/syscalls/syscalls.h b/shared/syscalls/syscalls.h deleted file mode 100644 index 2d80b42e..00000000 --- a/shared/syscalls/syscalls.h +++ /dev/null @@ -1,80 +0,0 @@ -#pragma once - -#include "types.h" -#include "ui/graphic_types.h" -#include "keyboard_input.h" -#include "mouse_input.h" -#include "std/string.h" -#include "net/network_types.h" -#include "ui/draw/draw.h" -#include "files/fs.h" -#include "net/socket_types.h" - -#ifdef __cplusplus -extern "C" { -#endif - -extern void printl(const char *str); - -extern void* malloc(size_t size); -void* zalloc(size_t size); -extern void free_sized(void *ptr, size_t size); - -extern bool read_key(keypress *kp); -extern bool read_event(kbd_event *event); -extern void get_mouse_status(mouse_data *in); - -extern void msleep(uint64_t time); -extern void halt(int32_t exit_code); -extern uint16_t exec(const char* prog_name, int argc, const char* argv[]); - -extern void request_draw_ctx(draw_ctx*); -extern void begin_drawing(draw_ctx *); -extern void commit_draw_ctx(draw_ctx*); -extern void resize_draw_ctx(draw_ctx*, uint32_t width, uint32_t height); -extern void destroy_draw_ctx(draw_ctx *ctx); - -extern bool should_close_ctx(); - -extern uint32_t gpu_char_size(uint32_t scale); - -extern uint64_t get_time(); - -extern bool socket_create(Socket_Role role, protocol_t protocol, const SocketExtraOptions* extra, SocketHandle *out_handle); -extern int32_t socket_bind(SocketHandle *handle, ip_version_t ip_version, uint16_t port); -extern int32_t socket_connect(SocketHandle *handle, SockDstKind dst_kind, void* dst, uint16_t port); -extern int32_t socket_listen(SocketHandle *handle); -extern bool socket_accept(SocketHandle *spec); -extern size_t socket_send(SocketHandle *handle, SockDstKind dst_kind, const void* dst, uint16_t port, void *packet, size_t size); -extern bool socket_receive(SocketHandle *handle, void *packet, size_t size, net_l4_endpoint* out_src); -extern int32_t socket_close(SocketHandle *handle); - -int printf(const char *fmt, ...); - -extern FS_RESULT openf(const char* path, file* descriptor); -extern size_t readf(file *descriptor, char* buf, size_t size); -extern size_t writef(file *descriptor, const char* buf, size_t size); -extern size_t sreadf(const char* path, void* buf, size_t size); -extern size_t swritef(const char* path, const void* buf, size_t size); -extern void closef(file *descriptor); -void seek(file *descriptor, int64_t offset, SEEK_TYPE type); -void* realloc_sized(void* old_ptr, size_t old_size, size_t new_size); - -void *calloc(size_t nitems, size_t size); - -sizedptr dir_list(const char *path); - -int print(const char *fmt, ...); -char *read_full_file(const char *path); - -bool write_full_file(const char *path, void* buf, size_t size); - -int system(const char *command); - -static inline void yield(){ - msleep(0); -} - -#ifdef __cplusplus -} -#endif diff --git a/shared/syscalls/syscalls_as.S b/shared/syscalls/syscalls_as.S deleted file mode 100644 index f83867f9..00000000 --- a/shared/syscalls/syscalls_as.S +++ /dev/null @@ -1,54 +0,0 @@ -#ifndef CROSS -#include "syscall_codes.h" - -.macro syscall_def name:req, id:req -.global \name -.type \name, %function -\name: - svc #\id - ret -.endm - -#ifndef KERNEL -syscall_def malloc, MALLOC_CODE -syscall_def free_sized, FREE_CODE - -syscall_def printl, PRINTL_CODE - -syscall_def read_key, READ_KEY_CODE -syscall_def read_event, READ_EVENT_CODE -syscall_def register_shortcut, REGISTER_SHORTCUT_CODE -syscall_def read_shortcut, READ_SHORTCUT_CODE -syscall_def get_mouse_status, GET_MOUSE_STATUS_CODE - -syscall_def request_draw_ctx, REQUEST_DRAW_CTX_CODE -syscall_def commit_draw_ctx, GPU_FLUSH_DATA_CODE -syscall_def resize_draw_ctx, RESIZE_DRAW_CTX_CODE - -syscall_def gpu_char_size, GPU_CHAR_SIZE_CODE - -syscall_def exec, EXEC_CODE - -syscall_def get_time, GET_TIME_CODE - -syscall_def socket_create, SOCKET_CREATE_CODE -syscall_def socket_bind, SOCKET_BIND_CODE -syscall_def socket_connect, SOCKET_CONNECT_CODE -syscall_def socket_listen, SOCKET_LISTEN_CODE -syscall_def socket_accept, SOCKET_ACCEPT_CODE -syscall_def socket_send, SOCKET_SEND_CODE -syscall_def socket_receive, SOCKET_RECEIVE_CODE -syscall_def socket_close, SOCKET_CLOSE_CODE - -syscall_def openf, FILE_OPEN_CODE -syscall_def readf, FILE_READ_CODE -syscall_def writef, FILE_WRITE_CODE -syscall_def closef, FILE_CLOSE_CODE -syscall_def dir_list, DIR_LIST_CODE -syscall_def sreadf, FILE_SIMPLE_READ_CODE -syscall_def swritef, FILE_SIMPLE_WRITE_CODE - -#endif -syscall_def msleep, SLEEP_CODE -syscall_def halt, HALT_CODE -#endif diff --git a/shared/types.h b/shared/types.h deleted file mode 100644 index 3c349f49..00000000 --- a/shared/types.h +++ /dev/null @@ -1,95 +0,0 @@ -#pragma once - -#ifndef asm -#define asm __asm__ -#endif - -#ifdef __cplusplus -extern "C" { -#endif - -#define bswap16(v) __builtin_bswap16((uint16_t)(v)) -#define bswap32(v) __builtin_bswap32((uint32_t)(v)) -#define bswap64(v) __builtin_bswap64((uint64_t)(v)) - -#if __BYTE_ORDER__ == __ORDER_LITTLE_ENDIAN__ - #define be16(v) bswap16(v) - #define be32(v) bswap32(v) - #define be64(v) bswap64(v) -#else - #define be16(v) ((uint16_t)(v)) - #define be32(v) ((uint32_t)(v)) - #define be64(v) ((uint64_t)(v)) -#endif - -#define rd_be16(p) ( ((uint16_t)((const uint8_t*)(p))[0] << 8) | \ - ((uint16_t)((const uint8_t*)(p))[1]) ) - -#define rd_be32(p) ( ((uint32_t)((const uint8_t*)(p))[0] << 24) | \ - ((uint32_t)((const uint8_t*)(p))[1] << 16) | \ - ((uint32_t)((const uint8_t*)(p))[2] << 8) | \ - ((uint32_t)((const uint8_t*)(p))[3]) ) - -#define wr_be16(p, v) do { \ - (p)[0] = (uint8_t)((v) >> 8); \ - (p)[1] = (uint8_t)(v); \ -} while(0) - -#define wr_be32(p, v) do { \ - (p)[0] = (uint8_t)((v) >> 24); \ - (p)[1] = (uint8_t)((v) >> 16); \ - (p)[2] = (uint8_t)((v) >> 8); \ - (p)[3] = (uint8_t)(v); \ -} while(0) - -typedef unsigned int uint32_t; -#ifndef CROSS -typedef unsigned long int size_t; -typedef unsigned long long uint64_t; -typedef unsigned long long uintptr_t; - -#define UINT64_MAX 0xFFFFFFFFFFFFFFFFULL -#define UINT16_MAX 0xFFFF -#define UINT32_MAX 0xFFFFFFFF -#define UINT8_MAX 0xFF - -typedef unsigned short uint16_t; -typedef unsigned char uint8_t; - -typedef signed int int32_t; -typedef long long int64_t; -typedef long long intptr_t; -typedef signed short int16_t; -typedef signed char int8_t; - -#define INT16_MAX 0x7FFF - -#define NULL 0 - -#else - -#include -#include - -#endif - -#define FLOAT_MAX 3.40282347e+38F - -#define N_ARR(arr) (sizeof(arr)/sizeof((arr)[0])) - -typedef struct sizedptr { - uintptr_t ptr; - size_t size; -} sizedptr; - -#ifdef __cplusplus -} -#else - -typedef unsigned char bool; -typedef char tern; - -#define true 1 -#define false 0 - -#endif \ No newline at end of file diff --git a/shared/ui/draw/draw.c b/shared/ui/draw/draw.c deleted file mode 100644 index b63ac924..00000000 --- a/shared/ui/draw/draw.c +++ /dev/null @@ -1,405 +0,0 @@ -#include "draw.h" -#include "ui/font8x8_bridge.h" -#include "std/memory.h" - -int try_merge(gpu_rect* a, gpu_rect* b) { - uint32_t ax1 = a->point.x; - uint32_t ay1 = a->point.y; - uint32_t ax2 = ax1 + a->size.width; - uint32_t ay2 = ay1 + a->size.height; - uint32_t bx1 = b->point.x; - uint32_t by1 = b->point.y; - uint32_t bx2 = bx1 + b->size.width; - uint32_t by2 = by1 + b->size.height; - - if (ax1 >= bx2 || bx1 >= ax2 || ay1 >= by2 || by1 >= ay2) - return false; - - uint32_t min_x = a->point.x < b->point.x ? a->point.x : b->point.x; - uint32_t min_y = a->point.y < b->point.y ? a->point.y : b->point.y; - uint32_t max_x = ax2 > bx2 ? ax2 : bx2; - uint32_t max_y = ay2 > by2 ? ay2 : by2; - - a->point.x = min_x; - a->point.y = min_y; - a->size.width = max_x - min_x; - a->size.height = max_y - min_y; - - return true; -} - -void mark_dirty(draw_ctx *ctx, uint32_t x, uint32_t y, uint32_t w, uint32_t h) { - if (ctx->full_redraw) return; - if (x >= ctx->width || y >= ctx->height) return; - - if (x + w > ctx->width) w = ctx->width - x; - if (y + h > ctx->height) h = ctx->height - y; - if (w == 0 || h == 0) return; - - gpu_rect new_rect = (gpu_rect){{x, y}, {w, h}}; - - int merged = 0; - for (uint32_t i = 0; i < ctx->dirty_count; i++) { - if (try_merge(&ctx->dirty_rects[i], &new_rect)) { - merged = 1; - break; - } - } - if (!merged) { - if (ctx->dirty_count < MAX_DIRTY_RECTS) { - ctx->dirty_rects[ctx->dirty_count++] = new_rect; - } else { - ctx->full_redraw = 1; - return; - } - } - - for (uint32_t i = 0; i < ctx->dirty_count; ++i) { - for (uint32_t j = i + 1; j < ctx->dirty_count; ) { - if (try_merge(&ctx->dirty_rects[i], &ctx->dirty_rects[j])) { - for (uint32_t k = j + 1; k < ctx->dirty_count; ++k) - ctx->dirty_rects[k - 1] = ctx->dirty_rects[k]; - ctx->dirty_count--; - } else { - ++j; - } - } - } - - uint64_t area_sum = 0; - for (uint32_t r = 0; r < ctx->dirty_count; ++r) - area_sum += (uint64_t)ctx->dirty_rects[r].size.width * (uint64_t)ctx->dirty_rects[r].size.height; - - const uint64_t screen_area = (uint64_t)ctx->width * (uint64_t)ctx->height; - if (area_sum * 100 >= screen_area * FULL_REDRAW_THRESHOLD_PCT) ctx->full_redraw = 1; -} - -#ifndef CROSS - -void fb_clear(draw_ctx *ctx, uint32_t color) { - uint32_t* row = ctx->fb; - const uint32_t w = ctx->width; - const uint32_t h = ctx->height; - const uint32_t pitch = ctx->stride >> 2; - - for (uint32_t y = 0; y < h; y++) { - uint32_t *p = row; - uint32_t n = w; - - if (((uintptr_t)p & 7) && n) { - *p++ = color; - --n; - } - uint64_t pat = ((uint64_t)color << 32) | color; - uint64_t *q = (uint64_t*)p; - for (uint32_t i = 0; i < (n >> 1); i++) q[i] = pat; - p = (uint32_t*)(q + (n >> 1)); - if (n & 1) *p = color; - - row += pitch; - } - - ctx->full_redraw = 1; -} - - -//TODO: all functions should include this with the (if alpha < 0xFF) check -uint32_t pixel_blend(uint32_t p1, uint32_t p2){ - uint16_t a1 = (p1 >> 24) & 0xFF; - uint16_t a2 = (p2 >> 24) & 0xFF; - if (a2 == 0) return p1; - if (a1 == 0) return p2; - - uint16_t r1 = (p1 >> 16) & 0xFF; - uint16_t r2 = (p2 >> 16) & 0xFF; - - uint16_t g1 = (p1 >> 8) & 0xFF; - uint16_t g2 = (p2 >> 8) & 0xFF; - - uint16_t b1 = p1 & 0xFF; - uint16_t b2 = p2 & 0xFF; - - uint8_t a = a1 + ((255 - a1) * a2)/255; - - uint8_t r = ((r1 * a1) + (r2 * a2 * (255 - a1))/255)/a; - uint8_t g = ((g1 * a1) + (g2 * a2 * (255 - a1))/255)/a; - uint8_t b = ((b1 * a1) + (b2 * a2 * (255 - a1))/255)/a; - - return (a << 24) | (r << 16) | (g << 8) | (b); -} - -void fb_draw_raw_pixel(draw_ctx *ctx, uint32_t x, uint32_t y, color color){ - if (x >= ctx->width || y >= ctx->height) return; - if (((color >> 24) & 0xFF) < 0xFF) - ctx->fb[y * (ctx->stride >> 2) + x] = pixel_blend(color, ctx->fb[y * (ctx->stride >> 2) + x]); - else - ctx->fb[y * (ctx->stride >> 2) + x] = color; -} - -void fb_draw_pixel(draw_ctx *ctx, uint32_t x, uint32_t y, color color){ - fb_draw_raw_pixel(ctx, x, y, color); - mark_dirty(ctx, x,y,1,1); -} - -void fb_fill_rect(draw_ctx *ctx, int32_t x, int32_t y, uint32_t width, uint32_t height, color color){ - if (x >= (int32_t)ctx->width || y >= (int32_t)ctx->height || x + (int32_t)width < 0 || y + (int32_t)height < 0) return; - - int32_t w = width; - int32_t h = height; - if (x < 0){ - width -= -x; - x = 0; - } - if (y < 0){ - height -= -y; - y = 0; - } - if (x + w > (int32_t)ctx->width) w = ctx->width - x; - else if (x < 0){ w += x; x = 0; } - if (y + h > (int32_t)ctx->height) h = ctx->height - y; - else if (y < 0){ h += y; y = 0; } - - if (w <= 0 || h <= 0) return; - - uint8_t alpha = ((color >> 24) & 0xFF); - - if (alpha < 0xFF && alpha > 0){ - for (int32_t dy = 0; dy < h; dy++){ - for (int32_t dx = 0; dx < w; dx++){ - fb_draw_raw_pixel(ctx, x + dx, y + dy, color); - } - } - return; - } - - const uint32_t dst_pitch_px = (ctx->stride >> 2); - uint32_t* dst_row = ctx->fb + y * dst_pitch_px + x; - for (int32_t row = 0; row < h; ++row) { - uint32_t *p = dst_row; - uint32_t n = w; - uint32_t col = (uint32_t)color; - - if (((uintptr_t)p & 7) && n) { *p++ = col; --n; } - uint64_t pat = ((uint64_t)col << 32) | (uint64_t)col; - uint64_t *q = (uint64_t*)p; - for (uint32_t i = 0; i < (n >> 1); ++i) q[i] = pat; - p = (uint32_t*)(q + (n >> 1)); - if (n & 1) *p = col; - - dst_row += dst_pitch_px; - } - mark_dirty(ctx, x,y,w,h); -} - -void fb_draw_img(draw_ctx *ctx, uint32_t x, uint32_t y, uint32_t *img, uint32_t img_width, uint32_t img_height){ - fb_draw_partial_img(ctx, img, x, y, img_width, img_height, (image_transform){}); -} - -void fb_draw_partial_img(draw_ctx *ctx, uint32_t *img, uint32_t x, uint32_t y, uint32_t full_width, uint32_t full_height, image_transform transform){ - if (x >= ctx->width || y >= ctx->height) return; - - if (transform.start_x >= full_width) return; - - uint32_t w = transform.img_width == 0 ? full_width : transform.img_width; - uint32_t h = transform.img_height == 0 ? full_height : transform.img_height; - - if (w > full_width - transform.start_x) w = full_width - transform.start_x; - - if (x + w > ctx->width) w = ctx->width - x; - if (y + h > ctx->height) h = ctx->height - y; - if (!w || !h) return; - - uint32_t y_sind = transform.flip_y ? (full_height-transform.start_y) : transform.start_y; - - const uint32_t dst_pitch_px = (ctx->stride >> 2); - uint32_t* dst_row = ctx->fb + y * dst_pitch_px + x; - - const uint32_t src_pitch_px = full_width; - const uint32_t* src_row = img + (y_sind * full_width); - - for (uint32_t row = 0; row < h; ++row) { - const uint32_t* src = src_row; - uint32_t* dst = dst_row; - for (uint32_t col = 0; col < w; ++col) { - uint32_t x_ind = transform.flip_x ? full_width-transform.start_x-col : transform.start_x + col; - uint32_t pix = src[x_ind]; - if (((pix >> 24) & 0xFF) < 0xFF) - dst[col] = pixel_blend(pix, dst[col]); - else - dst[col] = pix; - } - dst_row += dst_pitch_px; - if (transform.flip_y) src_row -= src_pitch_px; - else src_row += src_pitch_px; - } - - mark_dirty(ctx, x,y,w, h); -} - -gpu_rect fb_draw_line(draw_ctx *ctx, uint32_t x0, uint32_t y0, uint32_t x1, uint32_t y1, color color){ - const uint32_t ox0 = x0, oy0 = y0, ox1 = x1, oy1 = y1; - - int dx = (x1 > x0) ? (x1 - x0) : (x0 - x1); - int sx = (x0 < x1) ? 1 : -1; - int dy = (y1 > y0) ? (y0 - y1) : (y1 - y0); - dy = dy < 0 ? -dy : dy; - int sy = (y0 < y1) ? 1 : -1; - int err = (dx > dy ? dx : -dy) / 2, e2; - - for (;;) { - fb_draw_raw_pixel(ctx, x0, y0, color); - if (x0 == x1 && y0 == y1) break; - e2 = err; - if (e2 > -dx) { err -= dy; x0 += sx; } - if (e2 < dy) { err += dx; y0 += sy; } - } - - uint32_t min_x = (ox0 < ox1) ? ox0 : ox1; - uint32_t min_y = (oy0 < oy1) ? oy0 : oy1; - uint32_t max_x = (ox0 > ox1) ? ox0 : ox1; - uint32_t max_y = (oy0 > oy1) ? oy0 : oy1; - - if (max_x >= ctx->width) max_x = ctx->width - 1; - if (max_y >= ctx->height) max_y = ctx->height - 1; - - const uint32_t bw = (max_x >= min_x) ? (max_x - min_x + 1) : 0; - const uint32_t bh = (max_y >= min_y) ? (max_y - min_y + 1) : 0; - - if (bw && bh) mark_dirty(ctx, min_x, min_y, bw, bh); - - return (gpu_rect) { {min_x, min_y}, {bw, bh} }; -} - -void fb_draw_raw_char(draw_ctx *ctx, uint32_t x, uint32_t y, char c, uint32_t scale, uint32_t color){ - const uint8_t* glyph = get_font8x8((uint8_t)c); - const uint32_t char_size = CHAR_SIZE * scale; - if (x >= ctx->width || y >= ctx->height) return; - - uint32_t max_w = ctx->width - x; - uint32_t max_h = ctx->height - y; - uint32_t draw_w = char_size <= max_w ? char_size : max_w; - uint32_t draw_h = char_size <= max_h ? char_size : max_h; - - const uint32_t row_pitch = ctx->stride >> 2; - - for (uint32_t gy = 0; gy < 8; ++gy) { - uint32_t base_y = gy * scale; - if (base_y >= draw_h) break; - uint32_t ry_lim = scale; - if (base_y + ry_lim > draw_h) ry_lim = draw_h - base_y; - uint8_t bits = glyph[gy]; - for (uint32_t ry = 0; ry < ry_lim; ++ry) { - uint32_t* dst = ctx->fb + (y + base_y + ry) * row_pitch + x; - for (uint32_t gx = 0; gx < 8; ++gx) { - uint32_t base_x = gx * scale; - if (base_x >= draw_w) break; - if (bits & (1u << (7 - gx))) { - uint32_t rx_lim = scale; - if (base_x + rx_lim > draw_w) rx_lim = draw_w - base_x; - uint32_t* p = dst + base_x; - for (uint32_t rx = 0; rx < rx_lim; ++rx) { - if (((color >> 24) & 0xFF) < 0xFF) - p[rx] = pixel_blend(color, p[rx]); - else - p[rx] = color; - } - } - } - } - } -} - -void fb_draw_char(draw_ctx *ctx, uint32_t x, uint32_t y, char c, uint32_t scale, uint32_t color){ - fb_draw_raw_char(ctx, x, y, c, scale, color); - mark_dirty(ctx, x,y,CHAR_SIZE*scale,CHAR_SIZE*scale); -} - -gpu_size fb_draw_string(draw_ctx *ctx, const char* s, uint32_t x0, uint32_t y0, uint32_t scale, uint32_t color){ - const uint32_t char_size = fb_get_char_size(scale); - const int str_length = strlen(s); - - uint32_t xoff = 0; - uint32_t xSize = 0; - uint32_t xRowSize = 0; - uint32_t ySize = 0; - - const uint32_t start_y = y0; - uint32_t rows = 1; - - for (int i = 0; i < str_length; ++i){ - char c = s[i]; - if (c == '\n'){ - if (xRowSize > xSize) - xSize = xRowSize; - xRowSize = 0; - xoff = 0; - y0 += (char_size + 2); - rows++; - } else { - fb_draw_raw_char(ctx, x0 + (xoff * char_size),y0,c,scale, color); - xoff++; - xRowSize += char_size; - } - } - if (xRowSize > xSize) - xSize = xRowSize; - - ySize = rows * (char_size + 2); - - uint32_t bbox_w = xSize; - uint32_t bbox_h = ySize; - - if (x0 + bbox_w > ctx->width) bbox_w = ctx->width - x0; - if (start_y + bbox_h > ctx->height) bbox_h = ctx->height - start_y; - - if (bbox_w && bbox_h) mark_dirty(ctx, x0,start_y,bbox_w,bbox_h); - - return (gpu_size){xSize,ySize}; -} - -uint32_t fb_get_char_size(uint32_t scale){ - return CHAR_SIZE * scale; -} - -void fb_draw_cursor(draw_ctx *ctx, uint32_t color) { - // 22x24 Px - const uint8_t cursor_bitmap[22][24] = - { - {1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0}, - {1,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0}, - {1,1,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0}, - {1,1,1,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0}, - {1,1,1,1,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0}, - {1,1,1,1,1,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0}, - {1,1,1,1,1,1,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0}, - {1,1,1,1,1,1,1,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0}, - {1,1,1,1,1,1,1,1,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0}, - {1,1,1,1,1,1,1,1,1,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0}, - {1,1,1,1,1,1,1,1,1,1,1,0,0,0,0,0,0,0,0,0,0,0,0,0}, - {1,1,1,1,1,1,1,1,1,1,1,1,0,0,0,0,0,0,0,0,0,0,0,0}, - {1,1,1,1,1,1,1,1,1,1,1,1,1,0,0,0,0,0,0,0,0,0,0,0}, - {1,1,1,1,1,1,1,1,1,1,1,1,1,1,0,0,0,0,0,0,0,0,0,0}, - {1,1,1,1,1,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0}, - {1,1,1,1,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0}, - {1,1,1,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0}, - {1,1,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0}, - {1,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0}, - {1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0}, - {0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0}, - {0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0} - }; - - const uint32_t row_pitch = (ctx->stride >> 2); - for (uint32_t y = 0; y < 22; y++){ - uint32_t* dst = ctx->fb + y * row_pitch; - for (uint32_t x = 0; x < 24; x++) - { - if (cursor_bitmap[y][x]) - { - dst[x] = color; - } - } - } -} - -#endif \ No newline at end of file diff --git a/shared/ui/draw/draw.h b/shared/ui/draw/draw.h deleted file mode 100644 index 45159229..00000000 --- a/shared/ui/draw/draw.h +++ /dev/null @@ -1,51 +0,0 @@ -#pragma once - -#ifdef __cplusplus -extern "C" { -#endif - -#include "types.h" -#include "ui/graphic_types.h" -#include "std/string.h" - -#define CHAR_SIZE 8 - -#define MAX_DIRTY_RECTS 64 -#define FULL_REDRAW_THRESHOLD_PCT 35u - -typedef struct draw_ctx { - gpu_rect dirty_rects[MAX_DIRTY_RECTS]; - uint32_t* fb; - uint32_t stride; - uint32_t width; - uint32_t height; - uint32_t dirty_count; - bool full_redraw; -} draw_ctx; - -typedef struct { - uint32_t img_width; - uint32_t img_height; - uint32_t start_x; - uint32_t start_y; - bool flip_x; - bool flip_y; -} image_transform; - -void mark_dirty(draw_ctx *ctx, uint32_t x, uint32_t y, uint32_t w, uint32_t h); - -void fb_clear(draw_ctx *ctx, uint32_t color); -void fb_draw_pixel(draw_ctx *ctx, uint32_t x, uint32_t y, color color); -void fb_fill_rect(draw_ctx *ctx, int32_t x, int32_t y, uint32_t width, uint32_t height, color color); -void fb_fill_partial_rect(draw_ctx *ctx, uint32_t x, uint32_t y, uint32_t width, uint32_t height, color color, uint32_t start_x, uint32_t start_y, uint32_t full_width); -void fb_draw_img(draw_ctx *ctx, uint32_t x, uint32_t y, uint32_t *img, uint32_t img_width, uint32_t img_height); -void fb_draw_partial_img(draw_ctx *ctx, uint32_t *img, uint32_t x, uint32_t y, uint32_t full_width, uint32_t full_height, image_transform transform); -gpu_rect fb_draw_line(draw_ctx *ctx, uint32_t x0, uint32_t y0, uint32_t x1, uint32_t y1, color color); -void fb_draw_char(draw_ctx *ctx, uint32_t x, uint32_t y, char c, uint32_t scale, uint32_t color); -gpu_size fb_draw_string(draw_ctx *ctx, const char* s, uint32_t x, uint32_t y, uint32_t scale, uint32_t color); -uint32_t fb_get_char_size(uint32_t scale); -void fb_draw_cursor(draw_ctx *ctx, uint32_t color); - -#ifdef __cplusplus -} -#endif \ No newline at end of file diff --git a/shared/ui/font8x8_basic.h b/shared/ui/font8x8_basic.h deleted file mode 100644 index 34d3d2c4..00000000 --- a/shared/ui/font8x8_basic.h +++ /dev/null @@ -1,104 +0,0 @@ -#pragma once - -#include "types.h" - -static const uint8_t font8x8_basic[128][8] = { - [' '] = {0,0,0,0,0,0,0,0}, - ['!'] = {0x18,0x18,0x18,0x18,0x00,0x18,0x00,0x00}, - ['"'] = {0x6c,0x6c,0x48,0x00,0x00,0x00,0x00,0x00}, - ['#'] = {0x6c,0x6c,0xfe,0x6c,0xfe,0x6c,0x6c,0x00}, - ['$'] = {0x18,0x3e,0x58,0x3c,0x1a,0x7c,0x18,0x00}, - ['%'] = {0x00,0xc6,0xcc,0x18,0x30,0x66,0xc6,0x00}, - ['&'] = {0x38,0x6c,0x38,0x76,0xdc,0xcc,0x76,0x00}, - ['\''] = {0x30,0x30,0x60,0x00,0x00,0x00,0x00,0x00}, - ['('] = {0x0c,0x18,0x30,0x30,0x30,0x18,0x0c,0x00}, - [')'] = {0x30,0x18,0x0c,0x0c,0x0c,0x18,0x30,0x00}, - ['*'] = {0x00,0x66,0x3c,0xff,0x3c,0x66,0x00,0x00}, - ['+'] = {0x00,0x18,0x18,0x7e,0x18,0x18,0x00,0x00}, - [','] = {0x00,0x00,0x00,0x00,0x30,0x30,0x60,0x00}, - ['-'] = {0x00,0x00,0x00,0x7e,0x00,0x00,0x00,0x00}, - ['.'] = {0x00,0x00,0x00,0x00,0x00,0x30,0x30,0x00}, - ['/'] = {0x06,0x0c,0x18,0x30,0x60,0xc0,0x80,0x00}, - ['0'] = {0x7c,0xc6,0xce,0xd6,0xe6,0xc6,0x7c,0x00}, - ['1'] = {0x18,0x38,0x18,0x18,0x18,0x18,0x7e,0x00}, - ['2'] = {0x7c,0xc6,0x0e,0x1c,0x70,0xc0,0xfe,0x00}, - ['3'] = {0x7c,0xc6,0x06,0x3c,0x06,0xc6,0x7c,0x00}, - ['4'] = {0x1c,0x3c,0x6c,0xcc,0xfe,0x0c,0x1e,0x00}, - ['5'] = {0xfe,0xc0,0xfc,0x06,0x06,0xc6,0x7c,0x00}, - ['6'] = {0x38,0x60,0xc0,0xfc,0xc6,0xc6,0x7c,0x00}, - ['7'] = {0xfe,0xc6,0x0c,0x18,0x30,0x30,0x30,0x00}, - ['8'] = {0x7c,0xc6,0xc6,0x7c,0xc6,0xc6,0x7c,0x00}, - ['9'] = {0x7c,0xc6,0xc6,0x7e,0x06,0x0c,0x78,0x00}, - [':'] = {0x00,0x30,0x30,0x00,0x00,0x30,0x30,0x00}, - [';'] = {0x00,0x30,0x30,0x00,0x00,0x30,0x30,0x60}, - ['<'] = {0x0c,0x18,0x30,0x60,0x30,0x18,0x0c,0x00}, - ['='] = {0x00,0x00,0x7e,0x00,0x7e,0x00,0x00,0x00}, - ['>'] = {0x30,0x18,0x0c,0x06,0x0c,0x18,0x30,0x00}, - ['?'] = {0x7c,0xc6,0x0c,0x18,0x18,0x00,0x18,0x00}, - ['@'] = {0x7c,0xc6,0xde,0xde,0xde,0xc0,0x78,0x00}, - - ['A'] = {0x38,0x6c,0xc6,0xfe,0xc6,0xc6,0xc6,0x00}, - ['B'] = {0xfc,0x66,0x66,0x7c,0x66,0x66,0xfc,0x00}, - ['C'] = {0x3c,0x66,0xc0,0xc0,0xc0,0x66,0x3c,0x00}, - ['D'] = {0xf8,0x6c,0x66,0x66,0x66,0x6c,0xf8,0x00}, - ['E'] = {0xfe,0x62,0x68,0x78,0x68,0x62,0xfe,0x00}, - ['F'] = {0xfe,0x62,0x68,0x78,0x68,0x60,0xf0,0x00}, - ['G'] = {0x3c,0x66,0xc0,0xde,0xc6,0x66,0x3e,0x00}, - ['H'] = {0xc6,0xc6,0xc6,0xfe,0xc6,0xc6,0xc6,0x00}, - ['I'] = {0x7e,0x18,0x18,0x18,0x18,0x18,0x7e,0x00}, - ['J'] = {0x1e,0x0c,0x0c,0x0c,0xcc,0xcc,0x78,0x00}, - ['K'] = {0xe6,0x66,0x6c,0x78,0x6c,0x66,0xe6,0x00}, - ['L'] = {0xf0,0x60,0x60,0x60,0x62,0x66,0xfe,0x00}, - ['M'] = {0xc6,0xee,0xfe,0xfe,0xd6,0xc6,0xc6,0x00}, - ['N'] = {0xc6,0xe6,0xf6,0xde,0xce,0xc6,0xc6,0x00}, - ['O'] = {0x7c,0xc6,0xc6,0xc6,0xc6,0xc6,0x7c,0x00}, - ['P'] = {0x7C, 0x62, 0x62, 0x7C, 0x60, 0x60, 0x60, 0x00}, - ['Q'] = {0x7C, 0x62, 0x62, 0x62, 0x7C, 0x06, 0x06, 0x00}, - ['R'] = {0x7C, 0x62, 0x62, 0x7C, 0x6C, 0x66, 0x62, 0x00}, - ['S'] = {0x3C, 0x62, 0x60, 0x3C, 0x06, 0x62, 0x3C, 0x00}, - ['T'] = {0x7E, 0x5A, 0x18, 0x18, 0x18, 0x18, 0x18, 0x00}, - ['U'] = {0x62, 0x62, 0x62, 0x62, 0x62, 0x62, 0x3C, 0x00}, - ['V'] = {0x62, 0x62, 0x62, 0x62, 0x62, 0x3C, 0x18, 0x00}, - ['W'] = {0x62, 0x62, 0x62, 0x6A, 0x6A, 0x7E, 0x24, 0x00}, - ['X'] = {0x62, 0x62, 0x34, 0x18, 0x34, 0x62, 0x62, 0x00}, - ['Y'] = {0x66, 0x66, 0x66, 0x3C, 0x18, 0x18, 0x18, 0x00}, - ['Z'] = {0x7E, 0x06, 0x0C, 0x18, 0x30, 0x60, 0x7E, 0x00}, - - ['a'] = {0x00, 0x00, 0x3C, 0x06, 0x3E, 0x66, 0x3E, 0x00}, - ['b'] = {0x60, 0x60, 0x7C, 0x66, 0x66, 0x66, 0x7C, 0x00}, - ['c'] = {0x00, 0x00, 0x3C, 0x66, 0x60, 0x66, 0x3C, 0x00}, - ['d'] = {0x06, 0x06, 0x3E, 0x66, 0x66, 0x66, 0x3E, 0x00}, - ['e'] = {0x00, 0x00, 0x3C, 0x66, 0x7E, 0x60, 0x3C, 0x00}, - ['f'] = {0x0E, 0x18, 0x3E, 0x18, 0x18, 0x18, 0x18, 0x00}, - ['g'] = {0x00, 0x00, 0x3E, 0x66, 0x66, 0x3E, 0x06, 0x3C}, - ['h'] = {0x60, 0x60, 0x7C, 0x66, 0x66, 0x66, 0x66, 0x00}, - ['i'] = {0x18, 0x00, 0x38, 0x18, 0x18, 0x18, 0x3C, 0x00}, - ['j'] = {0x0C, 0x00, 0x0C, 0x0C, 0x0C, 0x6C, 0x6C, 0x38}, - ['k'] = {0x60, 0x60, 0x66, 0x6C, 0x78, 0x6C, 0x66, 0x00}, - ['l'] = {0x38, 0x18, 0x18, 0x18, 0x18, 0x18, 0x3C, 0x00}, - ['m'] = {0x00, 0x00, 0x6C, 0x7E, 0x7E, 0x6C, 0x6C, 0x00}, - ['n'] = {0x00, 0x00, 0x7C, 0x66, 0x66, 0x66, 0x66, 0x00}, - ['o'] = {0x00, 0x00, 0x3C, 0x66, 0x66, 0x66, 0x3C, 0x00}, - ['p'] = {0x00, 0x00, 0x7C, 0x66, 0x66, 0x7C, 0x60, 0x60}, - ['q'] = {0x00, 0x00, 0x3E, 0x66, 0x66, 0x3E, 0x06, 0x06}, - ['r'] = {0x00, 0x00, 0x6C, 0x76, 0x60, 0x60, 0x60, 0x00}, - ['s'] = {0x00, 0x00, 0x3E, 0x60, 0x3C, 0x06, 0x7C, 0x00}, - ['t'] = {0x10, 0x30, 0x7C, 0x30, 0x30, 0x30, 0x1C, 0x00}, - ['u'] = {0x00, 0x00, 0x66, 0x66, 0x66, 0x66, 0x3E, 0x00}, - ['v'] = {0x00, 0x00, 0x66, 0x66, 0x66, 0x3C, 0x18, 0x00}, - ['w'] = {0x00, 0x00, 0x6C, 0x6C, 0x7E, 0x7E, 0x24, 0x00}, - ['x'] = {0x00, 0x00, 0x66, 0x3C, 0x18, 0x3C, 0x66, 0x00}, - ['y'] = {0x00, 0x00, 0x66, 0x66, 0x66, 0x3E, 0x06, 0x3C}, - ['z'] = {0x00, 0x00, 0x7E, 0x0C, 0x18, 0x30, 0x7E, 0x00}, - - ['['] = {0x1c,0x18,0x18,0x18,0x18,0x18,0x1c,0x00}, - ['\\'] = {0xc0,0x60,0x30,0x18,0x0c,0x06,0x02,0x00}, - [']'] = {0x38,0x18,0x18,0x18,0x18,0x18,0x38,0x00}, - ['^'] = {0x10,0x38,0x6c,0xc6,0x00,0x00,0x00,0x00}, - ['_'] = {0x00,0x00,0x00,0x00,0x00,0x00,0x00,0xff}, - ['`'] = {0x30,0x18,0x0c,0x00,0x00,0x00,0x00,0x00}, - ['{'] = {0x0e,0x0c,0x0c,0x38,0x0c,0x0c,0x0e,0x00}, - ['|'] = {0x18,0x18,0x18,0x18,0x18,0x18,0x18,0x00}, - ['}'] = {0x70,0x30,0x30,0x1c,0x30,0x30,0x70,0x00}, - ['~'] = {0x76,0xdc,0x00,0x00,0x00,0x00,0x00,0x00}, -}; diff --git a/shared/ui/font8x8_bridge.c b/shared/ui/font8x8_bridge.c deleted file mode 100644 index f36100ff..00000000 --- a/shared/ui/font8x8_bridge.c +++ /dev/null @@ -1,6 +0,0 @@ -#include "font8x8_basic.h" -#include "font8x8_bridge.h" - -const uint8_t* get_font8x8(uint8_t c) { - return font8x8_basic[c]; -} \ No newline at end of file diff --git a/shared/ui/font8x8_bridge.h b/shared/ui/font8x8_bridge.h deleted file mode 100644 index bbc9a286..00000000 --- a/shared/ui/font8x8_bridge.h +++ /dev/null @@ -1,11 +0,0 @@ -#ifdef __cplusplus -extern "C" { -#endif -#include "types.h" - -//TODO: remove this header, use just #ifdef and else -const uint8_t* get_font8x8(uint8_t c); - -#ifdef __cplusplus -} -#endif \ No newline at end of file diff --git a/shared/ui/graphic_types.h b/shared/ui/graphic_types.h deleted file mode 100644 index e574fbe3..00000000 --- a/shared/ui/graphic_types.h +++ /dev/null @@ -1,43 +0,0 @@ -#pragma once - -#include "types.h" - -#ifdef __cplusplus -extern "C" { -#endif - -typedef uint32_t color; - -typedef union argbcolor { - struct { - uint32_t blue: 8; - uint32_t green: 8; - uint32_t red: 8; - uint32_t alpha: 8; - }; - uint32_t color; -} argbcolor; - -typedef struct { - uint32_t x; - uint32_t y; -} gpu_point; - -typedef struct { - int32_t x; - int32_t y; -} int_point; - -typedef struct { - uint32_t width; - uint32_t height; -} gpu_size; - -typedef struct { - gpu_point point; - gpu_size size; -} gpu_rect; - -#ifdef __cplusplus -} -#endif \ No newline at end of file diff --git a/shared/ui/uno/uno.c b/shared/ui/uno/uno.c deleted file mode 100644 index 6ded523d..00000000 --- a/shared/ui/uno/uno.c +++ /dev/null @@ -1,101 +0,0 @@ -#include "uno.h" -#include "ui/draw/draw.h" - -gpu_size calculate_label_size(text_ui_config text_config){ - if (!text_config.text || text_config.font_size==0) return (gpu_size){0,0}; - int num_lines = 1; - int num_chars = 0; - int local_num_chars = 0; - for (const char* p = text_config.text; *p; ++p){ - if (*p == '\n'){ - if (local_num_chars > num_chars) - num_chars = local_num_chars; - num_lines++; - local_num_chars = 0; - } - else - local_num_chars++; - } - if (local_num_chars > num_chars) - num_chars = local_num_chars; - unsigned int size = fb_get_char_size(text_config.font_size); - return (gpu_size){size * num_chars, (size + 2) * num_lines }; -} - -int_point calculate_label_pos(text_ui_config text_config, common_ui_config common_config){ - gpu_size s = calculate_label_size(text_config); - int_point point = common_config.point; - switch (common_config.horizontal_align) - { - case Trailing: - point.x = (s.width>=common_config.size.width) ? common_config.point.x : (int32_t)(common_config.point.x + (common_config.size.width - s.width)); - break; - case HorizontalCenter: - point.x = (s.width>=common_config.size.width) ? common_config.point.x : (int32_t)(common_config.point.x + ((common_config.size.width - s.width)/2)); - break; - default: - break; - } - - switch (common_config.vertical_align) - { - case Bottom: - point.y = (s.height>=common_config.size.height) ? common_config.point.y : (int32_t)(common_config.point.y + (common_config.size.height - s.height)); - break; - case VerticalCenter: - point.y = (s.height>=common_config.size.height) ? common_config.point.y : (int32_t)(common_config.point.y + ((common_config.size.height - s.height)/2)); - break; - default: - break; - } - - return point; -} - -common_ui_config label(draw_ctx *ctx, text_ui_config text_config, common_ui_config common_config){ - if (!text_config.text || text_config.font_size==0) return common_config; - int_point p = calculate_label_pos(text_config, common_config); - fb_draw_string(ctx, text_config.text, p.x, p.y, text_config.font_size, common_config.foreground_color); - return common_config; -} - -common_ui_config textbox(draw_ctx *ctx, text_ui_config text_config, common_ui_config common_config){ - common_ui_config inner = rectangle(ctx, (rect_ui_config){}, common_config); - label(ctx, text_config, inner); - return inner; -} - -common_ui_config rectangle(draw_ctx *ctx, rect_ui_config rect_config, common_ui_config common_config){ - if ((common_config.background_color >> 24 | rect_config.border_color >> 24) == 0) return common_config; - int32_t bx = common_config.point.x; - int32_t by = common_config.point.y; - uint32_t bw = common_config.size.width; - uint32_t bh = common_config.size.height; - uint32_t b = rect_config.border_size; - uint32_t p = rect_config.border_padding; - uint32_t twice_p = p << 1; - - if (bx < 0) bw -= -bx; - if (by < 0) bh -= -by; - - int32_t inner_x = bx + (rect_config.border_padding ? 0 : b); - int32_t inner_y = by + (rect_config.border_padding ? 0 : b); - uint32_t twice_b = rect_config.border_padding ? 0 : b << 1; - uint32_t inner_w = (bw > twice_b) ? (bw - twice_b) : 0; - uint32_t inner_h = (bh > twice_b) ? (bh - twice_b) : 0; - if (inner_w && inner_h) fb_fill_rect(ctx, inner_x, inner_y, inner_w, inner_h, common_config.background_color); - - fb_fill_rect(ctx, bx + p, by + p, b, bh - b - twice_p, rect_config.border_color); - fb_fill_rect(ctx, bx + p + bw - b - twice_p, by + p + b, b, bh - b - twice_p, rect_config.border_color); - fb_fill_rect(ctx, bx + p + b, by + p, bw - b - twice_p, b, rect_config.border_color); - fb_fill_rect(ctx, bx + p, by - p + bh - b , bw - b - twice_p, b, rect_config.border_color); - - return (common_ui_config){ - .point = {inner_x + p + b, inner_y + p + b}, - .size = {inner_w + ((p + b) << 1), inner_h + ((p + b) << 1)}, - .background_color = common_config.background_color, - .foreground_color = common_config.foreground_color, - .horizontal_align = common_config.horizontal_align, - .vertical_align = common_config.vertical_align - }; -} \ No newline at end of file diff --git a/shared/ui/uno/uno.h b/shared/ui/uno/uno.h deleted file mode 100644 index 78511c07..00000000 --- a/shared/ui/uno/uno.h +++ /dev/null @@ -1,58 +0,0 @@ -#pragma once - -#include "types.h" -#include "../graphic_types.h" -#include "../draw/draw.h" - -typedef enum HorizontalAlignment { - Leading, - HorizontalCenter, - Trailing, -} HorizontalAlignment; - -typedef enum VerticalAlignment { - Top, - Bottom, - VerticalCenter, -} VerticalAlignment; - -typedef struct text_ui_config { - const char* text; - uint16_t font_size; -} text_ui_config; - -typedef struct rect_ui_config { - uint32_t border_size; - color border_color; - uint32_t border_padding; -} rect_ui_config; - -typedef struct common_ui_config { - int_point point; - gpu_size size; - HorizontalAlignment horizontal_align; - VerticalAlignment vertical_align; - color background_color; - color foreground_color; -} common_ui_config; - -#ifdef __cplusplus -extern "C" { -#endif - -#define DRAW(item, children)\ -({\ -common_ui_config parent = item;\ -(void)parent;\ -children;\ -}) - -#define RELATIVE(a,b) { parent.point.x + a, parent.point.y + b } - -common_ui_config label(draw_ctx *ctx, text_ui_config text_config, common_ui_config common_config); -common_ui_config textbox(draw_ctx *ctx, text_ui_config text_config, common_ui_config common_config); -common_ui_config rectangle(draw_ctx *ctx, rect_ui_config rect_config, common_ui_config common_config); - -#ifdef __cplusplus -} -#endif \ No newline at end of file diff --git a/shared/utils/console.cpp b/shared/utils/console.cpp deleted file mode 100644 index 447f8aae..00000000 --- a/shared/utils/console.cpp +++ /dev/null @@ -1,227 +0,0 @@ -#include "console.hpp" -#include "std/memory.h" -#include "syscalls/syscalls.h" -#include "math/math.h" - -#define char_width (char_scale*CHAR_SIZE) -#define line_height (char_scale*CHAR_SIZE*2) - -static inline uint32_t line_len(const char* line, uint32_t max_cols){ - uint32_t n = 0; - while (n < max_cols && line[n]) n++; - return n; -} - -Console::Console() : cursor_x(0), cursor_y(0), is_initialized(false){ - -} - -void Console::initialize(){ - is_initialized = true; - dctx = get_ctx(); - resize(); - screen_clear(); -} - -bool Console::check_ready(){ - if (!screen_ready()) return false; - if (!is_initialized){ - initialize(); - } - return true; -} - -void Console::resize(){ - if (!dctx){ - rows = columns = 0; - return; - } - - gpu_size screen_size = { dctx->width, dctx->height }; - uint32_t new_columns = screen_size.width / char_width; - uint32_t new_rows = screen_size.height / line_height; - - if (new_rows == 0 || new_columns == 0) { rows = columns = 0; return; } - - char* old_data = row_data; - uint32_t old_rows = rows; - uint32_t old_cols = columns; - uint32_t old_offset = scroll_row_offset; - - uint32_t new_buf_size = new_rows * new_columns; - char* new_data = (char*)malloc(new_buf_size); - if (!new_data) return; - memset(new_data, 0, new_buf_size); - - if (old_data && old_rows && old_cols) { - uint32_t copy_rows = min(old_rows, new_rows); - - for (uint32_t y = 0; y < copy_rows; y++) { - const char* src = old_data + (((old_offset + y) % old_rows) * old_cols); - char* dst = new_data + (y * new_columns); - uint32_t len = line_len(src, old_cols); - uint32_t w = min(len, new_columns); - if (w) memcpy(dst, src, w); - if (w < new_columns) dst[w] = 0; - } - } - - if (old_data) free_sized(old_data, old_rows * old_cols); - - row_data = new_data; - rows = new_rows; - columns = new_columns; - buffer_data_size = new_buf_size; - scroll_row_offset = 0; - - if ((int32_t)cursor_y < 0) cursor_y = 0; - if ((int32_t)cursor_x < 0) cursor_x = 0; - if (cursor_y >= rows) cursor_y = rows ? rows - 1 : 0; - if (cursor_x >= columns) cursor_x = columns ? columns - 1 : 0; - - last_drawn_cursor_x = -1; - last_drawn_cursor_y = -1; -} - -void Console::put_char(char c){ - if (!check_ready()) return; - - if (c == '\r'){ - cursor_x = 0; - draw_cursor(); - return; - } - if (c == '\n'){ - newline(); - flush(dctx); - return; - } - if (cursor_x >= columns) newline(); - - char* line = row_data + (((scroll_row_offset + cursor_y) % rows) * columns); - line[cursor_x] = c; - if (cursor_x + 1 0){ - cursor_x--; - } else if (cursor_y > 0){ - cursor_y--; - char* line0 = row_data + (((scroll_row_offset + cursor_y) % rows) * columns); - cursor_x = line_len(line0, columns); - draw_cursor(); - flush(dctx); - return; - } else return; - - char* line = row_data + (((scroll_row_offset + cursor_y) % rows) * columns); - line[cursor_x] = 0; - fb_fill_rect(dctx, cursor_x*char_width, cursor_y * line_height, char_width, line_height, bg_color); - draw_cursor(); - flush(dctx); -} - -void Console::draw_cursor(){ - if (last_drawn_cursor_x >= 0 && last_drawn_cursor_y >= 0){ - if ((uint32_t)last_drawn_cursor_x < columns && (uint32_t)last_drawn_cursor_y < rows){ - fb_fill_rect(dctx, last_drawn_cursor_x*char_width, last_drawn_cursor_y * line_height, char_width, line_height, bg_color); - char *prev_line = row_data + (((scroll_row_offset + (uint32_t)last_drawn_cursor_y) % rows) * columns); - char ch = prev_line[last_drawn_cursor_x]; - if (ch) fb_draw_char(dctx, last_drawn_cursor_x * char_width, (last_drawn_cursor_y * line_height)+(line_height/2), ch, char_scale, text_color); - } - } - fb_fill_rect(dctx, cursor_x*char_width, cursor_y * line_height, char_width, line_height, text_color); - last_drawn_cursor_x = (int32_t)cursor_x; - last_drawn_cursor_y = (int32_t)cursor_y; -} - -void Console::put_string(const char* str){ - if (!check_ready()) return; - for (uint32_t i = 0; str[i]; i++) put_char(str[i]); - flush(dctx); -} - -void Console::newline(){ - if (!check_ready()) return; - cursor_x = 0; - cursor_y++; - if (cursor_y >= rows - 1){ - scroll(); - cursor_y = rows - 1; - } else { - char* line = row_data + (((scroll_row_offset + cursor_y) % rows) * columns); - memset(line, 0, columns); - } -} - -void Console::scroll(){ - if (!check_ready()) return; - - scroll_row_offset = (scroll_row_offset + 1) % rows; - uint32_t clear_index = (scroll_row_offset + rows - 1) % rows; - char* line = row_data + clear_index * columns; - memset(line, 0, columns); - - fb_clear(dctx, bg_color); - for (uint32_t y = 0; y < rows; y++) { - char* l = row_data + (((scroll_row_offset + y) % rows) * columns); - uint32_t len = line_len(l, columns); - if (!len) continue; - uint32_t ypix = (y * line_height) + (line_height / 2); - for (uint32_t x = 0; x < len; x++) { - fb_draw_char(dctx, x * char_width, ypix, l[x], char_scale, text_color); - } - } - draw_cursor(); -} - -void Console::refresh(){ - if (!check_ready()) return; - resize(); - screen_clear(); - redraw(); - flush(dctx); -} - -void Console::redraw(){ - if (!check_ready()) return; - - for (uint32_t y = 0; y < rows; y++){ - char* line = row_data + (((scroll_row_offset + y) % rows) *columns); - uint32_t len = line_len(line, columns); - if (!len) continue; - uint32_t ypix = (y * line_height) + (line_height / 2); - for (uint32_t x = 0; x < len; x++){ - fb_draw_char(dctx, x * char_width, ypix, line[x], char_scale, text_color); - } - } - draw_cursor(); -} - -void Console::screen_clear(){ - if (dctx) fb_clear(dctx, bg_color); - last_drawn_cursor_x = -1; - last_drawn_cursor_y = -1; -} - -void Console::clear(){ - screen_clear(); - if (row_data && buffer_data_size) memset(row_data, 0, buffer_data_size); - cursor_x = cursor_y = 0; -} - -const char* Console::get_current_line(){ - return row_data + (((scroll_row_offset + cursor_y) % rows) * columns); -} - -void Console::set_text_color(uint32_t hex){ - text_color = hex | 0xFF000000; -} \ No newline at end of file diff --git a/shared/utils/console.hpp b/shared/utils/console.hpp deleted file mode 100644 index 170bf850..00000000 --- a/shared/utils/console.hpp +++ /dev/null @@ -1,65 +0,0 @@ -#pragma once - -#include "types.h" -#include "data_struct/ring_buffer.hpp" -#include "ui/draw/draw.h" - -#define COLOR_WHITE 0xFFFFFFFF -#define COLOR_BLACK 0 - -class Console{ -public: - Console(); - - void initialize(); - - void put_char(char c); - void put_string(const char* str); - - void newline(); - void scroll(); - void clear(); - void resize(); - - void refresh(); - - void set_active(bool active); - void delete_last_char(); - -protected: - bool check_ready(); - void screen_clear(); - void redraw(); - void draw_cursor(); - const char* get_current_line(); - - virtual draw_ctx* get_ctx() = 0; - virtual void flush(draw_ctx *ctx) = 0; - virtual bool screen_ready() = 0; - - void set_text_color(uint32_t color); - - uint32_t cursor_x, cursor_y; - int32_t last_drawn_cursor_x, last_drawn_cursor_y; - uint32_t columns, rows; - bool is_initialized; - - static constexpr uint32_t max_rows=128; - - uint32_t default_bg_color = COLOR_BLACK; - uint32_t default_text_color = COLOR_WHITE; - uint32_t bg_color = default_bg_color; - uint32_t text_color = default_text_color; - - int32_t scroll_row_offset = 0; - char* row_data; - uint32_t gap_start, gap_end; - uint32_t buffer_data_size; - - draw_ctx *dctx; - - bool active = true; - - uint8_t char_scale = 1; -}; -