Also deserialize unsigned integers

This commit is contained in:
Vftdan 2024-10-24 10:27:45 +02:00
parent 67fb39b808
commit fe2590240b
1 changed files with 48 additions and 15 deletions

View File

@ -19,6 +19,28 @@ byteser_bytes_lcrop(AbstractOutputByteStream *stream, ByteSlice bytes, size_t si
}
}
HEADER_FN bool
bytedeser_bytes_lcrop(AbstractInputByteStream *stream, MutByteSlice *buf_slc_ptr, size_t size)
{
int8_t dummy;
MutByteSlice dummy_slc = VAR_BYTE_SLICE_MUT(dummy);
while (size > buf_slc_ptr->length) {
byte_stream_read_to(stream, dummy_slc);
--size;
}
byte_slice_advance_inplace(&buf_slc_ptr->as_ByteSlice, buf_slc_ptr->length - size);
if (!buf_slc_ptr->data || !buf_slc_ptr->length) {
return true; // Successfully read 0 bytes
}
if (byte_stream_is_end(stream)) {
return false; // Failed to read bytes
}
if (byte_stream_read_to(stream, *buf_slc_ptr) != buf_slc_ptr->length) {
return false; // Failed to read enough bytes
}
return true;
}
HEADER_FN void
byteser_net_integral_signed(AbstractOutputByteStream *stream, intmax_t value, size_t size)
{
@ -41,28 +63,17 @@ byteser_net_integral_unsigned(AbstractOutputByteStream *stream, uintmax_t value,
byteser_bytes_lcrop(stream, VAR_BYTE_SLICE_CONST(buf), size, 0);
}
// TODO finish deserialization
HEADER_FN bool
bytedeser_net_integral_signed(AbstractInputByteStream *stream, intmax_t *value_ptr, size_t size)
{
*value_ptr = 0;
int8_t buf[sizeof(*value_ptr)] = {0,};
int8_t dummy;
MutByteSlice dummy_slc = VAR_BYTE_SLICE_MUT(dummy);
while (size > sizeof(buf)) {
byte_stream_read_to(stream, dummy_slc);
--size;
}
MutByteSlice buf_slc = VAR_BYTE_SLICE_MUT(buf);
byte_slice_advance_inplace(&buf_slc.as_ByteSlice, buf_slc.length - size);
if (!bytedeser_bytes_lcrop(stream, &buf_slc, size)) {
return false;
}
if (!buf_slc.data || !buf_slc.length) {
return true; // Successfully read 0 bytes
}
if (byte_stream_is_end(stream)) {
return false; // Failed to read bytes
}
if (byte_stream_read_to(stream, buf_slc) != buf_slc.length) {
return false; // Failed to read enough bytes
return true;
}
assert(buf_slc.data - (uint8_t*) buf < (ssize_t) sizeof(buf));
@ -80,4 +91,26 @@ bytedeser_net_integral_signed(AbstractInputByteStream *stream, intmax_t *value_p
return true;
}
HEADER_FN bool
bytedeser_net_integral_unsigned(AbstractInputByteStream *stream, uintmax_t *value_ptr, size_t size)
{
*value_ptr = 0;
uint8_t buf[sizeof(*value_ptr)] = {0,};
MutByteSlice buf_slc = VAR_BYTE_SLICE_MUT(buf);
if (!bytedeser_bytes_lcrop(stream, &buf_slc, size)) {
return false;
}
if (!buf_slc.data || !buf_slc.length) {
return true;
}
intmax_t value = 0;
for (size_t i = 0; i < sizeof(buf); ++i) {
value <<= 8;
value |= 0xFF & (intmax_t) buf[i];
}
*value_ptr = value;
return true;
}
#endif /* end of include guard: COMMON_UTIL_BYTE_SERDES_H_ */