-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathStringBuf3.c
86 lines (74 loc) · 2.6 KB
/
StringBuf3.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
/*
* CBUtilLib: String buffer
* Copyright (C) 2012 Christopher Bazley
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
/* History:
CJB: 24-Sep-23: New function to append a formatted string.
CJB: 07-Apr-25: Dogfooding the _Optional qualifier.
*/
/* ISO library headers */
#include <stdbool.h>
#include <stdint.h>
#include <stdarg.h>
/* Local headers */
#include "StringBuff.h"
#include "Internal/CBUtilMisc.h"
bool stringbuffer_vprintf(StringBuffer *const buffer,
const char *const format, va_list args)
{
bool success = true;
assert(buffer != NULL);
assert(format != NULL);
DEBUG_VERBOSEF("StringBuff: Appending string formatted according to '%s' to buffer %p ('%s')\n",
format, (void *)buffer, STRING_OR_NULL(buffer->buffer));
/* If the string buffer contains the empty string "" then the length
may be zero (no allocated memory) as a special case. */
if (buffer->string_len > 0)
{
assert(buffer->buffer != NULL);
assert(buffer->string_len < buffer->buffer_size);
}
/* Find the length of the tail string (if any was provided). */
va_list args_copy;
va_copy(args_copy, args);
int const extra_chars = vsnprintf(NULL, 0, format, args);
if (extra_chars < 0)
{
return false;
}
/* Allocate space for the number of characters to be appended and a
null terminator. */
size_t min_size = (unsigned)extra_chars + 1;
_Optional char * const free_ptr = stringbuffer_prepare_append(buffer, &min_size);
if (free_ptr != NULL)
{
assert(buffer->buffer != NULL);
/* Copy characters from the tail string to the end of the existing
string. */
int const n = vsnprintf(&*free_ptr, min_size, format, args_copy);
assert(n == extra_chars);
NOT_USED(n);
/* Record the new string length and append a null terminator. */
stringbuffer_finish_append(buffer, (unsigned)extra_chars);
}
else
{
success = false;
}
va_end(args_copy);
return success;
}