2 * Copyright (C) 2002 Cisco Systems, Inc.
3 * maintained by linux-iscsi-devel@lists.sourceforge.net
5 * This program is free software; you can redistribute it and/or modify
6 * it under the terms of the GNU General Public License as published
7 * by the Free Software Foundation; either version 2 of the License, or
8 * (at your option) any later version.
10 * This program is distributed in the hope that it will be useful, but
11 * WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
13 * General Public License for more details.
15 * See the file COPYING included with this distribution for more details.
24 #include <sys/param.h>
29 int str_init_buffer(struct str_buffer
*s
, size_t initial_allocation
)
32 memset(s
, 0, sizeof (*s
));
34 if (initial_allocation
) {
35 s
->buffer
= malloc(initial_allocation
);
37 s
->allocated_length
= initial_allocation
;
38 memset(s
->buffer
, 0, initial_allocation
);
48 struct str_buffer
*str_alloc_buffer(size_t initial_allocation
)
50 struct str_buffer
*s
= calloc(1, sizeof (*s
));
53 str_init_buffer(s
, initial_allocation
);
58 void str_free_buffer(struct str_buffer
*s
)
65 s
->allocated_length
= 0;
70 int str_enlarge_data(struct str_buffer
*s
, int length
)
75 s
->data_length
+= length
;
76 if (s
->data_length
> s
->allocated_length
) {
77 log_debug(7, "enlarge buffer from %lu to %lu\n",
78 s
->allocated_length
, s
->data_length
);
79 new_buf
= realloc(s
->buffer
, s
->data_length
);
82 log_error("enlarged buffer %p to %d data "
83 "bytes, with only %d bytes of buffer "
84 "space", s
, (int)s
->data_length
,
85 (int)s
->allocated_length
);
89 memset(s
->buffer
+ s
->allocated_length
, 0,
90 s
->data_length
- s
->allocated_length
);
91 s
->allocated_length
= s
->data_length
;
98 void str_remove_initial(struct str_buffer
*s
, int length
)
100 char *remaining
= s
->buffer
+ length
;
101 int amount
= s
->data_length
- length
;
104 memmove(s
->buffer
, remaining
, amount
);
105 s
->data_length
= amount
;
106 s
->buffer
[amount
] = '\0';
110 /* truncate the data length down */
111 void str_truncate_buffer(struct str_buffer
*s
, size_t length
)
116 if (length
<= s
->data_length
) {
117 s
->data_length
= length
;
118 s
->buffer
[s
->data_length
] = '\0';
119 } else if (length
<= s
->allocated_length
) {
120 /* clear the data, and declare the
121 * data length to be larger
123 memset(s
->buffer
+ s
->data_length
, 0,
124 length
- s
->data_length
);
125 s
->data_length
= length
;
128 "couldn't truncate data buffer to length %d, "
130 (int)length
, (int)s
->allocated_length
);
135 char *str_buffer_data(struct str_buffer
*s
)
143 size_t str_data_length(struct str_buffer
* s
)
146 return s
->data_length
;
151 size_t str_unused_length(struct str_buffer
* s
)
154 return s
->allocated_length
- s
->data_length
;