Repository navigation
Expand file tree
/
Copy pathStringBuf2.c
More file actions
82 lines (72 loc) · 2.58 KB
/
Copy pathStringBuf2.c
File metadata and controls
82 lines (72 loc) · 2.58 KB
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
/*
* 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: Moved undo function to this file.
CJB: 07-Apr-25: Dogfooding the _Optional qualifier.
*/
/* ISO library headers */
#include <stdbool.h>
#include <stddef.h>
/* Local headers */
#include "Internal/CBUtilMisc.h"
#include "StringBuff.h"
void stringbuffer_undo(StringBuffer *const buffer)
{
assert(buffer != NULL);
DEBUGF("StringBuff: Undoing last operation on buffer %p ('%s')\n",
(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);
assert(buffer->buffer[buffer->string_len] == '\0');
}
if (buffer->undo_len < buffer->string_len)
{
/* Undo append by storing a null terminator at the old place. */
DEBUGF("StringBuff: Undoing append (truncating to %zu)\n",
buffer->undo_len);
if (buffer->buffer)
{
buffer->buffer[buffer->undo_len] = '\0';
}
}
else if (buffer->undo_len > buffer->string_len)
{
/* Undo truncation by reinstating the character previously overwritten
by a null terminator. Pre-truncation terminator must be intact. */
DEBUGF("StringBuff: Undoing truncation (extending to %zu)\n",
buffer->undo_len);
assert(buffer->undo_len < buffer->buffer_size);
if (buffer->buffer)
{
assert(buffer->buffer[buffer->undo_len] == '\0');
buffer->buffer[buffer->string_len] = buffer->undo_char;
}
}
else
{
DEBUGF("StringBuff: Nothing to undo (length %zu)\n", buffer->undo_len);
}
buffer->string_len = buffer->undo_len;
DEBUGF("StringBuff: buffer now contains '%s'\n",
STRING_OR_NULL(buffer->buffer));
}