-
Notifications
You must be signed in to change notification settings - Fork 0
/
manageBuffer.c
91 lines (82 loc) · 2.15 KB
/
manageBuffer.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
/**
* @Author: Izhar
* @Date: 2017-02-07T14:48:18-05:00
* @Email: [email protected]
* @Filename: pthreadsExample.c
* @Last modified by: Izhar Shaikh
* @Last modified time: 2017-02-08T03:22:45-05:00
*/
#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
#include "debugMacros.h"
#include "calenderFilter.h"
/* creates a new buffer and returns the handle */
circularBuffer_t *createBuffer(int capacity)
{
// Create new buffer
circularBuffer_t *newBuffer = (circularBuffer_t *) calloc(1, sizeof(circularBuffer_t));
if(newBuffer == NULL){
dbg_info("Failed to create new buffer!\n");
return NULL;
}
newBuffer->in = 0;
newBuffer->out = 0;
newBuffer->capacity = capacity;
// create new handle for items
char **itemHandle = (char **) calloc(capacity, sizeof(char *));
if(itemHandle == NULL){
dbg_info("Failed to create new elements handle!\n");
free(newBuffer);
return NULL;
}
newBuffer->items = itemHandle;
// create spaces for items
for(int i=0; i < capacity; i++)
{
newBuffer->items[i] = (char *) calloc(BUFFERSIZE, sizeof(char));
if(newBuffer->items[i] == NULL)
{
dbg_trace("Failed to allocate memory for item %d\n", i);
while(i > 0)
{
--i;
free(newBuffer->items[i]);
}
return NULL;
}
}
return newBuffer;
}
/* destroys the allocated buffer */
void destroyBuffer(circularBuffer_t **bufferToDestroy)
{
circularBuffer_t *buffer = *bufferToDestroy;
int capacity = buffer->capacity;
if(buffer == NULL){
dbg_info("Buffer already destroyed!");
return;
}
// Free the up the items first
while(buffer->capacity)
{
--buffer->capacity;
if(NULL != buffer->items[buffer->capacity])
{
free(buffer->items[buffer->capacity]);
buffer->items[buffer->capacity] = NULL;
}
}
// Free up the itemsHandle now
if(NULL != buffer->items){
free(buffer->items);
buffer->items = NULL;
}
// Free up the buffer handle now
if(NULL != buffer){
free(buffer);
buffer = NULL;
}
*bufferToDestroy = NULL; // Update caller handle of the buffer
dbg_trace("Destroyed buffer with capacity of %d.\n", capacity);
}