1 /* buf.c - by Alen Stojanov and David van Moolenbroek, taken from procfs */
9 static size_t left
, used
;
12 /*===========================================================================*
14 *===========================================================================*/
15 void buf_init(char *ptr
, size_t len
, off_t start
)
17 /* Initialize the buffer for fresh use. The output is to be stored into
18 * 'ptr' which is BUF_SIZE bytes in size, since that is the size we
19 * requested. Due to the way vsnprintf works, we cannot use the last
20 * byte of this buffer. The first 'start' bytes of the produced output
21 * are to be skipped. After that, a total of 'len' bytes are requested.
26 left
= MIN(len
, BUF_SIZE
- 1);
30 /*===========================================================================*
32 *===========================================================================*/
33 void buf_printf(char *fmt
, ...)
35 /* Add formatted text to the end of the buffer.
43 /* There is no way to estimate how much space the result will take, so
44 * we need to produce the string even when skipping part of the start.
45 * The null terminating character is not part of the result, so room
46 * must be given for it to be stored after completely filling up the
47 * requested part of the buffer.
49 max
= MIN(skip
+ left
+ 1, BUF_SIZE
);
52 len
= vsnprintf(&buf
[used
], max
, fmt
, args
);
55 /* The snprintf family returns the number of bytes that would be stored
56 * if the buffer were large enough, excluding the null terminator.
70 memmove(buf
, &buf
[skip
], len
- skip
);
78 assert((ssize_t
) left
>= 0);
80 if (len
> (ssize_t
) left
)
87 /*===========================================================================*
89 *===========================================================================*/
90 void buf_append(char *data
, size_t len
)
92 /* Add arbitrary data to the end of the buffer.
99 if (skip
>= (ssize_t
) len
) {
113 memcpy(&buf
[used
], data
, len
);
119 /*===========================================================================*
121 *===========================================================================*/
122 ssize_t
buf_result(void)
124 /* Return the resulting number of bytes produced, not counting the
125 * trailing null character in the buffer.