Skip to content

Commit 9c12b0f

Browse files
nikomatsakisNiko Matsakis
authored andcommitted
add down/up-cast impls for singleton sets, lists
Use a 1-tuple for this. It's mildly inconsistent with 2-, 3-tuples being "flatten". Not sure how I feel about that.
1 parent 7430462 commit 9c12b0f

File tree

1 file changed

+54
-1
lines changed

1 file changed

+54
-1
lines changed

crates/formality-core/src/collections.rs

Lines changed: 54 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -3,7 +3,10 @@
33
44
use std::collections::{BTreeMap, BTreeSet};
55

6-
use crate::cast::{DowncastTo, Upcast, UpcastFrom, Upcasted};
6+
use crate::{
7+
cast::{DowncastTo, Upcast, UpcastFrom, Upcasted},
8+
Downcast,
9+
};
710

811
pub type Map<K, V> = BTreeMap<K, V>;
912
pub type Set<E> = BTreeSet<E>;
@@ -136,6 +139,31 @@ impl<T> DowncastTo<()> for Set<T> {
136139
}
137140
}
138141

142+
impl<A, T> DowncastTo<(A,)> for Set<T>
143+
where
144+
T: DowncastTo<A> + Ord,
145+
{
146+
fn downcast_to(&self) -> Option<(A,)> {
147+
if self.len() == 1 {
148+
let a: A = self.first().unwrap().downcast()?;
149+
Some((a,))
150+
} else {
151+
None
152+
}
153+
}
154+
}
155+
156+
impl<A, T> UpcastFrom<(A,)> for Set<T>
157+
where
158+
A: Clone + Upcast<T>,
159+
T: Ord + Clone,
160+
{
161+
fn upcast_from(term: (A,)) -> Self {
162+
let (a,) = term;
163+
set![a.upcast()]
164+
}
165+
}
166+
139167
impl<T> DowncastTo<()> for Vec<T> {
140168
fn downcast_to(&self) -> Option<()> {
141169
if self.is_empty() {
@@ -146,6 +174,31 @@ impl<T> DowncastTo<()> for Vec<T> {
146174
}
147175
}
148176

177+
impl<A, T> DowncastTo<(A,)> for Vec<T>
178+
where
179+
T: DowncastTo<A>,
180+
{
181+
fn downcast_to(&self) -> Option<(A,)> {
182+
if self.len() == 1 {
183+
let a: A = self.first().unwrap().downcast()?;
184+
Some((a,))
185+
} else {
186+
None
187+
}
188+
}
189+
}
190+
191+
impl<A, T> UpcastFrom<(A,)> for Vec<T>
192+
where
193+
A: Clone + Upcast<T>,
194+
T: Clone,
195+
{
196+
fn upcast_from(term: (A,)) -> Self {
197+
let (a,) = term;
198+
vec![a.upcast()]
199+
}
200+
}
201+
149202
macro_rules! tuple_upcast {
150203
($coll:ident : $($name:ident),*) => {
151204
/// Upcast from a tuple of iterable things into a collection.

0 commit comments

Comments
 (0)