Skip to content

Commit

Permalink
Assert covariance of BTree{Map,Set} and associated iterators
Browse files Browse the repository at this point in the history
  • Loading branch information
nbdd0121 committed Aug 15, 2021
1 parent a59e885 commit a253a36
Show file tree
Hide file tree
Showing 2 changed files with 70 additions and 4 deletions.
54 changes: 52 additions & 2 deletions library/alloc/src/collections/btree/map.rs
Original file line number Diff line number Diff line change
@@ -1,3 +1,6 @@
#[cfg(test)]
mod tests;

use core::borrow::Borrow;
use core::cmp::Ordering;
use core::fmt::{self, Debug};
Expand Down Expand Up @@ -2220,5 +2223,52 @@ impl<K, V> BTreeMap<K, V> {
}
}

#[cfg(test)]
mod tests;
#[allow(dead_code)]
fn assert_covariance() {
// Lifetime and both type parameters should be covariant for these types.
fn map<'new>(v: BTreeMap<&'static str, &'static str>) -> BTreeMap<&'new str, &'new str> {
v
}
fn iter<'new>(
v: Iter<'static, &'static str, &'static str>,
) -> Iter<'new, &'new str, &'new str> {
v
}
fn into_iter<'new>(v: IntoIter<&'static str, &'static str>) -> IntoIter<&'new str, &'new str> {
v
}
fn keys<'new>(
v: Keys<'static, &'static str, &'static str>,
) -> Keys<'new, &'new str, &'new str> {
v
}
fn values<'new>(
v: Values<'static, &'static str, &'static str>,
) -> Values<'new, &'new str, &'new str> {
v
}
fn into_keys<'new>(v: IntoKeys<&'static str, &'static str>) -> IntoKeys<&'new str, &'new str> {
v
}
fn into_values<'new>(
v: IntoValues<&'static str, &'static str>,
) -> IntoValues<&'new str, &'new str> {
v
}
fn range<'new>(
v: Range<'static, &'static str, &'static str>,
) -> Range<'new, &'new str, &'new str> {
v
}

// Lifetime should be covariant for these types.
fn iter_mut<'new>(v: IterMut<'static, u8, u8>) -> IterMut<'new, u8, u8> {
v
}
fn values_mut<'new>(v: ValuesMut<'static, u8, u8>) -> ValuesMut<'new, u8, u8> {
v
}
fn range_mut<'new>(v: RangeMut<'static, u8, u8>) -> RangeMut<'new, u8, u8> {
v
}
}
20 changes: 18 additions & 2 deletions library/alloc/src/collections/btree/set.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,9 @@
// This is pretty much entirely stolen from TreeSet, since BTreeMap has an identical interface
// to TreeMap

#[cfg(test)]
mod tests;

use core::borrow::Borrow;
use core::cmp::Ordering::{Equal, Greater, Less};
use core::cmp::{max, min};
Expand Down Expand Up @@ -1601,5 +1604,18 @@ impl<'a, T: Ord> Iterator for Union<'a, T> {
#[stable(feature = "fused", since = "1.26.0")]
impl<T: Ord> FusedIterator for Union<'_, T> {}

#[cfg(test)]
mod tests;
#[allow(dead_code)]
fn assert_covariance() {
fn set<'new>(v: BTreeSet<&'static str>) -> BTreeSet<&'new str> {
v
}
fn iter<'new>(v: Iter<'static, &'static str>) -> Iter<'new, &'new str> {
v
}
fn into_iter<'new>(v: IntoIter<&'static str>) -> IntoIter<&'new str> {
v
}
fn range<'new>(v: Range<'static, &'static str>) -> Range<'new, &'new str> {
v
}
}

0 comments on commit a253a36

Please sign in to comment.