rcx

library of miscellaneous bits of C code
git clone git://git.rr3.xyz/rcx
Log | Files | Refs | README | LICENSE

commit fffb80f7fe99ba70ea6b49447bfbf92698d3454e
parent fbf42beb9362e5d583019b33e968e76a6707fd2b
Author: Robert Russell <robertrussell.72001@gmail.com>
Date:   Tue, 13 Jun 2023 13:33:21 -0700

Add str_alloc_cstr

Diffstat:
MMakefile | 2+-
Minc/string.h | 5+++++
Msrc/string.c | 12++++++++++++
3 files changed, 18 insertions(+), 1 deletion(-)

diff --git a/Makefile b/Makefile @@ -33,7 +33,7 @@ src/log.o: src/log.c inc/def.h inc/log.h inc/rcx.h config.mk src/opt.o: src/opt.c inc/def.h inc/opt.h inc/rcx.h config.mk src/rand.o: src/rand.c inc/bits.h inc/def.h inc/rand.h inc/rcx.h inc/unix.h config.mk src/str.o: src/str.c inc/alloc.h inc/debug.h inc/def.h inc/log.h inc/rcx.h inc/str.h config.mk -src/string.o: src/string.c inc/buffer.h inc/debug.h inc/def.h inc/rcx.h inc/string.h inc/utf8.h config.mk +src/string.o: src/string.c inc/alloc.h inc/buffer.h inc/debug.h inc/def.h inc/rcx.h inc/string.h inc/utf8.h config.mk src/unicode.o: src/unicode.c inc/def.h inc/rcx.h gen/ucattab.inc config.mk src/unix.o: src/unix.c inc/debug.h inc/def.h inc/rcx.h inc/unix.h config.mk src/utf8.o: src/utf8.c inc/def.h inc/rcx.h inc/utf8.h config.mk diff --git a/inc/string.h b/inc/string.h @@ -7,6 +7,9 @@ #include "def.h" #include "utf8.h" +/* Usage: printf("...%.*s...", STR_FMT(s)) */ +#define STR_FMT(s) (assert(str_len(s) <= INT_MAX), (int)str_len(s)), str_bytes(s) + typedef struct str Str; struct str { @@ -80,6 +83,8 @@ str_eq(Str s, Str t) { #define str_slice(s, l, ...) str_slice_(s, l, VA_DEFAULT(,##__VA_ARGS__, str_len(s))) Str str_slice_(Str s, isize l, isize u); +char *str_alloc_cstr(Str s); + static inline usize str_utf8_decode(rune *c, Str s) { return r_utf8_decode(c, (char *)s.data, s.len); diff --git a/src/string.c b/src/string.c @@ -1,5 +1,7 @@ #include <stdio.h> +#include <string.h> +#include "alloc.h" #include "debug.h" #include "rcx.h" #include "string.h" @@ -52,3 +54,13 @@ str_slice_(Str s, isize l, isize u) { .data = s.data + l, }; } + +char * +str_alloc_cstr(Str s) { + char *c = r_alloc(str_len(s) + 1); + if (!c) return 0; + memcpy(c, str_bytes(s), str_len(s)); + c[str_len(s)] = '\0'; + return c; +} +