-
Notifications
You must be signed in to change notification settings - Fork 5
/
simple_mem_buffer.c
55 lines (49 loc) · 1.38 KB
/
simple_mem_buffer.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
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "huffman.h"
#include "simple_mem_buffer.h"
int mem_eof(struct buffer_ops *handle) {
struct mem_region *pmr = handle->data;
if (pmr->end == pmr->cur)
return 1;
else
return 0;
}
int mem_read(struct buffer_ops *handle, void *buffer, size_t len) {
struct mem_region *pmr = handle->data;
if (len + pmr->cur >= pmr->end)
len = pmr->end - pmr->cur;
memcpy(buffer, pmr->data + pmr->cur, len);
pmr->cur += len;
return len;
}
int mem_write(struct buffer_ops *handle, void *data , size_t len) {
struct mem_region *pmr = handle->data;
if (len + pmr->cur >= pmr->end)
len = pmr->end - pmr->cur;
memcpy(pmr->data + pmr->cur, data, len);
pmr->cur += len;
return len;
}
int mem_rewind(struct buffer_ops *handle) {
struct mem_region *pmr = handle->data;
pmr->cur = 0;
return 0;
}
struct buffer_ops * create_mem_buffer_ops(void *buffer, size_t len) {
struct buffer_ops *ops = malloc(sizeof(struct buffer_ops));
struct mem_region *pmr = malloc(sizeof(struct mem_region));
pmr->data = buffer;
pmr->cur = 0;
pmr->end = len;
ops->data = pmr;
ops->eof = mem_eof;
ops->read = mem_read;
ops->write = mem_write;
ops->rewind = mem_rewind;
return ops;
}
void desotry_mem_buffer_ops(struct buffer_ops *ops) {
free(ops);
}