]> git.proxmox.com Git - mirror_frr.git/blob - lib/sbuf.h
zebra, lib: fix the ZEBRA_INTERFACE_VRF_UPDATE zapi message
[mirror_frr.git] / lib / sbuf.h
1 /*
2 * Simple string buffer
3 *
4 * Copyright (C) 2017 Christian Franke
5 *
6 * This file is part of FRR.
7 *
8 * FRR is free software; you can redistribute it and/or modify it
9 * under the terms of the GNU General Public License as published by the
10 * Free Software Foundation; either version 2, or (at your option) any
11 * later version.
12 *
13 * FRR is distributed in the hope that it will be useful, but
14 * WITHOUT ANY WARRANTY; without even the implied warranty of
15 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
16 * General Public License for more details.
17 *
18 * You should have received a copy of the GNU General Public License
19 * along with FRR; see the file COPYING. If not, write to the Free
20 * Software Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA
21 * 02111-1307, USA.
22 */
23 #ifndef SBUF_H
24 #define SBUF_H
25
26 /*
27 * sbuf provides a simple string buffer. One application where this comes
28 * in handy is the parsing of binary data: If there is an error in the parsing
29 * process due to invalid input data, printing an error message explaining what
30 * went wrong is definitely useful. However, just printing the actual error,
31 * without any information about the previous parsing steps, is usually not very
32 * helpful.
33 * Using sbuf, the parser can log the whole parsing process into a buffer using
34 * a printf like API. When an error ocurrs, all the information about previous
35 * parsing steps is there in the log, without any need for backtracking, and can
36 * be used to give a detailed and useful error description.
37 * When parsing completes successfully without any error, the log can just be
38 * discarded unless debugging is turned on, to not spam the log.
39 *
40 * For the described usecase, the code would look something like this:
41 *
42 * int sbuf_example(..., char **parser_log)
43 * {
44 * struct sbuf logbuf;
45 *
46 * sbuf_init(&logbuf, NULL, 0);
47 * sbuf_push(&logbuf, 0, "Starting parser\n");
48 *
49 * int rv = do_parse(&logbuf, ...);
50 *
51 * *parser_log = sbuf_buf(&logbuf);
52 *
53 * return 1;
54 * }
55 *
56 * In this case, sbuf_example uses a string buffer with undefined size, which
57 * will
58 * be allocated on the heap by sbuf. The caller of sbuf_example is expected to
59 * free
60 * the string returned in parser_log.
61 */
62
63 struct sbuf {
64 bool fixed;
65 char *buf;
66 size_t size;
67 size_t pos;
68 int indent;
69 };
70
71 void sbuf_init(struct sbuf *dest, char *buf, size_t size);
72 void sbuf_reset(struct sbuf *buf);
73 const char *sbuf_buf(struct sbuf *buf);
74 void sbuf_free(struct sbuf *buf);
75 #include "lib/log.h"
76 void sbuf_push(struct sbuf *buf, int indent, const char *format, ...)
77 PRINTF_ATTRIBUTE(3, 4);
78
79 #endif