Skip to content

Commit

Permalink
Implement the Debug trait for BitVec
Browse files Browse the repository at this point in the history
  • Loading branch information
wyhaya committed Jul 4, 2024
1 parent 498dda6 commit 3a0f172
Showing 1 changed file with 37 additions and 11 deletions.
48 changes: 37 additions & 11 deletions src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1708,10 +1708,18 @@ impl<B: BitBlock> fmt::Display for BitVec<B> {
impl<B: BitBlock> fmt::Debug for BitVec<B> {
fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
self.ensure_invariant();
for bit in self {
write!(fmt, "{}", if bit { 1 } else { 0 })?;
let mut storage = std::string::String::new();
let mut iter = self.iter().enumerate();
while let Some((i, bit)) = iter.next() {
if i != 0 && i % B::bits() == 0 {
storage.push(' ');
}
storage.push(if bit { '1' } else { '0' });
}
Ok(())
fmt.debug_struct("BitVec")
.field("storage", &storage)
.field("nbits", &self.nbits)
.finish()
}
}

Expand Down Expand Up @@ -1935,12 +1943,30 @@ mod tests {
const U32_BITS: usize = 32;

#[test]
fn test_to_str() {
let zerolen = BitVec::new();
assert_eq!(format!("{:?}", zerolen), "");
fn test_display_output() {
assert_eq!(format!("{}", BitVec::new()), "");
assert_eq!(format!("{}", BitVec::from_elem(1, true)), "1");
assert_eq!(format!("{}", BitVec::from_elem(8, false)), "00000000")
}

let eightbits = BitVec::from_elem(8, false);
assert_eq!(format!("{:?}", eightbits), "00000000")
#[test]
fn test_debug_output() {
assert_eq!(
format!("{:?}", BitVec::new()),
"BitVec { storage: \"\", nbits: 0 }"
);
assert_eq!(
format!("{:?}", BitVec::from_elem(1, true)),
"BitVec { storage: \"1\", nbits: 1 }"
);
assert_eq!(
format!("{:?}", BitVec::from_elem(8, false)),
"BitVec { storage: \"00000000\", nbits: 8 }"
);
assert_eq!(
format!("{:?}", BitVec::from_elem(33, true)),
"BitVec { storage: \"11111111111111111111111111111111 1\", nbits: 33 }"
)
}

#[test]
Expand All @@ -1966,7 +1992,7 @@ mod tests {
let mut b = BitVec::from_elem(2, false);
b.set(0, true);
b.set(1, false);
assert_eq!(format!("{:?}", b), "10");
assert_eq!(format!("{}", b), "10");
assert!(!b.none() && !b.all());
}

Expand Down Expand Up @@ -2316,7 +2342,7 @@ mod tests {
fn test_from_bytes() {
let bit_vec = BitVec::from_bytes(&[0b10110110, 0b00000000, 0b11111111]);
let str = concat!("10110110", "00000000", "11111111");
assert_eq!(format!("{:?}", bit_vec), str);
assert_eq!(format!("{}", bit_vec), str);
}

#[test]
Expand All @@ -2335,7 +2361,7 @@ mod tests {
fn test_from_bools() {
let bools = [true, false, true, true];
let bit_vec: BitVec = bools.iter().copied().collect();
assert_eq!(format!("{:?}", bit_vec), "1011");
assert_eq!(format!("{}", bit_vec), "1011");
}

#[test]
Expand Down

0 comments on commit 3a0f172

Please sign in to comment.