add string functions, cleanup vector docs

This commit is contained in:
2023-12-03 17:08:04 -08:00
parent 0857e7a0a1
commit 194acafd3a
6 changed files with 134 additions and 2 deletions

40
docs/string.md Normal file
View File

@ -0,0 +1,40 @@
# string
C string helpers
## Functions
### find_substrings
Finds the indexes of all locations of the given needle in the haystack. The returned array of `size_t` is allocated by
this function and memory cleanup is managed by the user. `num_substrings` is a pointer to a pre-allocated `size_t` that will
be modified to contain the number of found substrings and subsequently the size of the returned array of `size_t`.
Returns `NULL` and prints to `stderr` if there is an error.
```c
size_t *find_substrings(const char* haystack, const char* needle, size_t *num_substrings);
/* Usage */
const char* haystack = "One two three two";
const char* needle = "two";
size_t subs_sz = 0;
size_t *subs = find_substrings(haystack, needle, &subs_sz);
// subs: [ 4, 14 ]
// subs_sz: 2
free(subs);
```
### substr
Extracts a substring at a specific index and length. This function returns a copy of the substring in a heap allocated
buffer that the user is responsible for freeing. Returns `NULL` and prints to `stderr` if there is an error.
```c
const char* substr(const char* str, size_t idx, size_t len);
/* Usage */
const char *s = substr("One two three", 4, 3);
assert(strcmp(s, "two") == 0);
free(s);
```

View File

@ -117,7 +117,7 @@ Shrinks the capacity of the vector down to the current length. Returns a non-zer
int vec_shrink(Vector *vec);
```
## vec_max
### vec_max
Finds the largest value in the vector and returns a void pointer to the underlying data. Requires a
comparison function to compare the data in the vector. This function must return `1` if `a > b`, `-1` if
@ -127,7 +127,7 @@ comparison function to compare the data in the vector. This function must return
const void *vec_min(const Vector *vec, int(*cmp)(const void *a, const void *b));
```
## vec_min
### vec_min
Finds the smallest value in the vector and returns a void pointer to the underlying data. Requires a
comparison function to compare the data in the vector. This function must return `1` if `a > b`, `-1` if