Fills a 'bitstring' containing 'n' bits from 'stream'. * Returns 'SIMPLICITY_ERR_BITSTREAM_EOF' if not enough bits are available. * If successful, '*result' is set to a bitstring with 'n' bits read from 'stream' and 'SIMPLICITY_NO_ERROR' is returned. * * If an error is returned '*result' might be modified. * * Precondition: NULL != result * n <= 2^31 * NULL != s
| 212 | * NULL != stream |
| 213 | */ |
| 214 | simplicity_err simplicity_readBitstring(bitstring* result, size_t n, bitstream* stream) { |
| 215 | static_assert(0x80000000u + 2*(CHAR_BIT - 1) <= SIZE_MAX, "size_t needs to be at least 32-bits"); |
| 216 | simplicity_assert(n <= 0x80000000u); |
| 217 | size_t total_offset = n + stream->offset; |
| 218 | /* |= stream->len * CHAR_BIT < total_offset iff stream->len < (total_offset + (CHAR_BIT - 1)) / CHAR_BIT */ |
| 219 | if (stream->len < (total_offset + (CHAR_BIT - 1)) / CHAR_BIT) return SIMPLICITY_ERR_BITSTREAM_EOF; |
| 220 | /* total_offset <= stream->len * CHAR_BIT */ |
| 221 | *result = (bitstring) |
| 222 | { .arr = stream->arr |
| 223 | , .offset = stream->offset |
| 224 | , .len = n |
| 225 | }; |
| 226 | { |
| 227 | size_t delta = total_offset / CHAR_BIT; |
| 228 | stream->arr += delta; stream->len -= delta; |
| 229 | stream->offset = total_offset % CHAR_BIT; |
| 230 | /* Note that if 0 == stream->len then 0 == stream->offset. */ |
| 231 | } |
| 232 | return SIMPLICITY_NO_ERROR; |
| 233 | } |