summaryrefslogtreecommitdiff
path: root/buf.c
blob: ac7e83ad4f4d5775b1468207651f10b72f8b1dda (plain) (blame)
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
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
#include "buf.h"


bbuf* bbuf_new(int size)
{
	bbuf *ret = NULL;
	ret = malloc(sizeof(bbuf));
	if (!ret)
	{
		return NULL;
	}
	ret->buf = malloc(size);
	if (!ret->buf)
	{
		free(ret);
		return NULL;
	}
	ret->buf_size = size;
	ret->size = 0;
	return ret;
}

//set buffer value
int bbuf_set(bbuf *a, char *val, int size)
{
	if (!a)
		return -1;

	if (!a->buf)
		return -1;

	if (size<0)
		return -1;

	if (size > a->buf_size)
	{
		a->size = a->buf_size;
	} else
	{
		a->size = size;
	}
	memcpy(a->buf, val, a->size);

	return a->size;
}


//get copy of buffer
bbuf *bbuf_copy(bbuf *buf)
{
	bbuf *ret = NULL;

	if (!buf)
	{
		return NULL;
	}

	ret = malloc(sizeof(bbuf));
	memcpy(ret, buf, sizeof(bbuf));
	ret->buf = malloc(buf->buf_size);
	if (!ret->buf)
	{
		free(ret);
		return NULL;
	}
	memcpy(ret->buf, buf->buf, buf->buf_size);
	ret->size = buf->size;
	ret->buf_size = buf->buf_size;

	return ret;
}


//get buffer from buffer, mapped pointer, plz dont modify
int bbuf_get(bbuf *buf, char **val, int *size)
{
	if (!buf)
	{
		return -1;
	}

	if (!val)
	{
		return -1;
	}

	*size = buf->size;
	*val = buf->buf;

	return 0;
}


//resize buffer
int bbuf_realloc(bbuf *buf, int size)
{
	int ret = -1;
	char *ptr=NULL;
	if (!buf)
		return -1;
	if (size < 0)
		return -1;
	if (buf->buf_size == size)
		return size;

	ret = buf->buf_size;
	ptr = realloc(buf->buf, size);
	if (ptr != NULL)
	{
		buf->buf = ptr;
		ret = size;
	}

	return ret;
}


//increase buffer for size
int bbuf_inc(bbuf *a, char *b, int size)
{
	printf("Not implemented\n");
	return -1;
}


//decrease buffer for size
int bbuf_dec(bbuf *a, char *b, int size)
{
	printf("Not implemented\n");
	return -1;
}


//free buffer
void bbuf_free(bbuf *buf)
{
	if (buf == NULL)
	{
		return;
	}
	if (buf->buf != NULL)
	{
		memset(buf->buf, 0, buf->buf_size);
		free(buf->buf);
		buf->buf = NULL;
		memset(buf, 0, sizeof(bbuf));
		free(buf);
	}
}

int bbuf_concat(bbuf *a, bbuf *b)
{
	printf("Not implemented\n");
	return -1;
}