Idris2/support/refc/buffer.c

93 lines
2.2 KiB
C
Raw Normal View History

#include "buffer.h"
#include "refc_util.h"
2020-05-18 16:51:10 +03:00
#include <string.h>
2022-09-21 13:13:15 +03:00
#include <sys/stat.h>
2020-05-18 16:51:10 +03:00
2022-09-21 13:13:15 +03:00
void *newBuffer(int bytes) {
size_t size = sizeof(Buffer) + bytes * sizeof(uint8_t);
2020-05-18 16:51:10 +03:00
2022-09-21 13:13:15 +03:00
Buffer *buf = malloc(size);
if (buf == NULL) {
return NULL;
}
2020-05-18 16:51:10 +03:00
2022-09-21 13:13:15 +03:00
buf->size = bytes;
memset(buf->data, 0, bytes);
2020-05-18 16:51:10 +03:00
2022-09-21 13:13:15 +03:00
return (void *)buf;
2020-05-18 16:51:10 +03:00
}
2022-09-21 13:13:15 +03:00
static void assert_valid_range(Buffer *buf, int64_t offset, int64_t len) {
IDRIS2_REFC_VERIFY(offset >= 0, "offset (%lld) < 0", (long long)offset);
IDRIS2_REFC_VERIFY(len >= 0, "len (%lld) < 0", (long long)offset);
2022-09-21 13:13:15 +03:00
IDRIS2_REFC_VERIFY(offset + len <= buf->size,
"offset (%lld) + len (%lld) > buf.size (%lld)",
(long long)offset, (long long)len, (long long)buf->size);
}
2022-09-21 13:13:15 +03:00
void copyBuffer(void *from, int from_offset, int len, void *to, int to_offset) {
Buffer *bfrom = from;
Buffer *bto = to;
2020-05-18 16:51:10 +03:00
2022-09-21 13:13:15 +03:00
assert_valid_range(bfrom, from_offset, len);
assert_valid_range(bto, to_offset, len);
2022-09-21 13:13:15 +03:00
memcpy(bto->data + to_offset, bfrom->data + from_offset, len);
2020-05-18 16:51:10 +03:00
}
2022-09-21 13:13:15 +03:00
int getBufferSize(void *buffer) { return ((Buffer *)buffer)->size; }
2020-05-18 16:51:10 +03:00
void setBufferUIntLE(void *b, int loc, uint64_t val, size_t len) {
assert_valid_range((Buffer *)b, loc, len);
while (len--) {
((Buffer *)b)->data[loc++] = (uint8_t)val;
val >>= 8;
}
2020-05-18 16:51:10 +03:00
}
uint64_t getBufferUIntLE(void *b, int loc, size_t len) {
assert_valid_range((Buffer *)b, loc, len);
uint64_t r = 0;
loc += len;
while (len--) {
r <<= 8;
r += (uint8_t)(((Buffer *)b)->data[--loc]);
}
return r;
2020-05-18 16:51:10 +03:00
}
2022-09-21 13:13:15 +03:00
void setBufferDouble(void *buffer, int loc, double val) {
union {
double d;
uint64_t i;
} tmp;
tmp.d = val;
setBufferUIntLE(buffer, loc, tmp.i, 8);
2020-05-18 16:51:10 +03:00
}
2022-09-21 13:13:15 +03:00
void setBufferString(void *buffer, int loc, char *str) {
Buffer *b = buffer;
size_t len = strlen(str);
assert_valid_range(b, loc, len);
memcpy((b->data) + loc, str, len);
2020-05-18 16:51:10 +03:00
}
2022-09-21 13:13:15 +03:00
double getBufferDouble(void *buffer, int loc) {
union {
double d;
uint64_t i;
} tmp;
tmp.i = getBufferUIntLE(buffer, loc, 8);
return tmp.d;
2020-05-18 16:51:10 +03:00
}
2022-09-21 13:13:15 +03:00
char *getBufferString(void *buffer, int loc, int len) {
Buffer *b = buffer;
assert_valid_range(b, loc, len);
char *s = (char *)(b->data + loc);
char *rs = malloc(len + 1);
strncpy(rs, s, len);
rs[len] = '\0';
return rs;
2020-05-18 16:51:10 +03:00
}