summaryrefslogtreecommitdiff
path: root/buf.c
blob: 440ac7682b20f2ac7ca017cec7cb5681833ac876 (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
#include "buf.h"

buf_t* buf_init()
{
	buf_t *ret = NULL;

	ret = malloc( sizeof(buf_t) );
	memset(ret, 0, sizeof(buf_t));

	return ret;
}


int buf_size( buf_t *bf, int size )
{
	if (bf->buf != NULL)
	{
		printf("Buffer should be empty\n");
		return -1;
	}

	bf->buf = malloc( size );
	bf->size = size;
	bf->buf_size = size;

	return 0;
}


int buf_used_size( buf_t *bf, int size )
{
	if ( size > bf->buf_size )
	{
		printf("Cannot set buffer size more then buffer itself\n");
		return -1;
	}

	if ( size < 0)
	{
		printf("Cannot set buffer less then zero\n");
		return -1;
	}

	bf->size = size;

	return 0;
}


int buf_resize( buf_t *bf, int size )
{
	uint8_t *n=NULL;

	if ( size < 1)
	{
		printf("Cannot set buffer size less then 1\n");
		return -1;
	}

	n = realloc( bf->buf, size ); //resized data is not nullified at the end?
	if ( n == NULL )
	{
		printf("Buffer realloc failed\n");
		return -1;
	}

	if ( size > bf->buf_size )
	{
		memset(bf->buf+bf->buf_size-1, 0, size-(bf->buf_size)); //hope its correct
	}

	bf->buf_size = size;
	bf->buf = n;
	if (bf->size > bf->buf_size)
	{
		bf->size = bf->buf_size;
	}

	return 0;
}


int buf_zero( buf_t *bf )
{
	if ( bf->buf == NULL )
		return -1;
	
	memset( bf->buf, 0, bf->buf_size );

	return 0;
}


void buf_free( buf_t *bf )
{
	if ( bf == NULL )
		return;

	if ( bf->buf != NULL )
	{
		free( bf->buf );
		bf->buf = NULL;
	}

	free( bf );
	bf = NULL;
}