fixed varint.h using nonexistant type, buf.c had a memory bug

This commit is contained in:
2026-11-10 20:57:13 +01:00
parent 01ec943234
commit e5f8d4c68f
2 changed files with 16 additions and 10 deletions
+15 -9
View File
@@ -1,18 +1,23 @@
#include "buf.h"
#include "intutils.h"
#include <string.h>
// Internal claim functions to avoid code duplication in the cursor functions
// Claim n bytes from the cursor, returns nullptr (+ sets failed) on overrun.
// Returns nullptr on n == 0 without failing (nothing to point at)
static const uint8_t* rcur_claim(bravais_rcur_t* cur, size_t n) {
if (cur->failed || n > cur->len - cur->pos) {
cur->failed = true;
return nullptr;
}
if (cur->base == nullptr) {
if (n == 0) {
return nullptr;
}
const uint8_t* start = cur->base + cur->pos;
const uint8_t* start = cur->buf + cur->pos;
cur->pos += n;
return start;
@@ -24,11 +29,11 @@ static uint8_t* wcur_claim(bravais_wcur_t* cur, size_t n) {
return nullptr;
}
if (cur->base == nullptr) {
if (n == 0) {
return nullptr;
}
uint8_t* start = cur->base + cur->pos;
uint8_t* start = cur->buf + cur->pos;
cur->pos += n;
return start;
@@ -38,7 +43,7 @@ void bravais_rcur_init(bravais_rcur_t* cur, const uint8_t* buf, size_t len) {
cur->buf = buf;
cur->len = len;
cur->pos = 0;
cur->failed = false;
cur->failed = (buf == nullptr && len != 0);
}
uint8_t bravais_rcur_u8(bravais_rcur_t* cur) {
@@ -68,8 +73,9 @@ uint32_t bravais_rcur_u32(bravais_rcur_t* cur) {
return 0;
}
// Assemble from bytes in big-endian order
uint32_t val = (uint32_t)((ptr[0] << 24) | (ptr[1] << 16) | (ptr[2] << 8) | ptr[3]);
// Assemble from bytes in big-endian order - widen before shifting
uint32_t val = ((uint32_t)ptr[0] << 24) | ((uint32_t)ptr[1] << 16) | ((uint32_t)ptr[2] << 8) | ((uint32_t)ptr[3]);
return val;
}
@@ -94,7 +100,7 @@ uint64_t bravais_rcur_u64(bravais_rcur_t* cur) {
}
void bravais_rcur_bytes(bravais_rcur_t* cur, uint8_t* outBuf, size_t len) {
if (len <= 0) { return; }
if (len == 0) { return; }
const uint8_t* ptr = rcur_claim(cur, len);
if (ptr == nullptr) {
@@ -129,7 +135,7 @@ void bravais_wcur_init(bravais_wcur_t* cur, uint8_t* buf, size_t len) {
cur->buf = buf;
cur->len = len;
cur->pos = 0;
cur->failed = false;
cur->failed = (buf == nullptr && len != 0);
}
void bravais_wcur_u8(bravais_wcur_t* cur, uint8_t val) {
+1 -1
View File
@@ -22,7 +22,7 @@
// Bytes needed to encode *val*, or 0 if *val* is too large to encode (>BRAVAIS_VARINT_MAX).
size_t bravais_varint_len(uint64_t val);
uint64_t bravais_rcur_varint(bravais_rcur_buf_t* buf);
uint64_t bravais_rcur_varint(bravais_rcur_t* buf);
// Always uses the shortest encoding. Fails the cursor if value is too large.
void bravais_wcur_varint(bravais_wcur_t* cur, uint64_t val);