Skip to content

Commit 8375a00

Browse files
nshylocker
authored andcommitted
ibuf: add ibuf_truncate method
It is used to discard data written after the given position. Part of tarantool/tarantool#7939
1 parent af26f3f commit 8375a00

File tree

3 files changed

+57
-0
lines changed

3 files changed

+57
-0
lines changed

include/small/ibuf.h

+12
Original file line numberDiff line numberDiff line change
@@ -151,6 +151,18 @@ ibuf_alloc(struct ibuf *ibuf, size_t size)
151151
void
152152
ibuf_shrink(struct ibuf *ibuf);
153153

154+
/**
155+
* Discard data written after position. Use ibuf_used to get position.
156+
* Note that you should not update read position in between. It is safe
157+
* to use if buffer is reallocated in between.
158+
*/
159+
static inline void
160+
ibuf_truncate(struct ibuf *ibuf, size_t used)
161+
{
162+
assert(used <= ibuf_used(ibuf));
163+
ibuf->wpos = ibuf->rpos + used;
164+
}
165+
154166
static inline void *
155167
ibuf_reserve_cb(void *ctx, size_t *size)
156168
{

test/ibuf.c

+43
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,7 @@
22
#include <small/ibuf.h>
33
#include <small/slab_cache.h>
44
#include <stdio.h>
5+
#include <string.h>
56
#include "unit.h"
67

78
struct slab_cache cache;
@@ -95,6 +96,47 @@ test_ibuf_shrink(void)
9596
footer();
9697
}
9798

99+
static void
100+
test_ibuf_truncate()
101+
{
102+
header();
103+
104+
char *ptr;
105+
const char *hello = "Hello Hello";
106+
const char *goodbye = "Goodbye";
107+
struct ibuf ibuf;
108+
109+
ibuf_create(&ibuf, &cache, 16 * 1024);
110+
ibuf_alloc(&ibuf, 10);
111+
ibuf.rpos += 10;
112+
ptr = ibuf_alloc(&ibuf, strlen(hello) + 1);
113+
fail_unless(ptr != NULL);
114+
strcpy(ptr, hello);
115+
size_t svp = ibuf_used(&ibuf);
116+
117+
/*
118+
* Test when there is NO reallocation in between used/truncate.
119+
*/
120+
ptr = ibuf_alloc(&ibuf, 100);
121+
fail_unless(ptr != NULL);
122+
strcpy(ptr, goodbye);
123+
ibuf_truncate(&ibuf, svp);
124+
fail_unless(ibuf_used(&ibuf) == svp);
125+
fail_unless(strcmp(ibuf.rpos, hello) == 0);
126+
127+
/*
128+
* Test when there IS reallocation in between used/truncate.
129+
*/
130+
ptr = ibuf_alloc(&ibuf, 32 * 1024);
131+
fail_unless(ptr != NULL);
132+
strcpy(ptr, goodbye);
133+
ibuf_truncate(&ibuf, svp);
134+
fail_unless(ibuf_used(&ibuf) == svp);
135+
fail_unless(strcmp(ibuf.rpos, hello) == 0);
136+
137+
footer();
138+
}
139+
98140
int main()
99141
{
100142
quota_init(&quota, UINT_MAX);
@@ -104,6 +146,7 @@ int main()
104146

105147
test_ibuf_basic();
106148
test_ibuf_shrink();
149+
test_ibuf_truncate();
107150

108151
slab_cache_destroy(&cache);
109152
}

test/ibuf.result

+2
Original file line numberDiff line numberDiff line change
@@ -2,3 +2,5 @@
22
*** test_ibuf_basic: done ***
33
*** test_ibuf_shrink ***
44
*** test_ibuf_shrink: done ***
5+
*** test_ibuf_truncate ***
6+
*** test_ibuf_truncate: done ***

0 commit comments

Comments
 (0)