Skip to content

Commit

Permalink
Add Default and Debug impls to SparseMap (bytecodealliance#9860)
Browse files Browse the repository at this point in the history
* add Default and Debug impls to SparseMap

* more meaningful debug impl
  • Loading branch information
wtachau authored Dec 18, 2024
1 parent b3ac63a commit ab325dc
Showing 1 changed file with 44 additions and 0 deletions.
44 changes: 44 additions & 0 deletions cranelift/entity/src/sparse.rs
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@
use crate::map::SecondaryMap;
use crate::EntityRef;
use alloc::vec::Vec;
use core::fmt;
use core::mem;
use core::slice;
use core::u32;
Expand Down Expand Up @@ -203,6 +204,28 @@ where
}
}

impl<K, V> Default for SparseMap<K, V>
where
K: EntityRef,
V: SparseMapValue<K>,
{
fn default() -> SparseMap<K, V> {
SparseMap::new()
}
}

impl<K, V> fmt::Debug for SparseMap<K, V>
where
K: EntityRef + fmt::Debug,
V: SparseMapValue<K> + fmt::Debug,
{
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_map()
.entries(self.values().map(|v| (v.key(), v)))
.finish()
}
}

/// Iterating over the elements of a set.
impl<'a, K, V> IntoIterator for &'a SparseMap<K, V>
where
Expand Down Expand Up @@ -234,6 +257,8 @@ pub type SparseSet<T> = SparseMap<T, T>;

#[cfg(test)]
mod tests {
use alloc::format;

use super::*;

/// An opaque reference to an instruction in a function.
Expand Down Expand Up @@ -364,4 +389,23 @@ mod tests {
assert_eq!(set.get(i0), Some(&i0));
assert_eq!(set.get(i1), Some(&i1));
}

#[test]
fn default_impl() {
let map: SparseMap<Inst, Obj> = SparseMap::default();

assert!(map.is_empty());
assert_eq!(map.len(), 0);
}

#[test]
fn debug_impl() {
let i1 = Inst::new(1);
let mut map = SparseMap::new();
assert_eq!(map.insert(Obj(i1, "hi")), None);

let debug = format!("{map:?}");
let expected = "{inst1: Obj(inst1, \"hi\")}";
assert_eq!(debug, expected);
}
}

0 comments on commit ab325dc

Please sign in to comment.