Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Implemented Binary and Display traits for FixedBitSet. #39

Merged
merged 4 commits into from Apr 15, 2020
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
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");
}