summaryrefslogtreecommitdiffstats
path: root/core/src
diff options
context:
space:
mode:
authorLibravatar Héctor Ramón Jiménez <hector@hecrj.dev>2025-02-11 03:39:42 +0100
committerLibravatar Héctor Ramón Jiménez <hector@hecrj.dev>2025-02-11 03:41:29 +0100
commit0c528be2ea74f9aae1d4ac80b282ba9c16674649 (patch)
tree87108ca5917382a8e6a7d53968896f5ee1f7a617 /core/src
parent9f21eae1528fa414adbfb987ce4c851fa58326fe (diff)
downloadiced-0c528be2ea74f9aae1d4ac80b282ba9c16674649.tar.gz
iced-0c528be2ea74f9aae1d4ac80b282ba9c16674649.tar.bz2
iced-0c528be2ea74f9aae1d4ac80b282ba9c16674649.zip
Introduce `with` helper and use `sipper` in `gallery` example
Diffstat (limited to 'core/src')
-rw-r--r--core/src/lib.rs60
1 files changed, 60 insertions, 0 deletions
diff --git a/core/src/lib.rs b/core/src/lib.rs
index d5c221ac..ac0a228f 100644
--- a/core/src/lib.rs
+++ b/core/src/lib.rs
@@ -93,3 +93,63 @@ pub use smol_str::SmolStr;
pub fn never<T>(never: std::convert::Infallible) -> T {
match never {}
}
+
+/// Applies the given prefix value to the provided closure and returns
+/// a new closure that takes the other argument.
+///
+/// This lets you partially "apply" a function—equivalent to currying,
+/// but it only works with binary functions. If you want to apply an
+/// arbitrary number of arguments, use the [`with!`] macro instead.
+///
+/// # When is this useful?
+/// Sometimes you will want to identify the source or target
+/// of some message in your user interface. This can be achieved through
+/// normal means by defining a closure and moving the identifier
+/// inside:
+///
+/// ```rust
+/// # let element: Option<()> = Some(());
+/// # enum Message { ButtonPressed(u32, ()) }
+/// let id = 123;
+///
+/// # let _ = {
+/// element.map(move |result| Message::ButtonPressed(id, result))
+/// # };
+/// ```
+///
+/// That's quite a mouthful. [`with()`] lets you write:
+///
+/// ```rust
+/// # use iced_core::with;
+/// # let element: Option<()> = Some(());
+/// # enum Message { ButtonPressed(u32, ()) }
+/// let id = 123;
+///
+/// # let _ = {
+/// element.map(with(Message::ButtonPressed, id))
+/// # };
+/// ```
+///
+/// Effectively creating the same closure that partially applies
+/// the `id` to the message—but much more concise!
+pub fn with<T, R, O>(
+ mut f: impl FnMut(T, R) -> O,
+ prefix: T,
+) -> impl FnMut(R) -> O
+where
+ T: Clone,
+{
+ move |result| f(prefix.clone(), result)
+}
+
+/// Applies the given prefix values to the provided closure in the first
+/// argument and returns a new closure that takes its last argument.
+///
+/// This is variadic version of [`with()`] which works with any number of
+/// arguments.
+#[macro_export]
+macro_rules! with {
+ ($f:expr, $($x:expr),+ $(,)?) => {
+ move |result| $f($($x),+, result)
+ };
+}