Skip to content

Commit

Permalink
Added a substring to char* function
Browse files Browse the repository at this point in the history
  • Loading branch information
RolandMarchand committed Jul 15, 2022
1 parent 68f0942 commit 9ab919f
Show file tree
Hide file tree
Showing 2 changed files with 20 additions and 0 deletions.
15 changes: 15 additions & 0 deletions src/scanner/substring.c
Original file line number Diff line number Diff line change
Expand Up @@ -24,9 +24,24 @@
#include "substring.h"

#include <string.h>
#include <stdio.h>

void sbstrcpy(const struct substring *from, char *to)
{
strncpy(to, from->start, SUBSTRING_LENGTH(*from) - 1);
to[SUBSTRING_LENGTH(*from) - 1] = '\0';
}

char *sbstr2str(const struct substring *sbstr)
{
if (SUBSTRING_LENGTH(*sbstr) > 1024) {
fprintf(stderr, "Max substring size of 1024 allowed.\
Use sbstrcpy() instead.\n");
return NULL;
}

static char string[1024];
sbstrcpy(sbstr, string);

return string;
}
5 changes: 5 additions & 0 deletions src/scanner/substring.h
Original file line number Diff line number Diff line change
Expand Up @@ -31,4 +31,9 @@ struct substring {
char *end;
};

/* write the contents of `from` to `to`
* `to` must have the size of SUBSTRING_LENGTH(from) */
extern void sbstrcpy(const struct substring *from, char *to);
/* return a manually allocated string of max size 1024
* if the size exceeds the limit, retun null*/
extern char *sbstr2str(const struct substring *sbstr);

0 comments on commit 9ab919f

Please sign in to comment.