Single header string library for microcontrollers
Single header string library for microcontrollers implements the
following routines:
*printf() - implements printf() family of functions that can print
standard specifiers (including floating point %f and %g) as well as
non-standard %m and %M specifiers that allow custom formatting like JSON,
hex, base64
xmatch() - glob pattern match with captures
json_get() - find element in a JSON string
json_get_num() - fetch numeric value from a JSON string
json_get_bool() - fetch boolean value from a JSON string
json_get_str() - fetch string value from a JSON string
xhexdump() - print hex dump of the given memory buffer
Features
- Ideal for implementing serial protocols, debug logging, JSON data exchange
- Source code is both ISO C and ISO C++ compliant
- Tiny size: see the Footprint section below for exact numbers
*printf() supports all major format specifiers, width, precition and alignment
*printf() supports floating point %f and %g specifiers by default
*printf() Supports non-standard %M,%m specifiers which allows for custom formats
- Can print to anything: to a memory buffer, file, socket, UART, etc
- Extensively tested using VC98, VC22, ARM GCC, AVR GCC, x86 GCC, Clang
Usage example
Printing to a buffer:
|
xprintf(out, NULL, "%s: %g\n", "dbl", 1.234); // dbl: 1.234 |
|
xprintf(out, NULL, "%.*s\n", 3, "foobar"); // foo |
|
xprintf(out, NULL, "%#04x\n", 11); // 0x0b |
|
xprintf(out, NULL, "%d %5s\n", 7, "pad"); // 7 pad |
Print to the UART. Output JSON, and base64-encoded data:
|
#include "str.h" |
|
|
|
void xputchar(char ch, void *arg) { Serial.write(ch); } |
|
#define printf(fmt, ...) xprintf(xputchar, NULL, fmt, __VA_ARGS__) |
|
|
|
void setup() { |
|
Serial.begin(115200); |
|
} |
|
|
|
void loop() { |
|
printf("JSON: {%m:%g,[%d]}\n", ESC("value"), 1.234, 42); |
|
printf("Base64: %M\n", fmt_b64, 5, "hello"); |
|
delay(1000); |
|
} |
Parse JSON:
|
char buf[100]; |
|
const char *json = "{ \"a\": -42, \"b\": \"hi\", \"c\": true }"; |
|
int b = 0; |
|
assert(json_get_long(json, (int) strlen(json), "$.a", 0) == -42); |
|
assert(json_get_str(json, (int) strlen(json), "$.b", buf, sizeof(buf)) == 2); |
|
assert(strcmp(buf, "hi") == 0); |
|
assert(json_get_bool(json, (int) strlen(json), "$.c", &b) == 1); |
|
assert(b == 1); |
Parse and print floating point:
|
char buf[20]; |
|
double d; |
|
json_get_num("1.23", 4, "$", &d); // Parse floating point number |
|
xsnprintf(buf, sizeof(buf), "%g", d); // 1.23 (print parsed number) |
Code duplication
str.h is divided in two parts: API declaration, and implementation.
The implementation part is wrapped into the preprocessor conditional:
// API declarations
size_t xprintf(void (*)(char, void *), void *, const char *, ...);
...
#ifndef STR_API_ONLY
// Implementation
......
#endif
If more than one file includes str.h, then the build will result in
duplicate symbols, because the implementation will end up duplicated in
several object files.
To avoid this, only one file should include the full
str.h, and the rest of the files should only include API declarations:
file1.c:
file2.c, file3.c, ...:
#define STR_API_ONLY
#include "str.h"
...
API reference
xprintf(), vxprintf()
size_t vxprintf(void (*fn)(char, void *), void *arg, const char *fmt, va_list *);
size_t xprintf(void (*fn)(char, void *), void *arg, const char *fmt, ...);
Print formatted string using an output function fn(). The output function
outputs a single byte: void fn(char ch, void *param) { ... }. By using
different output functions, it is possible to print data to anywhere.
Parameters:
fn - an output function
arg - an parameter for the fn() output function
fmt - printf-like format string which supports the following specifiers:
%hhd, %hd, %d, %ld, %lld - for char, short, int, long, int64_t
%hhu, %hu, %u, %lu, %llu - same but for unsigned variants
%hhx, %hx, %x, %lx, %llx - same, for unsigned hex output
%g, %f - for double
%c - for char
%s - for char *
%% - prints % character itself
%p - for any pointer, prints 0x..... hex value
%M - (NON-STANDARD EXTENSION): prints using a custom format function
%m - (NON-STANDARD EXTENSION): same as %M but double-quotes the result
%X.Y - optional width and precision modifiers
%.* - optional precision modifier specified as int argument
Return value: Number of bytes printed
The %M specifier expects a cusom format function that can grab any number of
positional arguments. That format function should return the number of bytes
it has printed. Here its signature:
size_t (*ff)(void (*fn)(char, void *), void *arg, va_list *ap);
Parameters:
fn - an output function
arg - an parameter for the fn() output function
ap - a pointer for fetching positional arguments
This library ships with several pre-defined format functions described below.
For example, a fmt_b64() format function grabs two positional arguments:
int and void *, and base64-encodes that memory location:
char buf[100]; // Base64-encode "abc"
xsnprintf(buf, sizeof(buf), "%M", fmt_b64, 3, "abc"); // buf contains: YWJj
xsnprintf(), xvsnprintf()
size_t xvsnprintf(char *buf, size_t len, const char *fmt, va_list *ap);
size_t xsnprintf(char *buf, size_t len, const char *fmt, ...);
Print formatted string into a fixed-size buffer. Parameters:
buf - a buffer to print to. Can be NULL, in this case len must be 0
len - a size of the buf
fmt - a format string. Supports all specifiers mentioned above
Return value: number of bytes printed. The result is guaranteed to be NUL
terminated.
json_get()
int json_get(const char *buf, int len, const char *path, int *size);
Parse JSON string buf, len and return the offset of the element
specified by the JSON path. The length of the element is stored in size.
Parameters:
buf - a pointer to a JSON string
len - a length of a JSON string
path - a JSON path. Must start with $, e.g. $.user, $[12], $, etc
size - a pointer that receives element's length. Can be NULL
Return value: offset of the element, or negative value on error.
Usage example: