-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcbuf.c
138 lines (114 loc) · 2.22 KB
/
cbuf.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
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
#include "cbuf.h"
#include <assert.h>
#include <stdio.h>
#include <stdlib.h>
#include <sys/mman.h>
#include <unistd.h>
signed
cbuf_init(cbuf_t *self, unsigned long order)
{
assert(order >= 12); // At least 4096b buffer
char path[] = "/dev/shm/cbuf-XXXXXX";
int fd;
if ((fd = mkstemp(path)) == -1) {
perror("mkstemp");
goto fail;
}
if (unlink(path) == -1) {
perror("unlink");
goto fail;
}
self->size = 1ULL << order;
self->write_offset = 0;
self->read_offset = 0;
if ((ftruncate(fd, self->size)) == -1) {
perror("ftruncate");
goto fail;
}
// mmap anonymous (twice the desired size)
self->addr = mmap(NULL, self->size << 1,
PROT_NONE, MAP_ANON | MAP_PRIVATE, -1, 0);
if (self->addr == MAP_FAILED) {
perror("mmap");
goto fail;
}
// mmap first
char *addr;
addr = mmap(self->addr, self->size,
PROT_READ | PROT_WRITE, MAP_FIXED | MAP_SHARED, fd, 0);
if (self->addr == MAP_FAILED) {
perror("mmap");
goto fail;
}
if (addr != self->addr) {
fprintf(stderr, "not contiguous\n");
goto fail;
}
// mmap second
addr = mmap(self->addr + self->size, self->size,
PROT_READ | PROT_WRITE, MAP_FIXED | MAP_SHARED, fd, 0);
if (self->addr == MAP_FAILED) {
perror("mmap");
goto fail;
}
if (addr != self->addr + self->size) {
fprintf(stderr, "not contiguous\n");
goto fail;
}
if (close(fd) == -1) {
perror("close");
goto fail;
}
return 0;
fail:
return -1;
}
signed
cbuf_destroy(cbuf_t *self)
{
if (munmap(self->addr, self->size << 1) == -1) {
perror("munmap");
return -1;
}
return 0;
}
char *
cbuf_write_addr(cbuf_t *self)
{
return self->addr + self->write_offset;
}
void
cbuf_write_advance(cbuf_t *self, size_t size)
{
self->write_offset += size;
}
char *
cbuf_read_addr(cbuf_t *self)
{
return self->addr + self->read_offset;
}
void
cbuf_read_advance(cbuf_t *self, size_t size)
{
self->read_offset += size;
if (self->read_offset >= self->size) {
self->read_offset -= self->size;
self->write_offset -= self->size;
}
}
size_t
cbuf_count(cbuf_t *self)
{
return self->write_offset - self->read_offset;
}
size_t
cbuf_count_free(cbuf_t *self)
{
return self->size - cbuf_count(self);
}
void
cbuf_clear(cbuf_t *self)
{
self->write_offset = 0;
self->read_offset = 0;
}