cranelift-entity: improve EntitySet::cardinality() implementation (#6066)
* Simplify 'EntitySet::cardinality()' * Fix test
This commit is contained in:
@@ -73,16 +73,10 @@ where
|
|||||||
/// `insert` with different key values, that have happened since the the set was most recently
|
/// `insert` with different key values, that have happened since the the set was most recently
|
||||||
/// `clear`ed or created with `new`.
|
/// `clear`ed or created with `new`.
|
||||||
pub fn cardinality(&self) -> usize {
|
pub fn cardinality(&self) -> usize {
|
||||||
let mut n: usize = 0;
|
self.elems[..(self.len + (BITS - 1)) / BITS]
|
||||||
for idx in 0..self.len / BITS {
|
.iter()
|
||||||
n += self.elems[idx].count_ones() as usize;
|
.map(|x| x.count_ones() as usize)
|
||||||
}
|
.sum()
|
||||||
for bit_ix in (self.len / BITS) * BITS..self.len {
|
|
||||||
if (self.elems[bit_ix / BITS] & (1 << (bit_ix % BITS))) != 0 {
|
|
||||||
n += 1;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
n
|
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Remove all entries from this set.
|
/// Remove all entries from this set.
|
||||||
@@ -254,4 +248,43 @@ mod tests {
|
|||||||
|
|
||||||
assert!(m.is_empty());
|
assert!(m.is_empty());
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn cardinality() {
|
||||||
|
let mut m = EntitySet::new();
|
||||||
|
|
||||||
|
m.insert(E(1));
|
||||||
|
assert!(m.cardinality() == 1);
|
||||||
|
|
||||||
|
m.insert(E(0));
|
||||||
|
assert!(m.cardinality() == 2);
|
||||||
|
|
||||||
|
m.insert(E(1));
|
||||||
|
assert!(m.cardinality() == 2);
|
||||||
|
|
||||||
|
m.insert(E(BITS as u32 - 1));
|
||||||
|
assert!(m.cardinality() == 3);
|
||||||
|
|
||||||
|
m.insert(E(BITS as u32));
|
||||||
|
assert!(m.cardinality() == 4);
|
||||||
|
|
||||||
|
m.insert(E(BITS as u32 - 1));
|
||||||
|
assert!(m.cardinality() == 4);
|
||||||
|
|
||||||
|
assert!(m.pop() == Some(E(BITS as u32)));
|
||||||
|
assert!(m.cardinality() == 3);
|
||||||
|
assert!(m.pop() == Some(E(BITS as u32 - 1)));
|
||||||
|
assert!(m.cardinality() == 2);
|
||||||
|
|
||||||
|
m.insert(E(100));
|
||||||
|
assert!(m.cardinality() == 3);
|
||||||
|
|
||||||
|
assert!(m.pop() == Some(E(100)));
|
||||||
|
assert!(m.cardinality() == 2);
|
||||||
|
|
||||||
|
m.insert(E(100));
|
||||||
|
m.insert(E(101));
|
||||||
|
m.insert(E(102));
|
||||||
|
assert!(m.cardinality() == 5);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
Reference in New Issue
Block a user