From 15e119014bfaf138d476351f72ccec52270f9713 Mon Sep 17 00:00:00 2001 From: fall-leaf Date: Fri, 4 Aug 2023 14:21:59 +0300 Subject: [PATCH] added a string split function --- include/parse.h | 24 +++++++++++------------ src/parse.c | 61 +++++++++++++++++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 73 insertions(+), 12 deletions(-) diff --git a/include/parse.h b/include/parse.h index c054c39..17a8994 100644 --- a/include/parse.h +++ b/include/parse.h @@ -2,21 +2,21 @@ typedef struct { - size_t admin_count; - char * username; - char * password; - char * channel; - char * server; - char ** admins; - int port; + char * username; + char * password; + char * channel; + char * server; + int port; } creds_t; -VARDECL creds_t creds; +extern creds_t creds; -DECL char * dump(void); -DECL char * raw(char const * const sql); -DECL char * remind(char * who); -DECL char * slurp(char const * fn); +DECL char ** str_split(char const * s, char c); +DECL void split_clean(char ** split) +DECL char * dump(void); +DECL char * raw(char const * const sql); +DECL char * remind(char * who); +DECL char * slurp(char const * fn); DECL int is_admin(char const * user); DECL void parse_admins(char * admin_string); DECL int parse_pair(char const * buf, size_t const len); diff --git a/src/parse.c b/src/parse.c index ce5caf0..89757da 100644 --- a/src/parse.c +++ b/src/parse.c @@ -52,6 +52,67 @@ VARDECL size_t const cred_names_len[] = VARDECL creds_t creds = {0}; +DECL char ** +str_split(char const * s, char c) +{ + char ** ret = NULL; + size_t i = 0; + + size_t current_token_i = 0; + + size_t token_start_i = 0; + size_t tokens_q = 0; + + /* count tokens */ + for (i = 1; s[i]; ++i) + { + /* end of a token*/ + if (s[i] == c && s[i - 1] != c) + { ++tokens_q; } + } + ++tokens_q; + + ret = (char **)calloc(tokens_q + 1, sizeof(char *)); + if (!ret) + { return ret; } + + for (i = 1; s[i]; ++i) + { + + if (s[i] == c && s[i - 1] != c) + { + /* end of a token*/ + ret[current_token_i] = strndup(s + token_start_i, i - token_start_i); + if (!ret[current_token_i]) + { + split_clean(ret); + return NULL; + } + ++current_token_i; + } + else if (s[i] != c && s[i - 1] == c) + { + /* start of a token */ + token_start_i = i; + } + } + + /* Signal that the split array is ended (for iteration purposes) */ + ret[current_token_i + 1] = NULL; + + return ret; +} + +DECL void +split_clean(char ** split) +{ + while (*split) + { + free(*split); + } + free(split); +} + DECL char * slurp(char const * fn) {