1 /*
2  * Copyright (c) 2001 X-Way Rights BV
3  *
4  * This library is free software; you can redistribute it and/or
5  * modify it under the terms of the GNU Lesser General Public
6  * License as published by the Free Software Foundation; either
7  * version 2.1 of the License, or (at your option) any later version.
8  *
9  * This library is distributed in the hope that it will be useful,
10  * but WITHOUT ANY WARRANTY; without even the implied warranty of
11  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
12  * Lesser General Public License for more details.
13  *
14  * You should have received a copy of the GNU Lesser General Public
15  * License along with this library; if not, write to the Free Software
16  * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
17  *
18  */
19 
20 /*!\file memchunk.c
21  * \author Bob Deblier <bob.deblier@telenet.be>
22  */
23 
24 #define BEECRYPT_DLL_EXPORT
25 
26 #if HAVE_CONFIG_H
27 # include "config.h"
28 #endif
29 
30 #include "beecrypt/memchunk.h"
31 
memchunkAlloc(size_t size)32 memchunk* memchunkAlloc(size_t size)
33 {
34 	memchunk* tmp = (memchunk*) calloc(1, sizeof(memchunk));
35 
36 	if (tmp)
37 	{
38 		tmp->size = size;
39 		tmp->data = (byte*) malloc(size);
40 
41 		if (tmp->data == (byte*) 0)
42 		{
43 			free(tmp);
44 			tmp = 0;
45 		}
46 	}
47 
48 	return tmp;
49 }
50 
memchunkInit(memchunk * m)51 void memchunkInit(memchunk* m)
52 {
53 	m->data = (byte*) 0;
54 	m->size = 0;
55 }
56 
memchunkWipe(memchunk * m)57 void memchunkWipe(memchunk* m)
58 {
59 	if (m)
60 	{
61 		if (m->data)
62 		{
63 			memset(m->data, 0, m->size);
64 		}
65 	}
66 }
67 
memchunkFree(memchunk * m)68 void memchunkFree(memchunk* m)
69 {
70 	if (m)
71 	{
72 		if (m->data)
73 		{
74 			free(m->data);
75 
76 			m->size = 0;
77 			m->data = (byte*) 0;
78 		}
79 		free(m);
80 	}
81 }
82 
memchunkResize(memchunk * m,size_t size)83 memchunk* memchunkResize(memchunk* m, size_t size)
84 {
85 	if (m)
86 	{
87 		if (m->data)
88 			m->data = (byte*) realloc(m->data, size);
89 		else
90 			m->data = (byte*) malloc(size);
91 
92 		if (m->data == (byte*) 0)
93 		{
94 			free(m);
95 			m = (memchunk*) 0;
96 		}
97 		else
98 			m->size = size;
99 	}
100 
101 	return m;
102 }
103 
memchunkClone(const memchunk * m)104 memchunk* memchunkClone(const memchunk* m)
105 {
106 	if (m)
107 	{
108 		memchunk* tmp = memchunkAlloc(m->size);
109 
110 		if (tmp)
111 			memcpy(tmp->data, m->data, m->size);
112 
113 		return tmp;
114 	}
115 
116 	return (memchunk*) 0;
117 }
118