Skip to content

Commit f96876c

Browse files
authored
Add assert in debug mode and tests (#1416)
1 parent e2a7a3e commit f96876c

File tree

1 file changed

+25
-1
lines changed

1 file changed

+25
-1
lines changed

utils/bitfield/src/rleplus/writer.rs

Lines changed: 25 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,9 @@
11
// Copyright 2019-2022 ChainSafe Systems
22
// SPDX-License-Identifier: Apache-2.0, MIT
33

4+
/// The maximum varint that can be serialized on 9 bytes.
5+
const MAX_VARINT: u64 = 2u64.pow(63)-1;
6+
47
#[derive(Default, Clone, Debug)]
58
/// A `BitWriter` allows for efficiently writing bits to a byte buffer, up to a byte at a time.
69
pub struct BitWriter {
@@ -37,6 +40,7 @@ impl BitWriter {
3740
/// Writes a given length to the buffer according to RLE+ encoding.
3841
pub fn write_len(&mut self, len: usize) {
3942
debug_assert!(len > 0);
43+
debug_assert!(len <= (MAX_VARINT as usize));
4044

4145
if len == 1 {
4246
// Block Single (prefix 1)
@@ -85,7 +89,7 @@ impl BitWriter {
8589

8690
#[cfg(test)]
8791
mod tests {
88-
use super::BitWriter;
92+
use super::{BitWriter, MAX_VARINT};
8993

9094
#[test]
9195
fn write() {
@@ -178,4 +182,24 @@ mod tests {
178182
let mut writer = BitWriter::new();
179183
writer.write(0, 16);
180184
}
185+
186+
#[test]
187+
fn test_write_max_varint() {
188+
let mut writer = BitWriter::new();
189+
writer.write(0b_0000_0100, 3);
190+
writer.write_len(MAX_VARINT as usize);
191+
let rle = writer.finish();
192+
193+
crate::BitField::from_bytes(&rle).unwrap();
194+
}
195+
196+
#[cfg(debug_assertions)]
197+
#[test]
198+
#[should_panic(expected = "assertion failed")]
199+
fn test_write_succ_max_varint() {
200+
let mut writer = BitWriter::new();
201+
writer.write(0b_0000_0100, 3);
202+
writer.write_len(MAX_VARINT as usize + 1);
203+
writer.finish();
204+
}
181205
}

0 commit comments

Comments
 (0)