Skip to content

Commit 23df53e

Browse files
committed
Fix a bug where valid data was invalidated in cases where the write would end exactly at the end of the buffer
1 parent 1d95623 commit 23df53e

File tree

2 files changed

+32
-4
lines changed

2 files changed

+32
-4
lines changed

lfbb/src/lfbb.c

Lines changed: 6 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -115,11 +115,8 @@ void LFBB_WriteRelease(LFBB_Inst_Type *inst, const size_t written) {
115115
w = 0U;
116116
}
117117

118-
/* Increment the write index and wrap to 0 if needed */
118+
/* Increment the write index */
119119
w += written;
120-
if (w == inst->size) {
121-
w = 0U;
122-
}
123120

124121
/* If we wrote over invalidated parts of the buffer move the invalidate
125122
* index
@@ -128,6 +125,11 @@ void LFBB_WriteRelease(LFBB_Inst_Type *inst, const size_t written) {
128125
i = w;
129126
}
130127

128+
/* Wrap the write index if we reached the end of the buffer */
129+
if (w == inst->size) {
130+
w = 0U;
131+
}
132+
131133
/* Store the indexes with adequate memory ordering */
132134
atomic_store_explicit(&inst->i, i, memory_order_release);
133135
atomic_store_explicit(&inst->w, w, memory_order_release);

tests/tests.cpp

Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -194,3 +194,29 @@ TEST_CASE("Interleaved write and read without enough space",
194194
write_location = LFBB_WriteAcquire(&lfbb, sizeof(test_data2));
195195
REQUIRE(write_location == nullptr);
196196
}
197+
198+
TEST_CASE("Write ends exactly at the end of the buffer",
199+
"[write_ends_at_buffer_end]") {
200+
const size_t write_size = 8;
201+
uint8_t buf[write_size * 2];
202+
203+
LFBB_Inst_Type lfbb;
204+
LFBB_Init(&lfbb, buf, sizeof(buf));
205+
206+
/* 1. Write the first half */
207+
LFBB_WriteAcquire(&lfbb, write_size);
208+
LFBB_WriteRelease(&lfbb, write_size);
209+
210+
/* 2. Read the first half */
211+
size_t read_available;
212+
LFBB_ReadAcquire(&lfbb, &read_available);
213+
LFBB_ReadRelease(&lfbb, write_size);
214+
215+
/* 3. Write the second half */
216+
uint8_t *second_half_write = LFBB_WriteAcquire(&lfbb, write_size);
217+
LFBB_WriteRelease(&lfbb, write_size);
218+
219+
/* 4. Read the second half */
220+
uint8_t *second_half_read = LFBB_ReadAcquire(&lfbb, &read_available);
221+
REQUIRE(second_half_read == second_half_write);
222+
}

0 commit comments

Comments
 (0)