QPMS
Electromagnetic multiple scattering library and toolkit.
Loading...
Searching...
No Matches
canonbuf.h
Go to the documentation of this file.
1
12#ifndef QPMS_CANONBUF_H
13#define QPMS_CANONBUF_H
14
15#include <complex.h>
16#include <float.h>
17#include <stdarg.h>
18#include <stdio.h>
19#include <stdlib.h>
20#include <string.h>
21
22typedef struct {
23 char *buf;
24 size_t len, cap;
26
28static inline void qpms_canonbuf_free(qpms_canonbuf_t *b) {
29 free(b->buf);
30 b->buf = NULL;
31 b->len = b->cap = 0;
32}
33
34static inline int qcb_reserve(qpms_canonbuf_t *b, size_t extra) {
35 if (b->len + extra + 1 <= b->cap) return 0;
36 size_t ncap = b->cap ? b->cap : 4096;
37 while (b->len + extra + 1 > ncap) ncap *= 2;
38 char *nb = realloc(b->buf, ncap);
39 if (!nb) return -1;
40 b->buf = nb;
41 b->cap = ncap;
42 return 0;
43}
44
46static inline int qpms_canonbuf_printf(qpms_canonbuf_t *b, const char *fmt, ...)
47#if defined(__GNUC__)
48 __attribute__((format(printf, 2, 3)))
49#endif
50;
51
52static inline int qpms_canonbuf_printf(qpms_canonbuf_t *b, const char *fmt, ...) {
53 va_list ap;
54 va_start(ap, fmt);
55 va_list ap2;
56 va_copy(ap2, ap);
57 const int need = vsnprintf(NULL, 0, fmt, ap);
58 va_end(ap);
59 if (need < 0 || qcb_reserve(b, (size_t)need)) {
60 va_end(ap2);
61 return -1;
62 }
63 vsnprintf(b->buf + b->len, (size_t)need + 1, fmt, ap2);
64 va_end(ap2);
65 b->len += (size_t)need;
66 return 0;
67}
68
70static inline int qpms_canonbuf_double(qpms_canonbuf_t *b, double v) {
71 return qpms_canonbuf_printf(b, "%.17g", v);
72}
73
75static inline int qpms_canonbuf_cdouble(qpms_canonbuf_t *b, _Complex double v) {
76 return qpms_canonbuf_printf(b, "(%.17g,%.17g)", creal(v), cimag(v));
77}
78
80
81static inline int qpms_canonbuf_string(qpms_canonbuf_t *b, const char *s) {
82 if (!s) return qpms_canonbuf_printf(b, "-");
83 return qpms_canonbuf_printf(b, "%zu:%s", strlen(s), s);
84}
85
86#endif // QPMS_CANONBUF_H
static int qpms_canonbuf_double(qpms_canonbuf_t *b, double v)
Appends a double with round-trip exactness (%.17g).
Definition canonbuf.h:70
static int qpms_canonbuf_cdouble(qpms_canonbuf_t *b, _Complex double v)
Appends a complex double as "(re,im)" with round-trip exact parts.
Definition canonbuf.h:75
static int qpms_canonbuf_printf(qpms_canonbuf_t *b, const char *fmt,...)
Appends a printf-formatted string; 0 on success, -1 on error.
Definition canonbuf.h:52
static int qpms_canonbuf_string(qpms_canonbuf_t *b, const char *s)
Appends a length-prefixed string (delimiter-safe; NULL and "" differ).
Definition canonbuf.h:81
static void qpms_canonbuf_free(qpms_canonbuf_t *b)
Frees the buffer contents (safe on a zero-initialised buffer).
Definition canonbuf.h:28
Definition canonbuf.h:22