rcx

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

string.c (890B)


      1 #include <stdio.h>
      2 #include <string.h>
      3 
      4 #include "alloc.h"
      5 #include "rcx.h"
      6 #include "string.h"
      7 
      8 int
      9 str_alloc_printf(Str *str, char *fmt, ...) {
     10 	va_list args;
     11 	va_start(args, fmt);
     12 	int ret = str_alloc_vprintf(str, fmt, args);
     13 	va_end(args);
     14 	return ret;
     15 }
     16 
     17 int
     18 str_alloc_vprintf(Str *str, char *fmt, va_list args) {
     19 	/* XXX: Using stdlib printf means we waste 1 byte for null term. */
     20 
     21 	va_list args2;
     22 	va_copy(args2, args);
     23 	int ret = vsnprintf(0, 0, fmt, args2);
     24 	va_end(args2);
     25 	if (ret < 0) return -1;
     26 	usize len = ret;
     27 
     28 	usize buflen = len + 1u;
     29 	char *buf = r_alloc(buflen);
     30 	if (!buf) return -1;
     31 
     32 	ret = vsnprintf(buf, buflen, fmt, args);
     33 	if (ret < 0) {
     34 		free(buf);
     35 		return -1;
     36 	}
     37 
     38 	str->len = len;
     39 	str->data = (u8 *)buf;
     40 	return 0;
     41 }
     42 
     43 char *
     44 str_alloc_cstr(Str s) {
     45 	char *c = r_alloc(s.len + 1);
     46 	if (!c) return 0;
     47 	memcpy(c, s.data, s.len);
     48 	c[s.len] = '\0';
     49 	return c;
     50 }
     51