fix: tiny refactor of mkstr, reset strs_cnt

This commit is contained in:
0xdeadbeer 2024-09-03 21:01:26 +02:00
parent 42ed96353d
commit ca1293aa8f
2 changed files with 14 additions and 12 deletions

View File

@ -4,7 +4,7 @@
#include <math.h> #include <math.h>
#include "streecmp.h" #include "streecmp.h"
int strs_cnt = 0; static int strs_cnt = 1;
void frenod(struct nod *nod) { void frenod(struct nod *nod) {
for (int i = 0; i < POOL_SIZE; i++) { for (int i = 0; i < POOL_SIZE; i++) {
@ -51,14 +51,14 @@ struct nod *mknod(struct nod *nod, int loc) {
return nod->pool[loc]; return nod->pool[loc];
} }
int mkstr(struct nod *nod, char *str) { int mkstr(struct nod *nod, char *str, int val) {
struct nod *target = nod->pool[*str]; struct nod *target = nod->pool[*str];
if (target != NULL) { if (target != NULL) {
if (*str == '\0') { if (*str == '\0') {
return 0; return 0;
} }
return mkstr(target, str+1); return mkstr(target, str+1, val);
} }
struct nod *new = mknod(nod, *str); struct nod *new = mknod(nod, *str);
@ -68,15 +68,16 @@ int mkstr(struct nod *nod, char *str) {
new->val.cval = *str; new->val.cval = *str;
if (*str != '\0') { if (*str != '\0') {
return mkstr(new, str+1); return mkstr(new, str+1, val);
} }
strs_cnt++; new->val.ival = val;
new->val.ival = strs_cnt; return val;
return strs_cnt;
} }
int gentree(struct nod *nod, char *strs, char *delim) { int gentree(struct nod *nod, char *strs, char *delim) {
strs_cnt = 1;
char *strs_cpy = strdup(strs); char *strs_cpy = strdup(strs);
if (strs_cpy == NULL) { if (strs_cpy == NULL) {
goto _err; goto _err;
@ -88,10 +89,11 @@ int gentree(struct nod *nod, char *strs, char *delim) {
for (char *tok = strtok(strs_cpy, delim); tok != NULL; tok for (char *tok = strtok(strs_cpy, delim); tok != NULL; tok
= strtok(NULL, delim)) { = strtok(NULL, delim)) {
int ret = mkstr(nod, tok); int ret = mkstr(nod, tok, strs_cnt);
if (ret < 0) { if (ret < 0) {
goto _err_mkstr; goto _err_mkstr;
} }
strs_cnt++;
} }
free(strs_cpy); free(strs_cpy);
@ -130,12 +132,12 @@ int streencmp(struct nod *nod, char *str, int len) {
sptr++; sptr++;
} }
struct nod *end = nptr->pool['\0']; nptr = nptr->pool['\0'];
if (end == NULL) { if (nptr == NULL) {
goto _not_found; goto _not_found;
} }
return end->val.ival; return nptr->val.ival;
_not_found: _not_found:
return 0; return 0;

View File

@ -18,7 +18,7 @@ struct nod {
void frenod(struct nod *nod); void frenod(struct nod *nod);
struct nod *allocnod(void); struct nod *allocnod(void);
struct nod *mknod(struct nod *nod, int loc); struct nod *mknod(struct nod *nod, int loc);
int mkstr(struct nod *nod, char *str); int mkstr(struct nod *nod, char *str, int val);
int gentree(struct nod *nod, char *strs, char *delim); int gentree(struct nod *nod, char *strs, char *delim);
int streecmp(struct nod *nod, char *str); int streecmp(struct nod *nod, char *str);
int streencmp(struct nod *nod, char *str, int len); int streencmp(struct nod *nod, char *str, int len);