]> git.lizzy.rs Git - rust.git/commitdiff
Implement Show for SmallIntMap
authorAdolfo Ochagavía <aochagavia92@gmail.com>
Sat, 7 Jun 2014 16:17:58 +0000 (18:17 +0200)
committerAdolfo Ochagavía <aochagavia92@gmail.com>
Sat, 7 Jun 2014 17:44:45 +0000 (19:44 +0200)
src/libcollections/smallintmap.rs

index f3118181bdcdd148f682b96e3b9d73360e8f28e3..45584dd4b28ba4eccda480616bd855e23cbc1bcb 100644 (file)
@@ -17,6 +17,7 @@
 
 use core::prelude::*;
 
+use core::fmt;
 use core::iter::{Enumerate, FilterMap};
 use core::mem::replace;
 
@@ -176,6 +177,18 @@ pub fn update(&mut self, key: uint, newval: V, ff: |V, V| -> V) -> bool {
     }
 }
 
+impl<V: fmt::Show> fmt::Show for SmallIntMap<V> {
+    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
+        try!(write!(f, r"\{"));
+
+        for (i, (k, v)) in self.iter().enumerate() {
+            if i != 0 { try!(write!(f, ", ")); }
+            try!(write!(f, "{}: {}", k, *v));
+        }
+
+        write!(f, r"\}")
+    }
+}
 
 macro_rules! iterator {
     (impl $name:ident -> $elem:ty, $getter:ident) => {
@@ -461,6 +474,20 @@ fn test_move_iter() {
         assert!(called);
         m.insert(2, box 1);
     }
+
+    #[test]
+    fn test_show() {
+        let mut map = SmallIntMap::new();
+        let empty = SmallIntMap::<int>::new();
+
+        map.insert(1, 2);
+        map.insert(3, 4);
+
+        let map_str = map.to_str();
+        let map_str = map_str.as_slice();
+        assert!(map_str == "{1: 2, 3: 4}" || map_str == "{3: 4, 1: 2}");
+        assert_eq!(format!("{}", empty), "{}".to_string());
+    }
 }
 
 #[cfg(test)]