From 9e660e594f6d3a43ea1427fb872801a2fcedad93 Mon Sep 17 00:00:00 2001 From: Krow Savcik Date: Tue, 26 Sep 2023 22:32:35 +0300 Subject: initial commit --- src/palette.c | 113 ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 113 insertions(+) create mode 100644 src/palette.c (limited to 'src/palette.c') diff --git a/src/palette.c b/src/palette.c new file mode 100644 index 0000000..3584e55 --- /dev/null +++ b/src/palette.c @@ -0,0 +1,113 @@ +#include +#include +#include + +#include "palette.h" +#include "debug.h" +#include "types.h" + +Palette * +palette_clone(const Palette *p) +{ + Palette *res; + + /* TODO: better malloc (place list and num together) */ + res = malloc(sizeof(Palette)); + res->clist = malloc(p->num*sizeof(*p->clist)); + + res->num = p->num; + memcpy(res->clist, p->clist, p->num * sizeof(*p->clist)); + + return res; +} + +static char * +palette_intern_get_num(char *s, int *a) +{ + while (*s == ' ' || *s == '\t') + ++s; + if (*s == '\n') + *a = -1; + else { + *a = 0; + while (*s >= '0' && *s <= '9') { + *a = (*a) * 10; + *a += (int) (*s-'0'); + ++s; + } + } + + return s; +} + +static uint8 +palette_intern_get_color(char *s, Color *c) +{ + int a; + char *st = s; + + st = palette_intern_get_num(st, &a); + if (a < 0 || a > 255) return 1; + c->r = a; + + st = palette_intern_get_num(st, &a); + if (a < 0 || a > 255) return 1; + c->g = a; + + st = palette_intern_get_num(st, &a); + if (a < 0 || a > 255) return 1; + c->b = a; + + return 0; +} + +static uint +palette_intern_get_color_number(const char *s) +{ + FILE *fp; + char line[1024]; + size_t len = 1024; + uint ans = 0; + + fp = fopen(s, "r"); + while (fgets(line, len, fp)) { + if (line[0] >= '0' && line[0] <= '9') + ++ans; + } + fclose(fp); + + return ans; +} + +Palette * +palette_open_gpl(const char *p) +{ + /* TODO: check if file exists */ + /* TODO: better parsing */ + /* TODO: better malloc (place list and num together) */ + Palette *res; + FILE *fp; + Color *c; + char line[1024]; + size_t len = 1024; + + res = malloc(sizeof(Palette)); + res->num = palette_intern_get_color_number(p); + res->clist = malloc(res->num*sizeof(*res->clist)); + c = res->clist; + + fp = fopen(p, "r"); + while (fgets(line, len, fp)) { + if (line[0] >= '0' && line[0] <= '9') { + if (palette_intern_get_color(line, c)) { + free(res->clist); + free(res); + return NULL; + } + c++; + } + } + fclose(fp); + + return res; +} -- cgit v1.2.3