Skip to content

Commit

Permalink
chore(str): change fmt_str to s_fmt
Browse files Browse the repository at this point in the history
  • Loading branch information
exbotanical committed Jan 20, 2024
1 parent 7745008 commit b5b0773
Show file tree
Hide file tree
Showing 8 changed files with 32 additions and 41 deletions.
2 changes: 1 addition & 1 deletion clib.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"name": "libutil",
"version": "0.0.13",
"version": "0.1.13",
"author": "Matthew Zito",
"repo": "exbotanical/libutil",
"license": "MIT",
Expand Down
2 changes: 1 addition & 1 deletion include/libutil.h
Original file line number Diff line number Diff line change
Expand Up @@ -229,7 +229,7 @@ void buffer_free(buffer_t *buf);
/**
* Returns a formatted string. Uses printf syntax.
*/
char *fmt_str(char *fmt, ...);
char *s_fmt(char *fmt, ...);

/**
* s_truncate truncates the given string `s` by `n` characters.
Expand Down
25 changes: 0 additions & 25 deletions src/fmt.c

This file was deleted.

21 changes: 21 additions & 0 deletions src/str.c
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
#include <ctype.h> // for toupper
#include <stdarg.h>
#include <stdio.h> // for snprintf
#include <stdlib.h>
#include <string.h>
Expand Down Expand Up @@ -212,3 +213,23 @@ array_t *s_split(const char *s, const char *delim) {

return tokens;
}

char *s_fmt(char *fmt, ...) {
va_list args, args_cp;
va_start(args, fmt);
va_copy(args_cp, args);

// Pass length of zero first to determine number of bytes needed
unsigned int n = vsnprintf(NULL, 0, fmt, args) + 1;
char *buf = malloc(n);
if (!buf) {
return NULL;
}

vsnprintf(buf, n, fmt, args_cp);

va_end(args);
va_end(args_cp);

return buf;
}
12 changes: 0 additions & 12 deletions t/fmt_test.c

This file was deleted.

1 change: 0 additions & 1 deletion t/main.c
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,6 @@ int main() {

run_array_tests();
run_buffer_tests();
run_fmt_tests();
run_str_tests();

done_testing();
Expand Down
9 changes: 9 additions & 0 deletions t/str_test.c
Original file line number Diff line number Diff line change
Expand Up @@ -290,6 +290,13 @@ void test_s_split_end_match(void) {
array_free_ptrs(paths);
}

void test_s_fmt(void) {
char *formatted = s_fmt("%s %d %s", "test", 11, "string");
is(formatted, "test 11 string", "formats each part into a single string");

free(formatted);
}

void run_str_tests(void) {
test_s_copy();

Expand Down Expand Up @@ -325,4 +332,6 @@ void run_str_tests(void) {
test_s_split_no_match();
test_s_split_empty_input();
test_s_split_end_match();

test_s_fmt();
}
1 change: 0 additions & 1 deletion t/tests.h
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,6 @@

void run_array_tests(void);
void run_buffer_tests(void);
void run_fmt_tests(void);
void run_str_tests(void);

#endif /* TESTS_H */

0 comments on commit b5b0773

Please sign in to comment.