Skip to content

Commit

Permalink
Merge pull request #39 from Dolphindalt/master
Browse files Browse the repository at this point in the history
Implemented Binary and Display traits for FixedBitSet.
  • Loading branch information
bluss committed Apr 15, 2020
2 parents 1801536 + e3787d1 commit 3f67eb6
Showing 1 changed file with 50 additions and 0 deletions.
50 changes: 50 additions & 0 deletions src/lib.rs
Expand Up @@ -28,6 +28,9 @@ use core as std;

mod range;

use std::fmt::Write;
use std::fmt::{Display, Error, Formatter, Binary};

use std::ops::{BitAnd, BitAndAssign, BitOr, BitOrAssign, BitXor, BitXorAssign, Index};
use std::cmp::{Ord, Ordering};
use std::iter::{Chain, FromIterator};
Expand Down Expand Up @@ -356,6 +359,30 @@ impl FixedBitSet
}
}

impl Binary for FixedBitSet {
fn fmt(&self, f: &mut Formatter<'_>) -> Result<(), Error> {
if f.alternate() {
f.write_str("0b")?;
}

for i in 0..self.length {
if self[i] {
f.write_char('1')?;
} else {
f.write_char('0')?;
}
}

Ok(())
}
}

impl Display for FixedBitSet {
fn fmt(&self, f: &mut Formatter<'_>) -> Result<(), Error> {
Binary::fmt(&self, f)
}
}

/// An iterator producing elements in the difference of two sets.
///
/// This struct is created by the [`FixedBitSet::difference`] method.
Expand Down Expand Up @@ -1373,3 +1400,26 @@ fn from_iterator_ones() {
assert_eq!(fb.len(), dup.len());
assert_eq!(fb.ones().collect::<Vec<usize>>(), dup.ones().collect::<Vec<usize>>());
}

#[cfg(feature = "std")]
#[test]
fn binary_trait() {
let items: Vec<usize> = vec![1, 5, 7, 10, 14, 15];
let fb = items.iter().cloned().collect::<FixedBitSet>();

assert_eq!(format!("{:b}", fb), "0100010100100011");
assert_eq!(format!("{:#b}", fb), "0b0100010100100011");
}

#[cfg(feature = "std")]
#[test]
fn display_trait() {
let len = 8;
let mut fb = FixedBitSet::with_capacity(len);

fb.put(4);
fb.put(2);

assert_eq!(format!("{}", fb), "00101000");
assert_eq!(format!("{:#}", fb), "0b00101000");
}

0 comments on commit 3f67eb6

Please sign in to comment.