src/printf.c

changeset 643
5700ba9154ab
parent 634
f78d3b77d456
child 644
fcaa0891ef28
equal deleted inserted replaced
642:98c90759f69e 643:5700ba9154ab
29 #include "cx/printf.h" 29 #include "cx/printf.h"
30 30
31 #include <stdio.h> 31 #include <stdio.h>
32 #include <string.h> 32 #include <string.h>
33 33
34 #define CX_PRINTF_BUFSIZE 256 34 #ifndef CX_PRINTF_SBO_SIZE
35 #define CX_PRINTF_SBO_SIZE 512
36 #endif
35 37
36 int cx_fprintf(void *stream, cx_write_func wfc, char const *fmt, ...) { 38 int cx_fprintf(
39 void *stream,
40 cx_write_func wfc,
41 char const *fmt,
42 ...
43 ) {
37 int ret; 44 int ret;
38 va_list ap; 45 va_list ap;
39 va_start(ap, fmt); 46 va_start(ap, fmt);
40 ret = cx_vfprintf(stream, wfc, fmt, ap); 47 ret = cx_vfprintf(stream, wfc, fmt, ap);
41 va_end(ap); 48 va_end(ap);
42 return ret; 49 return ret;
43 } 50 }
44 51
45 int cx_vfprintf(void *stream, cx_write_func wfc, char const *fmt, va_list ap) { 52 int cx_vfprintf(void *stream, cx_write_func wfc, char const *fmt, va_list ap) {
46 char buf[CX_PRINTF_BUFSIZE]; 53 char buf[CX_PRINTF_SBO_SIZE];
47 va_list ap2; 54 va_list ap2;
48 va_copy(ap2, ap); 55 va_copy(ap2, ap);
49 int ret = vsnprintf(buf, CX_PRINTF_BUFSIZE, fmt, ap); 56 int ret = vsnprintf(buf, CX_PRINTF_SBO_SIZE, fmt, ap);
50 if (ret < 0) { 57 if (ret < 0) {
51 return ret; 58 return ret;
52 } else if (ret < CX_PRINTF_BUFSIZE) { 59 } else if (ret < CX_PRINTF_SBO_SIZE) {
53 return (int) wfc(buf, 1, ret, stream); 60 return (int) wfc(buf, 1, ret, stream);
54 } else { 61 } else {
55 int len = ret + 1; 62 int len = ret + 1;
56 char *newbuf = malloc(len); 63 char *newbuf = malloc(len);
57 if (!newbuf) { 64 if (!newbuf) {
78 85
79 cxmutstr cx_vasprintf_a(CxAllocator *a, char const *fmt, va_list ap) { 86 cxmutstr cx_vasprintf_a(CxAllocator *a, char const *fmt, va_list ap) {
80 cxmutstr s; 87 cxmutstr s;
81 s.ptr = NULL; 88 s.ptr = NULL;
82 s.length = 0; 89 s.length = 0;
83 char buf[CX_PRINTF_BUFSIZE]; 90 char buf[CX_PRINTF_SBO_SIZE];
84 va_list ap2; 91 va_list ap2;
85 va_copy(ap2, ap); 92 va_copy(ap2, ap);
86 int ret = vsnprintf(buf, CX_PRINTF_BUFSIZE, fmt, ap); 93 int ret = vsnprintf(buf, CX_PRINTF_SBO_SIZE, fmt, ap);
87 if (ret > 0 && ret < CX_PRINTF_BUFSIZE) { 94 if (ret > 0 && ret < CX_PRINTF_SBO_SIZE) {
88 s.ptr = cxMalloc(a, ret + 1); 95 s.ptr = cxMalloc(a, ret + 1);
89 if (s.ptr) { 96 if (s.ptr) {
90 s.length = (size_t) ret; 97 s.length = (size_t) ret;
91 memcpy(s.ptr, buf, ret); 98 memcpy(s.ptr, buf, ret);
92 s.ptr[s.length] = '\0'; 99 s.ptr[s.length] = '\0';

mercurial