Fetches up to 31 bits from 'stream' as the 'n' least significant bits of return value. * The 'n' bits are set from the MSB to the LSB. * Returns 'SIMPLICITY_ERR_BITSTREAM_EOF' if not enough bits are available. * * Precondition: 0 <= n < 32 * NULL != stream */
| 31 | * NULL != stream |
| 32 | */ |
| 33 | int32_t simplicity_readNBits(int n, bitstream* stream) { |
| 34 | simplicity_assert(0 <= n && n < 32); |
| 35 | |
| 36 | uint32_t result = 0; |
| 37 | while (CHAR_BIT <= stream->offset + n) { |
| 38 | if (!stream->len) return SIMPLICITY_ERR_BITSTREAM_EOF; |
| 39 | n -= CHAR_BIT - stream->offset; |
| 40 | result |= (uint32_t)(*stream->arr & (UCHAR_MAX >> stream->offset)) << n; |
| 41 | stream->arr++; stream->len--; stream->offset = 0; |
| 42 | } |
| 43 | /* stream->offset + n < CHAR_BIT */ |
| 44 | if (n) { |
| 45 | if (!stream->len) return SIMPLICITY_ERR_BITSTREAM_EOF; |
| 46 | stream->offset += (unsigned char)n; |
| 47 | result |= (*stream->arr >> (CHAR_BIT - stream->offset)) & ((UCHAR_MAX >> (CHAR_BIT - n))); |
| 48 | } |
| 49 | return (int32_t)result; |
| 50 | } |
| 51 | /* Decode an encoded bitstring up to length 1. |
| 52 | * If successful returns the length of the bitstring and 'result' contains the decoded bits. |
| 53 | * The decoded bitstring is stored in the LSBs of 'result', with the LSB being the last bit decoded. |
no outgoing calls
no test coverage detected