MCPcopy Create free account
hub / github.com/ElementsProject/elements / simplicity_readNBits

Function simplicity_readNBits

src/simplicity/bitstream.c:33–50  ·  view source on GitHub ↗

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 */

Source from the content-addressed store, hash-verified

31 * NULL != stream
32 */
33int32_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.

Callers 6

read1BitFunction · 0.85
decodeUpto3BitsFunction · 0.85
decodeUpto15BitsFunction · 0.85
getWord32ArrayFunction · 0.85
decodeNodeFunction · 0.85

Calls

no outgoing calls

Tested by

no test coverage detected