]> git.lizzy.rs Git - rust.git/commitdiff
Implement Show for Bitv{,Set}
authorSteven Fackler <sfackler@gmail.com>
Fri, 30 May 2014 04:29:06 +0000 (21:29 -0700)
committerSteven Fackler <sfackler@gmail.com>
Fri, 30 May 2014 04:29:06 +0000 (21:29 -0700)
Closes #14531

src/libcollections/bitv.rs

index 48491222be47ea3c6a4aa0973f4df6b5e370cf7e..54bc6989d7cf8ef5adff88aeab47a9c9c1d81f87 100644 (file)
 
 
 use std::cmp;
+use std::fmt;
 use std::iter::RandomAccessIterator;
 use std::iter::{Enumerate, Repeat, Map, Zip};
 use std::ops;
 use std::slice;
-use std::string::String;
 use std::uint;
 
 #[deriving(Clone)]
@@ -526,25 +526,6 @@ pub fn to_bools(&self) -> Vec<bool> {
         Vec::from_fn(self.nbits, |i| self[i])
     }
 
-    /**
-     * Converts `self` to a string.
-     *
-     * The resulting string has the same length as `self`, and each
-     * character is either '0' or '1'.
-     */
-     pub fn to_str(&self) -> String {
-        let mut rs = String::new();
-        for i in self.iter() {
-            if i {
-                rs.push_char('1');
-            } else {
-                rs.push_char('0');
-            }
-        };
-        rs
-     }
-
-
     /**
      * Compare a bitvector to a vector of `bool`.
      *
@@ -604,6 +585,15 @@ fn index(&self, i: &uint) -> bool {
     }
 }
 
+impl fmt::Show for Bitv {
+    fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
+        for bit in self.iter() {
+            try!(write!(fmt, "{}", if bit { 1 } else { 0 }));
+        }
+        Ok(())
+    }
+}
+
 #[inline]
 fn iterate_bits(base: uint, bits: uint, f: |uint| -> bool) -> bool {
     if bits == 0 {
@@ -827,6 +817,21 @@ fn eq(&self, other: &BitvSet) -> bool {
     fn ne(&self, other: &BitvSet) -> bool { !self.eq(other) }
 }
 
+impl fmt::Show for BitvSet {
+    fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
+        try!(write!(fmt, r"\{"));
+        let mut first = true;
+        for n in self.iter() {
+            if !first {
+                try!(write!(fmt, ", "));
+            }
+            try!(write!(fmt, "{}", n));
+            first = false;
+        }
+        write!(fmt, r"\}")
+    }
+}
+
 impl Container for BitvSet {
     #[inline]
     fn len(&self) -> uint { self.size }
@@ -1629,6 +1634,16 @@ fn test_big_bitv_tests() {
         assert!(!v.none());
     }
 
+    #[test]
+    fn test_bitv_set_show() {
+        let mut s = BitvSet::new();
+        s.insert(1);
+        s.insert(10);
+        s.insert(50);
+        s.insert(2);
+        assert_eq!("{1, 2, 10, 50}".to_string(), s.to_str());
+    }
+
     fn rng() -> rand::IsaacRng {
         let seed = &[1, 2, 3, 4, 5, 6, 7, 8, 9, 0];
         rand::SeedableRng::from_seed(seed)