Encodes a standard span-batch bitlist. The bitlist is encoded as big-endian integer, left-padded with zeroes to a multiple of 8 bits. The encoded bitlist cannot be longer than `bit_length`
(
w: &mut dyn bytes::BufMut,
bit_length: usize,
bits: &Self,
)
| 52 | /// The bitlist is encoded as big-endian integer, left-padded with zeroes to a multiple of 8 |
| 53 | /// bits. The encoded bitlist cannot be longer than `bit_length` |
| 54 | pub fn encode( |
| 55 | w: &mut dyn bytes::BufMut, |
| 56 | bit_length: usize, |
| 57 | bits: &Self, |
| 58 | ) -> Result<(), SpanBatchError> { |
| 59 | if bits.bit_len() > bit_length { |
| 60 | return Err(SpanBatchError::BitfieldTooLong); |
| 61 | } |
| 62 | |
| 63 | // Round up, ensure enough bytes when number of bits is not a multiple of 8. |
| 64 | // Alternative of (L+7)/8 is not overflow-safe. |
| 65 | let buf_len = bit_length / 8 + if !bit_length.is_multiple_of(8) { 1 } else { 0 }; |
| 66 | let mut buf = vec![0; buf_len]; |
| 67 | buf[buf_len - bits.0.len()..].copy_from_slice(bits.as_ref()); |
| 68 | w.put_slice(&buf); |
| 69 | Ok(()) |
| 70 | } |
| 71 | |
| 72 | /// Get a bit from the [`SpanBatchBits`] bitlist. |
| 73 | pub fn get_bit(&self, index: usize) -> Option<u8> { |