Skip to content

Commit ab2920f

Browse files
kkoyungjdm
authored andcommitted
Implements Ref::filter_map and RefMut::filter_map
In the Rust Standard Library, `std::cell::Ref` and `std::cell::RefMut` have an associated function `filter_map`, which provide the similar functionality as `ref_filter_map` and `ref_mut_filter_map`. Implements `Ref::filter_map` and `RefMut::filter_map` to match the standard library.
1 parent 79e5f85 commit ab2920f

File tree

1 file changed

+22
-0
lines changed

1 file changed

+22
-0
lines changed

src/lib.rs

Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -100,6 +100,16 @@ impl<'a, T: ?Sized> Ref<'a, T> {
100100
data: orig.data,
101101
}
102102
}
103+
104+
pub fn filter_map<U: ?Sized, F>(orig: Ref<'a, T>, f: F) -> Result<Ref<'a, U>, Self>
105+
where
106+
F: FnOnce(&T) -> Option<&U>,
107+
{
108+
match f(&orig).map(|new| new as *const U) {
109+
Some(raw) => Ok(Ref::map(orig, |_| unsafe { &*raw })),
110+
None => Err(orig),
111+
}
112+
}
103113
}
104114

105115
impl<'a, T: ?Sized + Display> Display for Ref<'a, T> {
@@ -150,6 +160,16 @@ impl<'a, T: ?Sized> RefMut<'a, T> {
150160
data,
151161
}
152162
}
163+
164+
pub fn filter_map<U: ?Sized, F>(mut orig: RefMut<'a, T>, f: F) -> Result<RefMut<'a, U>, Self>
165+
where
166+
F: FnOnce(&mut T) -> Option<&mut U>,
167+
{
168+
match f(&mut orig).map(|new| new as *mut U) {
169+
Some(raw) => Ok(RefMut::map(orig, |_| unsafe { &mut *raw })),
170+
None => Err(orig),
171+
}
172+
}
153173
}
154174

155175
impl<'a, T: ?Sized> Deref for RefMut<'a, T> {
@@ -317,6 +337,7 @@ impl<T: ?Sized + PartialEq> PartialEq for RefCell<T> {
317337
}
318338
}
319339

340+
#[deprecated(since = "0.2.2", note = "Users should instead use Ref::filter_map")]
320341
pub fn ref_filter_map<T: ?Sized, U: ?Sized, F: FnOnce(&T) -> Option<&U>>(
321342
orig: Ref<T>,
322343
f: F,
@@ -326,6 +347,7 @@ pub fn ref_filter_map<T: ?Sized, U: ?Sized, F: FnOnce(&T) -> Option<&U>>(
326347
.map(|raw| Ref::map(orig, |_| unsafe { &*raw }))
327348
}
328349

350+
#[deprecated(since = "0.2.2", note = "Users should instead use RefMut::filter_map")]
329351
pub fn ref_mut_filter_map<T: ?Sized, U: ?Sized, F: FnOnce(&mut T) -> Option<&mut U>>(
330352
mut orig: RefMut<T>,
331353
f: F,

0 commit comments

Comments
 (0)