Skip to content

Commit 386e511

Browse files
authored
Make PluralElements::map take FnMut; add try_map (#6478)
1 parent 9c48ed5 commit 386e511

File tree

1 file changed

+36
-13
lines changed

1 file changed

+36
-13
lines changed

components/plurals/src/lib.rs

Lines changed: 36 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -89,6 +89,7 @@ mod raw_operands;
8989
pub use raw_operands::RawPluralOperands;
9090

9191
use core::cmp::{Ord, PartialOrd};
92+
use core::convert::Infallible;
9293
use icu_locale_core::preferences::define_preferences;
9394
use icu_provider::marker::ErasedMarker;
9495
use icu_provider::prelude::*;
@@ -936,19 +937,41 @@ impl<T> PluralElements<T> {
936937
self.0.explicit_one.as_ref()
937938
}
938939

939-
/// Applies a function `f` to map all values to another type.
940-
pub fn map<B, F: Fn(T) -> B>(self, f: F) -> PluralElements<B> {
941-
let f = &f;
942-
PluralElements(PluralElementsInner {
943-
other: f(self.0.other),
944-
zero: self.0.zero.map(f),
945-
one: self.0.one.map(f),
946-
two: self.0.two.map(f),
947-
few: self.0.few.map(f),
948-
many: self.0.many.map(f),
949-
explicit_zero: self.0.explicit_zero.map(f),
950-
explicit_one: self.0.explicit_one.map(f),
951-
})
940+
/// Applies a function `f` to convert all values to another type.
941+
///
942+
/// # Examples
943+
///
944+
/// ```
945+
/// use icu_plurals::PluralElements;
946+
///
947+
/// let x = PluralElements::new(11).with_one_value(Some(15));
948+
/// let y = x.map(|i| i * 2);
949+
///
950+
/// assert_eq!(*y.other(), 22);
951+
/// assert_eq!(*y.one(), 30);
952+
/// ```
953+
pub fn map<B, F: FnMut(T) -> B>(self, mut f: F) -> PluralElements<B> {
954+
let Ok(x) = self.try_map(move |x| Ok::<B, Infallible>(f(x)));
955+
x
956+
}
957+
958+
/// Applies a function `f` to convert all values to another type,
959+
/// propagating a possible error.
960+
pub fn try_map<B, E, F: FnMut(T) -> Result<B, E>>(
961+
self,
962+
mut f: F,
963+
) -> Result<PluralElements<B>, E> {
964+
let plural_elements = PluralElements(PluralElementsInner {
965+
other: f(self.0.other)?,
966+
zero: self.0.zero.map(&mut f).transpose()?,
967+
one: self.0.one.map(&mut f).transpose()?,
968+
two: self.0.two.map(&mut f).transpose()?,
969+
few: self.0.few.map(&mut f).transpose()?,
970+
many: self.0.many.map(&mut f).transpose()?,
971+
explicit_zero: self.0.explicit_zero.map(&mut f).transpose()?,
972+
explicit_one: self.0.explicit_one.map(&mut f).transpose()?,
973+
});
974+
Ok(plural_elements)
952975
}
953976

954977
/// Converts from `&PluralElements<T>` to `PluralElements<&T>`.

0 commit comments

Comments
 (0)