/
strbuf.c
115 lines (102 loc) · 2.36 KB
/
strbuf.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
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
/*
* Copyright 2003,2004,2005 Kevin Smathers, All Rights Reserved
*
* This file may be used or modified without the need for a license.
*
* Redistribution of this file in either its original form, or in an
* updated form may be done under the terms of the GNU LIBRARY GENERAL
* PUBLIC LICENSE. If this license is unacceptable to you then you
* may not redistribute this work.
*
* See the file COPYING.LGPL for details.
*/
#include "config.h"
#include "util.h"
#include <string.h>
#ifdef HAVE_STRINGS_H
#include <strings.h>
#endif
#include "strbuf.h"
#ifndef max
#define max(x,y) ((x)>(y)?(x):(y))
#endif
#if WIN32
# define vsnprintf _vsnprintf
#endif
kStringBuffer*
kStringBuffer_create( kStringBuffer* _sb) {
kStringBuffer *sb;
if (_sb) {
sb = _sb;
} else {
sb = btmalloc( sizeof( kStringBuffer));
}
memset( sb, 0, sizeof( kStringBuffer));
return sb;
}
void
kStringBuffer_finit( kStringBuffer* sb) {
if (sb) {
if ( sb->buf)
btfree( sb->buf);
sb->buf = NULL;
sb->bufsize = 0;
sb->cpos = 0;
}
}
int
kStringBuffer_grow( kStringBuffer *sb, int len) {
sb->bufsize += len;
sb->buf = btrealloc( sb->buf, sb->bufsize);
bt_assert(sb->buf);
return 0;
}
void
sbclear( kStringBuffer* sb) {
kStringBuffer_finit( sb);
}
int
sbputc( kStringBuffer *sb, char c) {
if (sb->cpos + 1 >= sb->bufsize) {
kStringBuffer_grow( sb, 1024);
if (!sb->buf) return -1;
}
sb->buf[sb->cpos++] = c;
sb->buf[sb->cpos] = 0;
return 0;
}
int
sbstrcat( kStringBuffer *sb, char *str) {
return sbcat( sb, str, strlen(str));
}
int
sbcat( kStringBuffer *sb, char *str, int len) {
bt_assert( len >= 0);
if (sb->cpos + len >= sb->bufsize) {
kStringBuffer_grow( sb, max( len+1, 1024));
if (!sb->buf) return -1;
}
memcpy(sb->buf + sb->cpos, str, len);
sb->cpos += len;
sb->buf[sb->cpos] = 0;
return 0;
}
int
sbtail( kStringBuffer *sb, int start_char) {
bt_assert( start_char >= 0 && start_char <= sb->cpos);
if (start_char == 0) return 0;
if (start_char < sb->cpos) {
memmove( sb->buf, sb->buf + start_char, sb->cpos - start_char);
}
sb->cpos -= start_char;
sb->buf[sb->cpos] = 0;
return 0;
}
int
sbindex( kStringBuffer *sb, int ch) {
int count=0;
char *s = sb->buf;
while (count < sb->cpos && *s != ch) s++, count++;
if (count < sb->cpos) return count;
return -1;
}