]>
Commit | Line | Data |
---|---|---|
acddc0ed | 1 | // SPDX-License-Identifier: GPL-2.0-or-later |
31bfa062 CF |
2 | /* |
3 | * Simple string buffer | |
4 | * | |
5 | * Copyright (C) 2017 Christian Franke | |
31bfa062 CF |
6 | */ |
7 | #ifndef SBUF_H | |
8 | #define SBUF_H | |
9 | ||
5e244469 RW |
10 | #ifdef __cplusplus |
11 | extern "C" { | |
12 | #endif | |
13 | ||
31bfa062 CF |
14 | /* |
15 | * sbuf provides a simple string buffer. One application where this comes | |
16 | * in handy is the parsing of binary data: If there is an error in the parsing | |
17 | * process due to invalid input data, printing an error message explaining what | |
18 | * went wrong is definitely useful. However, just printing the actual error, | |
19 | * without any information about the previous parsing steps, is usually not very | |
20 | * helpful. | |
21 | * Using sbuf, the parser can log the whole parsing process into a buffer using | |
214d8a60 | 22 | * a printf like API. When an error occurs, all the information about previous |
31bfa062 CF |
23 | * parsing steps is there in the log, without any need for backtracking, and can |
24 | * be used to give a detailed and useful error description. | |
25 | * When parsing completes successfully without any error, the log can just be | |
26 | * discarded unless debugging is turned on, to not spam the log. | |
27 | * | |
28 | * For the described usecase, the code would look something like this: | |
29 | * | |
30 | * int sbuf_example(..., char **parser_log) | |
31 | * { | |
32 | * struct sbuf logbuf; | |
33 | * | |
34 | * sbuf_init(&logbuf, NULL, 0); | |
35 | * sbuf_push(&logbuf, 0, "Starting parser\n"); | |
36 | * | |
37 | * int rv = do_parse(&logbuf, ...); | |
38 | * | |
39 | * *parser_log = sbuf_buf(&logbuf); | |
40 | * | |
41 | * return 1; | |
42 | * } | |
43 | * | |
996c9314 LB |
44 | * In this case, sbuf_example uses a string buffer with undefined size, which |
45 | * will | |
46 | * be allocated on the heap by sbuf. The caller of sbuf_example is expected to | |
47 | * free | |
31bfa062 CF |
48 | * the string returned in parser_log. |
49 | */ | |
50 | ||
6c2cafdc LS |
51 | #define SBUF_DEFAULT_SIZE 8192 |
52 | ||
31bfa062 CF |
53 | struct sbuf { |
54 | bool fixed; | |
55 | char *buf; | |
56 | size_t size; | |
57 | size_t pos; | |
58 | int indent; | |
59 | }; | |
60 | ||
61 | void sbuf_init(struct sbuf *dest, char *buf, size_t size); | |
62 | void sbuf_reset(struct sbuf *buf); | |
63 | const char *sbuf_buf(struct sbuf *buf); | |
64 | void sbuf_free(struct sbuf *buf); | |
65 | #include "lib/log.h" | |
66 | void sbuf_push(struct sbuf *buf, int indent, const char *format, ...) | |
afb35622 | 67 | PRINTFRR(3, 4); |
31bfa062 | 68 | |
5e244469 RW |
69 | #ifdef __cplusplus |
70 | } | |
71 | #endif | |
72 | ||
31bfa062 | 73 | #endif |