prism3_function/transformer.rs
1/*******************************************************************************
2 *
3 * Copyright (c) 2025.
4 * 3-Prism Co. Ltd.
5 *
6 * All rights reserved.
7 *
8 ******************************************************************************/
9//! # Transformer Types
10//!
11//! Provides Rust implementations of transformer traits for type conversion
12//! and value transformation. Transformers consume input values (taking
13//! ownership) and produce output values.
14//!
15//! This module provides the `Transformer<T, R>` trait and three
16//! implementations:
17//!
18//! - [`BoxTransformer`]: Single ownership, not cloneable
19//! - [`ArcTransformer`]: Thread-safe shared ownership, cloneable
20//! - [`RcTransformer`]: Single-threaded shared ownership, cloneable
21//!
22//! # Author
23//!
24//! Hu Haixing
25
26use std::rc::Rc;
27use std::sync::Arc;
28
29use crate::predicate::{ArcPredicate, BoxPredicate, Predicate, RcPredicate};
30
31// ============================================================================
32// Core Trait
33// ============================================================================
34
35/// Transformer trait - transforms values from type T to type R
36///
37/// Defines the behavior of a transformation: converting a value of type `T`
38/// to a value of type `R` by consuming the input. This is analogous to
39/// `Fn(T) -> R` in Rust's standard library.
40///
41/// # Type Parameters
42///
43/// * `T` - The type of the input value (consumed)
44/// * `R` - The type of the output value
45///
46/// # Author
47///
48/// Hu Haixing
49pub trait Transformer<T, R> {
50 /// Transforms the input value to produce an output value
51 ///
52 /// # Parameters
53 ///
54 /// * `input` - The input value to transform (consumed)
55 ///
56 /// # Returns
57 ///
58 /// The transformed output value
59 fn transform(&self, input: T) -> R;
60
61 /// Converts to BoxTransformer
62 ///
63 /// **⚠️ Consumes `self`**: The original transformer becomes unavailable
64 /// after calling this method.
65 ///
66 /// # Returns
67 ///
68 /// Returns `BoxTransformer<T, R>`
69 fn into_box(self) -> BoxTransformer<T, R>
70 where
71 Self: Sized + 'static,
72 T: 'static,
73 R: 'static;
74
75 /// Converts to RcTransformer
76 ///
77 /// **⚠️ Consumes `self`**: The original transformer becomes unavailable
78 /// after calling this method.
79 ///
80 /// # Returns
81 ///
82 /// Returns `RcTransformer<T, R>`
83 fn into_rc(self) -> RcTransformer<T, R>
84 where
85 Self: Sized + 'static,
86 T: 'static,
87 R: 'static;
88
89 /// Converts to ArcTransformer
90 ///
91 /// **⚠️ Consumes `self`**: The original transformer becomes unavailable
92 /// after calling this method.
93 ///
94 /// # Returns
95 ///
96 /// Returns `ArcTransformer<T, R>`
97 fn into_arc(self) -> ArcTransformer<T, R>
98 where
99 Self: Sized + Send + Sync + 'static,
100 T: Send + Sync + 'static,
101 R: Send + Sync + 'static;
102
103 /// Converts transformer to a closure
104 ///
105 /// **⚠️ Consumes `self`**: The original transformer becomes unavailable
106 /// after calling this method.
107 ///
108 /// # Returns
109 ///
110 /// Returns a closure that implements `Fn(T) -> R`
111 fn into_fn(self) -> impl Fn(T) -> R
112 where
113 Self: Sized + 'static,
114 T: 'static,
115 R: 'static;
116}
117
118// ============================================================================
119// BoxTransformer - Box<dyn Fn(T) -> R>
120// ============================================================================
121
122/// BoxTransformer - transformer wrapper based on `Box<dyn Fn>`
123///
124/// A transformer wrapper that provides single ownership with reusable
125/// transformation. The transformer consumes the input and can be called
126/// multiple times.
127///
128/// # Features
129///
130/// - **Based on**: `Box<dyn Fn(T) -> R>`
131/// - **Ownership**: Single ownership, cannot be cloned
132/// - **Reusability**: Can be called multiple times (each call consumes its
133/// input)
134/// - **Thread Safety**: Not thread-safe (no `Send + Sync` requirement)
135///
136/// # Author
137///
138/// Hu Haixing
139pub struct BoxTransformer<T, R> {
140 function: Box<dyn Fn(T) -> R>,
141}
142
143impl<T, R> BoxTransformer<T, R>
144where
145 T: 'static,
146 R: 'static,
147{
148 /// Creates a new BoxTransformer
149 ///
150 /// # Parameters
151 ///
152 /// * `f` - The closure or function to wrap
153 ///
154 /// # Examples
155 ///
156 /// ```rust
157 /// use prism3_function::{BoxTransformer, Transformer};
158 ///
159 /// let double = BoxTransformer::new(|x: i32| x * 2);
160 /// assert_eq!(double.transform(21), 42);
161 /// ```
162 pub fn new<F>(f: F) -> Self
163 where
164 F: Fn(T) -> R + 'static,
165 {
166 BoxTransformer {
167 function: Box::new(f),
168 }
169 }
170
171 /// Creates an identity transformer
172 ///
173 /// # Examples
174 ///
175 /// ```rust
176 /// use prism3_function::{BoxTransformer, Transformer};
177 ///
178 /// let identity = BoxTransformer::<i32, i32>::identity();
179 /// assert_eq!(identity.transform(42), 42);
180 /// ```
181 pub fn identity() -> BoxTransformer<T, T> {
182 BoxTransformer::new(|x| x)
183 }
184
185 /// Chain composition - applies self first, then after
186 ///
187 /// Creates a new transformer that applies this transformer first, then
188 /// applies the after transformer to the result. Consumes self.
189 ///
190 /// # Type Parameters
191 ///
192 /// * `S` - The output type of the after transformer
193 /// * `F` - The type of the after transformer (must implement
194 /// Transformer<R, S>)
195 ///
196 /// # Parameters
197 ///
198 /// * `after` - The transformer to apply after self. **Note: This parameter
199 /// is passed by value and will transfer ownership.** If you need to
200 /// preserve the original transformer, clone it first (if it implements
201 /// `Clone`). Can be:
202 /// - A closure: `|x: R| -> S`
203 /// - A function pointer: `fn(R) -> S`
204 /// - A `BoxTransformer<R, S>`
205 /// - An `RcTransformer<R, S>`
206 /// - An `ArcTransformer<R, S>`
207 /// - Any type implementing `Transformer<R, S>`
208 ///
209 /// # Returns
210 ///
211 /// A new BoxTransformer representing the composition
212 ///
213 /// # Examples
214 ///
215 /// ## Direct value passing (ownership transfer)
216 ///
217 /// ```rust
218 /// use prism3_function::{BoxTransformer, Transformer};
219 ///
220 /// let double = BoxTransformer::new(|x: i32| x * 2);
221 /// let to_string = BoxTransformer::new(|x: i32| x.to_string());
222 ///
223 /// // to_string is moved here
224 /// let composed = double.and_then(to_string);
225 /// assert_eq!(composed.transform(21), "42");
226 /// // to_string.transform(5); // Would not compile - moved
227 /// ```
228 ///
229 /// ## Preserving original with clone
230 ///
231 /// ```rust
232 /// use prism3_function::{BoxTransformer, Transformer};
233 ///
234 /// let double = BoxTransformer::new(|x: i32| x * 2);
235 /// let to_string = BoxTransformer::new(|x: i32| x.to_string());
236 ///
237 /// // Clone to preserve original
238 /// let composed = double.and_then(to_string.clone());
239 /// assert_eq!(composed.transform(21), "42");
240 ///
241 /// // Original still usable
242 /// assert_eq!(to_string.transform(5), "5");
243 /// ```
244 pub fn and_then<S, F>(self, after: F) -> BoxTransformer<T, S>
245 where
246 S: 'static,
247 F: Transformer<R, S> + 'static,
248 {
249 let self_fn = self.function;
250 BoxTransformer::new(move |x: T| after.transform(self_fn(x)))
251 }
252
253 /// Reverse composition - applies before first, then self
254 ///
255 /// Creates a new transformer that applies the before transformer first,
256 /// then applies this transformer to the result. Consumes self.
257 ///
258 /// # Type Parameters
259 ///
260 /// * `S` - The input type of the before transformer
261 /// * `F` - The type of the before transformer (must implement
262 /// Transformer<S, T>)
263 ///
264 /// # Parameters
265 ///
266 /// * `before` - The transformer to apply before self. **Note: This parameter
267 /// is passed by value and will transfer ownership.** If you need to
268 /// preserve the original transformer, clone it first (if it implements
269 /// `Clone`). Can be:
270 /// - A closure: `|x: S| -> T`
271 /// - A function pointer: `fn(S) -> T`
272 /// - A `BoxTransformer<S, T>`
273 /// - An `RcTransformer<S, T>`
274 /// - An `ArcTransformer<S, T>`
275 /// - Any type implementing `Transformer<S, T>`
276 ///
277 /// # Returns
278 ///
279 /// A new BoxTransformer representing the composition
280 ///
281 /// # Examples
282 ///
283 /// ## Direct value passing (ownership transfer)
284 ///
285 /// ```rust
286 /// use prism3_function::{BoxTransformer, Transformer};
287 ///
288 /// let double = BoxTransformer::new(|x: i32| x * 2);
289 /// let add_one = BoxTransformer::new(|x: i32| x + 1);
290 ///
291 /// // add_one is moved here
292 /// let composed = double.compose(add_one);
293 /// assert_eq!(composed.transform(5), 12); // (5 + 1) * 2
294 /// // add_one.transform(3); // Would not compile - moved
295 /// ```
296 ///
297 /// ## Preserving original with clone
298 ///
299 /// ```rust
300 /// use prism3_function::{BoxTransformer, Transformer};
301 ///
302 /// let double = BoxTransformer::new(|x: i32| x * 2);
303 /// let add_one = BoxTransformer::new(|x: i32| x + 1);
304 ///
305 /// // Clone to preserve original
306 /// let composed = double.compose(add_one.clone());
307 /// assert_eq!(composed.transform(5), 12); // (5 + 1) * 2
308 ///
309 /// // Original still usable
310 /// assert_eq!(add_one.transform(3), 4);
311 /// ```
312 pub fn compose<S, F>(self, before: F) -> BoxTransformer<S, R>
313 where
314 S: 'static,
315 F: Transformer<S, T> + 'static,
316 {
317 let self_fn = self.function;
318 BoxTransformer::new(move |x: S| self_fn(before.transform(x)))
319 }
320
321 /// Creates a conditional transformer
322 ///
323 /// Returns a transformer that only executes when a predicate is satisfied.
324 /// You must call `or_else()` to provide an alternative transformer for when
325 /// the condition is not satisfied.
326 ///
327 /// # Parameters
328 ///
329 /// * `predicate` - The condition to check. **Note: This parameter is passed
330 /// by value and will transfer ownership.** If you need to preserve the
331 /// original predicate, clone it first (if it implements `Clone`). Can be:
332 /// - A closure: `|x: &T| -> bool`
333 /// - A function pointer: `fn(&T) -> bool`
334 /// - A `BoxPredicate<T>`
335 /// - An `RcPredicate<T>`
336 /// - An `ArcPredicate<T>`
337 /// - Any type implementing `Predicate<T>`
338 ///
339 /// # Returns
340 ///
341 /// Returns `BoxConditionalTransformer<T, R>`
342 ///
343 /// # Examples
344 ///
345 /// ## Basic usage with or_else
346 ///
347 /// ```rust
348 /// use prism3_function::{Transformer, BoxTransformer};
349 ///
350 /// let double = BoxTransformer::new(|x: i32| x * 2);
351 /// let identity = BoxTransformer::<i32, i32>::identity();
352 /// let conditional = double.when(|x: &i32| *x > 0).or_else(identity);
353 ///
354 /// assert_eq!(conditional.transform(5), 10);
355 /// assert_eq!(conditional.transform(-5), -5); // identity
356 /// ```
357 ///
358 /// ## Preserving predicate with clone
359 ///
360 /// ```rust
361 /// use prism3_function::{Transformer, BoxTransformer, BoxPredicate};
362 ///
363 /// let double = BoxTransformer::new(|x: i32| x * 2);
364 /// let is_positive = BoxPredicate::new(|x: &i32| *x > 0);
365 ///
366 /// // Clone to preserve original predicate
367 /// let conditional = double.when(is_positive.clone())
368 /// .or_else(BoxTransformer::identity());
369 ///
370 /// assert_eq!(conditional.transform(5), 10);
371 ///
372 /// // Original predicate still usable
373 /// assert!(is_positive.test(&3));
374 /// ```
375 pub fn when<P>(self, predicate: P) -> BoxConditionalTransformer<T, R>
376 where
377 P: Predicate<T> + 'static,
378 {
379 BoxConditionalTransformer {
380 transformer: self,
381 predicate: predicate.into_box(),
382 }
383 }
384}
385
386impl<T, R> BoxTransformer<T, R>
387where
388 T: 'static,
389 R: Clone + 'static,
390{
391 /// Creates a constant transformer
392 ///
393 /// # Examples
394 ///
395 /// ```rust
396 /// use prism3_function::{BoxTransformer, Transformer};
397 ///
398 /// let constant = BoxTransformer::constant("hello");
399 /// assert_eq!(constant.transform(123), "hello");
400 /// ```
401 pub fn constant(value: R) -> BoxTransformer<T, R> {
402 BoxTransformer::new(move |_| value.clone())
403 }
404}
405
406impl<T, R> Transformer<T, R> for BoxTransformer<T, R> {
407 fn transform(&self, input: T) -> R {
408 (self.function)(input)
409 }
410
411 fn into_box(self) -> BoxTransformer<T, R>
412 where
413 T: 'static,
414 R: 'static,
415 {
416 // Zero-cost: directly return itself
417 self
418 }
419
420 fn into_rc(self) -> RcTransformer<T, R>
421 where
422 T: 'static,
423 R: 'static,
424 {
425 RcTransformer {
426 function: Rc::from(self.function),
427 }
428 }
429
430 fn into_arc(self) -> ArcTransformer<T, R>
431 where
432 Self: Send + Sync,
433 T: Send + Sync + 'static,
434 R: Send + Sync + 'static,
435 {
436 unreachable!(
437 "BoxTransformer<T, R> does not implement Send + Sync, so this \
438 method can never be called"
439 )
440 }
441
442 fn into_fn(self) -> impl Fn(T) -> R
443 where
444 T: 'static,
445 R: 'static,
446 {
447 move |t: T| self.transform(t)
448 }
449}
450
451// ============================================================================
452// BoxConditionalTransformer - Box-based Conditional Transformer
453// ============================================================================
454
455/// BoxConditionalTransformer struct
456///
457/// A conditional transformer that only executes when a predicate is satisfied.
458/// Uses `BoxTransformer` and `BoxPredicate` for single ownership semantics.
459///
460/// This type is typically created by calling `BoxTransformer::when()` and is
461/// designed to work with the `or_else()` method to create if-then-else logic.
462///
463/// # Features
464///
465/// - **Single Ownership**: Not cloneable, consumes `self` on use
466/// - **Conditional Execution**: Only transforms when predicate returns `true`
467/// - **Chainable**: Can add `or_else` branch to create if-then-else logic
468/// - **Implements Transformer**: Can be used anywhere a `Transformer` is expected
469///
470/// # Examples
471///
472/// ## With or_else Branch
473///
474/// ```rust
475/// use prism3_function::{Transformer, BoxTransformer};
476///
477/// let double = BoxTransformer::new(|x: i32| x * 2);
478/// let negate = BoxTransformer::new(|x: i32| -x);
479/// let conditional = double.when(|x: &i32| *x > 0).or_else(negate);
480///
481/// assert_eq!(conditional.transform(5), 10); // when branch executed
482/// assert_eq!(conditional.transform(-5), 5); // or_else branch executed
483/// ```
484///
485/// # Author
486///
487/// Haixing Hu
488pub struct BoxConditionalTransformer<T, R> {
489 transformer: BoxTransformer<T, R>,
490 predicate: BoxPredicate<T>,
491}
492
493impl<T, R> BoxConditionalTransformer<T, R>
494where
495 T: 'static,
496 R: 'static,
497{
498 /// Adds an else branch
499 ///
500 /// Executes the original transformer when the condition is satisfied,
501 /// otherwise executes else_transformer.
502 ///
503 /// # Parameters
504 ///
505 /// * `else_transformer` - The transformer for the else branch, can be:
506 /// - Closure: `|x: T| -> R`
507 /// - `BoxTransformer<T, R>`, `RcTransformer<T, R>`, `ArcTransformer<T, R>`
508 /// - Any type implementing `Transformer<T, R>`
509 ///
510 /// # Returns
511 ///
512 /// Returns the composed `BoxTransformer<T, R>`
513 ///
514 /// # Examples
515 ///
516 /// ## Using a closure (recommended)
517 ///
518 /// ```rust
519 /// use prism3_function::{Transformer, BoxTransformer};
520 ///
521 /// let double = BoxTransformer::new(|x: i32| x * 2);
522 /// let conditional = double.when(|x: &i32| *x > 0).or_else(|x: i32| -x);
523 ///
524 /// assert_eq!(conditional.transform(5), 10); // Condition satisfied, execute double
525 /// assert_eq!(conditional.transform(-5), 5); // Condition not satisfied, execute negate
526 /// ```
527 pub fn or_else<F>(self, else_transformer: F) -> BoxTransformer<T, R>
528 where
529 F: Transformer<T, R> + 'static,
530 {
531 let pred = self.predicate;
532 let then_trans = self.transformer;
533 BoxTransformer::new(move |t| {
534 if pred.test(&t) {
535 then_trans.transform(t)
536 } else {
537 else_transformer.transform(t)
538 }
539 })
540 }
541}
542
543// ============================================================================
544// ArcTransformer - Arc<dyn Fn(T) -> R + Send + Sync>
545// ============================================================================
546
547/// ArcTransformer - thread-safe transformer wrapper
548///
549/// A thread-safe, clonable transformer wrapper suitable for multi-threaded
550/// scenarios. Can be called multiple times and shared across threads.
551///
552/// # Features
553///
554/// - **Based on**: `Arc<dyn Fn(T) -> R + Send + Sync>`
555/// - **Ownership**: Shared ownership via reference counting
556/// - **Reusability**: Can be called multiple times (each call consumes its
557/// input)
558/// - **Thread Safety**: Thread-safe (`Send + Sync` required)
559/// - **Clonable**: Cheap cloning via `Arc::clone`
560///
561/// # Author
562///
563/// Hu Haixing
564pub struct ArcTransformer<T, R> {
565 function: Arc<dyn Fn(T) -> R + Send + Sync>,
566}
567
568impl<T, R> ArcTransformer<T, R>
569where
570 T: Send + Sync + 'static,
571 R: 'static,
572{
573 /// Creates a new ArcTransformer
574 ///
575 /// # Parameters
576 ///
577 /// * `f` - The closure or function to wrap (must be Send + Sync)
578 ///
579 /// # Examples
580 ///
581 /// ```rust
582 /// use prism3_function::{ArcTransformer, Transformer};
583 ///
584 /// let double = ArcTransformer::new(|x: i32| x * 2);
585 /// assert_eq!(double.transform(21), 42);
586 /// ```
587 pub fn new<F>(f: F) -> Self
588 where
589 F: Fn(T) -> R + Send + Sync + 'static,
590 {
591 ArcTransformer {
592 function: Arc::new(f),
593 }
594 }
595
596 /// Creates an identity transformer
597 ///
598 /// # Examples
599 ///
600 /// ```rust
601 /// use prism3_function::{ArcTransformer, Transformer};
602 ///
603 /// let identity = ArcTransformer::<i32, i32>::identity();
604 /// assert_eq!(identity.transform(42), 42);
605 /// ```
606 pub fn identity() -> ArcTransformer<T, T> {
607 ArcTransformer::new(|x| x)
608 }
609
610 /// Chain composition - applies self first, then after
611 ///
612 /// Creates a new transformer that applies this transformer first, then
613 /// applies the after transformer to the result. Uses &self, so original
614 /// transformer remains usable.
615 ///
616 /// # Type Parameters
617 ///
618 /// * `S` - The output type of the after transformer
619 /// * `F` - The type of the after transformer (must implement
620 /// Transformer<R, S>)
621 ///
622 /// # Parameters
623 ///
624 /// * `after` - The transformer to apply after self. **Note: This parameter
625 /// is passed by value and will transfer ownership.** If you need to
626 /// preserve the original transformer, clone it first (if it implements
627 /// `Clone`). Can be:
628 /// - A closure: `|x: R| -> S`
629 /// - A function pointer: `fn(R) -> S`
630 /// - A `BoxTransformer<R, S>`
631 /// - An `RcTransformer<R, S>`
632 /// - An `ArcTransformer<R, S>` (will be moved)
633 /// - Any type implementing `Transformer<R, S> + Send + Sync`
634 ///
635 /// # Returns
636 ///
637 /// A new ArcTransformer representing the composition
638 ///
639 /// # Examples
640 ///
641 /// ## Direct value passing (ownership transfer)
642 ///
643 /// ```rust
644 /// use prism3_function::{ArcTransformer, Transformer};
645 ///
646 /// let double = ArcTransformer::new(|x: i32| x * 2);
647 /// let to_string = ArcTransformer::new(|x: i32| x.to_string());
648 ///
649 /// // to_string is moved here
650 /// let composed = double.and_then(to_string);
651 ///
652 /// // Original double transformer still usable (uses &self)
653 /// assert_eq!(double.transform(21), 42);
654 /// assert_eq!(composed.transform(21), "42");
655 /// // to_string.transform(5); // Would not compile - moved
656 /// ```
657 ///
658 /// ## Preserving original with clone
659 ///
660 /// ```rust
661 /// use prism3_function::{ArcTransformer, Transformer};
662 ///
663 /// let double = ArcTransformer::new(|x: i32| x * 2);
664 /// let to_string = ArcTransformer::new(|x: i32| x.to_string());
665 ///
666 /// // Clone to preserve original
667 /// let composed = double.and_then(to_string.clone());
668 /// assert_eq!(composed.transform(21), "42");
669 ///
670 /// // Both originals still usable
671 /// assert_eq!(double.transform(21), 42);
672 /// assert_eq!(to_string.transform(5), "5");
673 /// ```
674 pub fn and_then<S, F>(&self, after: F) -> ArcTransformer<T, S>
675 where
676 S: Send + Sync + 'static,
677 F: Transformer<R, S> + Send + Sync + 'static,
678 {
679 let self_clone = Arc::clone(&self.function);
680 ArcTransformer {
681 function: Arc::new(move |x: T| after.transform(self_clone(x))),
682 }
683 }
684
685 /// Reverse composition - applies before first, then self
686 ///
687 /// Creates a new transformer that applies the before transformer first,
688 /// then applies this transformer to the result. Uses &self, so original
689 /// transformer remains usable.
690 ///
691 /// # Type Parameters
692 ///
693 /// * `S` - The input type of the before transformer
694 /// * `F` - The type of the before transformer (must implement
695 /// Transformer<S, T>)
696 ///
697 /// # Parameters
698 ///
699 /// * `before` - The transformer to apply before self. **Note: This parameter
700 /// is passed by value and will transfer ownership.** If you need to
701 /// preserve the original transformer, clone it first (if it implements
702 /// `Clone`). Can be:
703 /// - A closure: `|x: S| -> T`
704 /// - A function pointer: `fn(S) -> T`
705 /// - A `BoxTransformer<S, T>`
706 /// - An `RcTransformer<S, T>`
707 /// - An `ArcTransformer<S, T>` (will be moved)
708 /// - Any type implementing `Transformer<S, T> + Send + Sync`
709 ///
710 /// # Returns
711 ///
712 /// A new ArcTransformer representing the composition
713 ///
714 /// # Examples
715 ///
716 /// ## Direct value passing (ownership transfer)
717 ///
718 /// ```rust
719 /// use prism3_function::{ArcTransformer, Transformer};
720 ///
721 /// let double = ArcTransformer::new(|x: i32| x * 2);
722 /// let add_one = ArcTransformer::new(|x: i32| x + 1);
723 ///
724 /// // add_one is moved here
725 /// let composed = double.compose(add_one);
726 /// assert_eq!(composed.transform(5), 12); // (5 + 1) * 2
727 /// // add_one.transform(3); // Would not compile - moved
728 /// ```
729 ///
730 /// ## Preserving original with clone
731 ///
732 /// ```rust
733 /// use prism3_function::{ArcTransformer, Transformer};
734 ///
735 /// let double = ArcTransformer::new(|x: i32| x * 2);
736 /// let add_one = ArcTransformer::new(|x: i32| x + 1);
737 ///
738 /// // Clone to preserve original
739 /// let composed = double.compose(add_one.clone());
740 /// assert_eq!(composed.transform(5), 12); // (5 + 1) * 2
741 ///
742 /// // Both originals still usable
743 /// assert_eq!(double.transform(10), 20);
744 /// assert_eq!(add_one.transform(3), 4);
745 /// ```
746 pub fn compose<S, F>(&self, before: F) -> ArcTransformer<S, R>
747 where
748 S: Send + Sync + 'static,
749 F: Transformer<S, T> + Send + Sync + 'static,
750 {
751 let self_clone = Arc::clone(&self.function);
752 ArcTransformer {
753 function: Arc::new(move |x: S| self_clone(before.transform(x))),
754 }
755 }
756
757 /// Creates a conditional transformer (thread-safe version)
758 ///
759 /// Returns a transformer that only executes when a predicate is satisfied.
760 /// You must call `or_else()` to provide an alternative transformer.
761 ///
762 /// # Parameters
763 ///
764 /// * `predicate` - The condition to check. **Note: This parameter is passed
765 /// by value and will transfer ownership.** If you need to preserve the
766 /// original predicate, clone it first (if it implements `Clone`). Must be
767 /// `Send + Sync`, can be:
768 /// - A closure: `|x: &T| -> bool` (requires `Send + Sync`)
769 /// - A function pointer: `fn(&T) -> bool`
770 /// - An `ArcPredicate<T>`
771 /// - Any type implementing `Predicate<T> + Send + Sync`
772 ///
773 /// # Returns
774 ///
775 /// Returns `ArcConditionalTransformer<T, R>`
776 ///
777 /// # Examples
778 ///
779 /// ## Basic usage with or_else
780 ///
781 /// ```rust
782 /// use prism3_function::{Transformer, ArcTransformer};
783 ///
784 /// let double = ArcTransformer::new(|x: i32| x * 2);
785 /// let identity = ArcTransformer::<i32, i32>::identity();
786 /// let conditional = double.when(|x: &i32| *x > 0).or_else(identity);
787 ///
788 /// let conditional_clone = conditional.clone();
789 ///
790 /// assert_eq!(conditional.transform(5), 10);
791 /// assert_eq!(conditional_clone.transform(-5), -5);
792 /// ```
793 ///
794 /// ## Preserving predicate with clone
795 ///
796 /// ```rust
797 /// use prism3_function::{Transformer, ArcTransformer, ArcPredicate};
798 ///
799 /// let double = ArcTransformer::new(|x: i32| x * 2);
800 /// let is_positive = ArcPredicate::new(|x: &i32| *x > 0);
801 ///
802 /// // Clone to preserve original predicate
803 /// let conditional = double.when(is_positive.clone())
804 /// .or_else(ArcTransformer::identity());
805 ///
806 /// assert_eq!(conditional.transform(5), 10);
807 ///
808 /// // Original predicate still usable
809 /// assert!(is_positive.test(&3));
810 /// ```
811 pub fn when<P>(self, predicate: P) -> ArcConditionalTransformer<T, R>
812 where
813 P: Predicate<T> + Send + Sync + 'static,
814 {
815 ArcConditionalTransformer {
816 transformer: self,
817 predicate: predicate.into_arc(),
818 }
819 }
820}
821
822impl<T, R> ArcTransformer<T, R>
823where
824 T: Send + Sync + 'static,
825 R: Clone + 'static,
826{
827 /// Creates a constant transformer
828 ///
829 /// # Examples
830 ///
831 /// ```rust
832 /// use prism3_function::{ArcTransformer, Transformer};
833 ///
834 /// let constant = ArcTransformer::constant("hello");
835 /// assert_eq!(constant.transform(123), "hello");
836 /// ```
837 pub fn constant(value: R) -> ArcTransformer<T, R>
838 where
839 R: Send + Sync,
840 {
841 ArcTransformer::new(move |_| value.clone())
842 }
843}
844
845impl<T, R> Transformer<T, R> for ArcTransformer<T, R> {
846 fn transform(&self, input: T) -> R {
847 (self.function)(input)
848 }
849
850 fn into_box(self) -> BoxTransformer<T, R>
851 where
852 T: 'static,
853 R: 'static,
854 {
855 BoxTransformer {
856 function: Box::new(move |x| self.transform(x)),
857 }
858 }
859
860 fn into_rc(self) -> RcTransformer<T, R>
861 where
862 T: 'static,
863 R: 'static,
864 {
865 RcTransformer {
866 function: Rc::new(move |x| self.transform(x)),
867 }
868 }
869
870 fn into_arc(self) -> ArcTransformer<T, R>
871 where
872 T: Send + Sync + 'static,
873 R: Send + Sync + 'static,
874 {
875 // Zero-cost: directly return itself
876 self
877 }
878
879 fn into_fn(self) -> impl Fn(T) -> R
880 where
881 T: 'static,
882 R: 'static,
883 {
884 move |t: T| self.transform(t)
885 }
886}
887
888impl<T, R> Clone for ArcTransformer<T, R> {
889 fn clone(&self) -> Self {
890 ArcTransformer {
891 function: Arc::clone(&self.function),
892 }
893 }
894}
895
896// ============================================================================
897// ArcConditionalTransformer - Arc-based Conditional Transformer
898// ============================================================================
899
900/// ArcConditionalTransformer struct
901///
902/// A thread-safe conditional transformer that only executes when a predicate is
903/// satisfied. Uses `ArcTransformer` and `ArcPredicate` for shared ownership
904/// across threads.
905///
906/// This type is typically created by calling `ArcTransformer::when()` and is
907/// designed to work with the `or_else()` method to create if-then-else logic.
908///
909/// # Features
910///
911/// - **Shared Ownership**: Cloneable via `Arc`, multiple owners allowed
912/// - **Thread-Safe**: Implements `Send + Sync`, safe for concurrent use
913/// - **Conditional Execution**: Only transforms when predicate returns `true`
914/// - **Chainable**: Can add `or_else` branch to create if-then-else logic
915///
916/// # Examples
917///
918/// ```rust
919/// use prism3_function::{Transformer, ArcTransformer};
920///
921/// let double = ArcTransformer::new(|x: i32| x * 2);
922/// let identity = ArcTransformer::<i32, i32>::identity();
923/// let conditional = double.when(|x: &i32| *x > 0).or_else(identity);
924///
925/// let conditional_clone = conditional.clone();
926///
927/// assert_eq!(conditional.transform(5), 10);
928/// assert_eq!(conditional_clone.transform(-5), -5);
929/// ```
930///
931/// # Author
932///
933/// Haixing Hu
934pub struct ArcConditionalTransformer<T, R> {
935 transformer: ArcTransformer<T, R>,
936 predicate: ArcPredicate<T>,
937}
938
939impl<T, R> ArcConditionalTransformer<T, R>
940where
941 T: Send + Sync + 'static,
942 R: 'static,
943{
944 /// Adds an else branch (thread-safe version)
945 ///
946 /// Executes the original transformer when the condition is satisfied,
947 /// otherwise executes else_transformer.
948 ///
949 /// # Parameters
950 ///
951 /// * `else_transformer` - The transformer for the else branch, can be:
952 /// - Closure: `|x: T| -> R` (must be `Send + Sync`)
953 /// - `ArcTransformer<T, R>`, `BoxTransformer<T, R>`
954 /// - Any type implementing `Transformer<T, R> + Send + Sync`
955 ///
956 /// # Returns
957 ///
958 /// Returns the composed `ArcTransformer<T, R>`
959 ///
960 /// # Examples
961 ///
962 /// ## Using a closure (recommended)
963 ///
964 /// ```rust
965 /// use prism3_function::{Transformer, ArcTransformer};
966 ///
967 /// let double = ArcTransformer::new(|x: i32| x * 2);
968 /// let conditional = double.when(|x: &i32| *x > 0).or_else(|x: i32| -x);
969 ///
970 /// assert_eq!(conditional.transform(5), 10);
971 /// assert_eq!(conditional.transform(-5), 5);
972 /// ```
973 pub fn or_else<F>(self, else_transformer: F) -> ArcTransformer<T, R>
974 where
975 F: Transformer<T, R> + Send + Sync + 'static,
976 R: Send + Sync,
977 {
978 let pred = self.predicate;
979 let then_trans = self.transformer;
980 ArcTransformer::new(move |t| {
981 if pred.test(&t) {
982 then_trans.transform(t)
983 } else {
984 else_transformer.transform(t)
985 }
986 })
987 }
988}
989
990impl<T, R> Clone for ArcConditionalTransformer<T, R> {
991 /// Clones the conditional transformer
992 ///
993 /// Creates a new instance that shares the underlying transformer and
994 /// predicate with the original instance.
995 fn clone(&self) -> Self {
996 Self {
997 transformer: self.transformer.clone(),
998 predicate: self.predicate.clone(),
999 }
1000 }
1001}
1002
1003// ============================================================================
1004// RcTransformer - Rc<dyn Fn(T) -> R>
1005// ============================================================================
1006
1007/// RcTransformer - single-threaded transformer wrapper
1008///
1009/// A single-threaded, clonable transformer wrapper optimized for scenarios
1010/// that require sharing without thread-safety overhead.
1011///
1012/// # Features
1013///
1014/// - **Based on**: `Rc<dyn Fn(T) -> R>`
1015/// - **Ownership**: Shared ownership via reference counting (non-atomic)
1016/// - **Reusability**: Can be called multiple times (each call consumes its
1017/// input)
1018/// - **Thread Safety**: Not thread-safe (no `Send + Sync`)
1019/// - **Clonable**: Cheap cloning via `Rc::clone`
1020///
1021/// # Author
1022///
1023/// Hu Haixing
1024pub struct RcTransformer<T, R> {
1025 function: Rc<dyn Fn(T) -> R>,
1026}
1027
1028impl<T, R> RcTransformer<T, R>
1029where
1030 T: 'static,
1031 R: 'static,
1032{
1033 /// Creates a new RcTransformer
1034 ///
1035 /// # Parameters
1036 ///
1037 /// * `f` - The closure or function to wrap
1038 ///
1039 /// # Examples
1040 ///
1041 /// ```rust
1042 /// use prism3_function::{RcTransformer, Transformer};
1043 ///
1044 /// let double = RcTransformer::new(|x: i32| x * 2);
1045 /// assert_eq!(double.transform(21), 42);
1046 /// ```
1047 pub fn new<F>(f: F) -> Self
1048 where
1049 F: Fn(T) -> R + 'static,
1050 {
1051 RcTransformer {
1052 function: Rc::new(f),
1053 }
1054 }
1055
1056 /// Creates an identity transformer
1057 ///
1058 /// # Examples
1059 ///
1060 /// ```rust
1061 /// use prism3_function::{RcTransformer, Transformer};
1062 ///
1063 /// let identity = RcTransformer::<i32, i32>::identity();
1064 /// assert_eq!(identity.transform(42), 42);
1065 /// ```
1066 pub fn identity() -> RcTransformer<T, T> {
1067 RcTransformer::new(|x| x)
1068 }
1069
1070 /// Chain composition - applies self first, then after
1071 ///
1072 /// Creates a new transformer that applies this transformer first, then
1073 /// applies the after transformer to the result. Uses &self, so original
1074 /// transformer remains usable.
1075 ///
1076 /// # Type Parameters
1077 ///
1078 /// * `S` - The output type of the after transformer
1079 /// * `F` - The type of the after transformer (must implement
1080 /// Transformer<R, S>)
1081 ///
1082 /// # Parameters
1083 ///
1084 /// * `after` - The transformer to apply after self. **Note: This parameter
1085 /// is passed by value and will transfer ownership.** If you need to
1086 /// preserve the original transformer, clone it first (if it implements
1087 /// `Clone`). Can be:
1088 /// - A closure: `|x: R| -> S`
1089 /// - A function pointer: `fn(R) -> S`
1090 /// - A `BoxTransformer<R, S>`
1091 /// - An `RcTransformer<R, S>` (will be moved)
1092 /// - An `ArcTransformer<R, S>`
1093 /// - Any type implementing `Transformer<R, S>`
1094 ///
1095 /// # Returns
1096 ///
1097 /// A new RcTransformer representing the composition
1098 ///
1099 /// # Examples
1100 ///
1101 /// ## Direct value passing (ownership transfer)
1102 ///
1103 /// ```rust
1104 /// use prism3_function::{RcTransformer, Transformer};
1105 ///
1106 /// let double = RcTransformer::new(|x: i32| x * 2);
1107 /// let to_string = RcTransformer::new(|x: i32| x.to_string());
1108 ///
1109 /// // to_string is moved here
1110 /// let composed = double.and_then(to_string);
1111 ///
1112 /// // Original double transformer still usable (uses &self)
1113 /// assert_eq!(double.transform(21), 42);
1114 /// assert_eq!(composed.transform(21), "42");
1115 /// // to_string.transform(5); // Would not compile - moved
1116 /// ```
1117 ///
1118 /// ## Preserving original with clone
1119 ///
1120 /// ```rust
1121 /// use prism3_function::{RcTransformer, Transformer};
1122 ///
1123 /// let double = RcTransformer::new(|x: i32| x * 2);
1124 /// let to_string = RcTransformer::new(|x: i32| x.to_string());
1125 ///
1126 /// // Clone to preserve original
1127 /// let composed = double.and_then(to_string.clone());
1128 /// assert_eq!(composed.transform(21), "42");
1129 ///
1130 /// // Both originals still usable
1131 /// assert_eq!(double.transform(21), 42);
1132 /// assert_eq!(to_string.transform(5), "5");
1133 /// ```
1134 pub fn and_then<S, F>(&self, after: F) -> RcTransformer<T, S>
1135 where
1136 S: 'static,
1137 F: Transformer<R, S> + 'static,
1138 {
1139 let self_clone = Rc::clone(&self.function);
1140 RcTransformer {
1141 function: Rc::new(move |x: T| after.transform(self_clone(x))),
1142 }
1143 }
1144
1145 /// Reverse composition - applies before first, then self
1146 ///
1147 /// Creates a new transformer that applies the before transformer first,
1148 /// then applies this transformer to the result. Uses &self, so original
1149 /// transformer remains usable.
1150 ///
1151 /// # Type Parameters
1152 ///
1153 /// * `S` - The input type of the before transformer
1154 /// * `F` - The type of the before transformer (must implement
1155 /// Transformer<S, T>)
1156 ///
1157 /// # Parameters
1158 ///
1159 /// * `before` - The transformer to apply before self. **Note: This parameter
1160 /// is passed by value and will transfer ownership.** If you need to
1161 /// preserve the original transformer, clone it first (if it implements
1162 /// `Clone`). Can be:
1163 /// - A closure: `|x: S| -> T`
1164 /// - A function pointer: `fn(S) -> T`
1165 /// - A `BoxTransformer<S, T>`
1166 /// - An `RcTransformer<S, T>` (will be moved)
1167 /// - An `ArcTransformer<S, T>`
1168 /// - Any type implementing `Transformer<S, T>`
1169 ///
1170 /// # Returns
1171 ///
1172 /// A new RcTransformer representing the composition
1173 ///
1174 /// # Examples
1175 ///
1176 /// ## Direct value passing (ownership transfer)
1177 ///
1178 /// ```rust
1179 /// use prism3_function::{RcTransformer, Transformer};
1180 ///
1181 /// let double = RcTransformer::new(|x: i32| x * 2);
1182 /// let add_one = RcTransformer::new(|x: i32| x + 1);
1183 ///
1184 /// // add_one is moved here
1185 /// let composed = double.compose(add_one);
1186 /// assert_eq!(composed.transform(5), 12); // (5 + 1) * 2
1187 /// // add_one.transform(3); // Would not compile - moved
1188 /// ```
1189 ///
1190 /// ## Preserving original with clone
1191 ///
1192 /// ```rust
1193 /// use prism3_function::{RcTransformer, Transformer};
1194 ///
1195 /// let double = RcTransformer::new(|x: i32| x * 2);
1196 /// let add_one = RcTransformer::new(|x: i32| x + 1);
1197 ///
1198 /// // Clone to preserve original
1199 /// let composed = double.compose(add_one.clone());
1200 /// assert_eq!(composed.transform(5), 12); // (5 + 1) * 2
1201 ///
1202 /// // Both originals still usable
1203 /// assert_eq!(double.transform(10), 20);
1204 /// assert_eq!(add_one.transform(3), 4);
1205 /// ```
1206 pub fn compose<S, F>(&self, before: F) -> RcTransformer<S, R>
1207 where
1208 S: 'static,
1209 F: Transformer<S, T> + 'static,
1210 {
1211 let self_clone = Rc::clone(&self.function);
1212 RcTransformer {
1213 function: Rc::new(move |x: S| self_clone(before.transform(x))),
1214 }
1215 }
1216
1217 /// Creates a conditional transformer (single-threaded shared version)
1218 ///
1219 /// Returns a transformer that only executes when a predicate is satisfied.
1220 /// You must call `or_else()` to provide an alternative transformer.
1221 ///
1222 /// # Parameters
1223 ///
1224 /// * `predicate` - The condition to check. **Note: This parameter is passed
1225 /// by value and will transfer ownership.** If you need to preserve the
1226 /// original predicate, clone it first (if it implements `Clone`). Can be:
1227 /// - A closure: `|x: &T| -> bool`
1228 /// - A function pointer: `fn(&T) -> bool`
1229 /// - A `BoxPredicate<T>`
1230 /// - An `RcPredicate<T>`
1231 /// - An `ArcPredicate<T>`
1232 /// - Any type implementing `Predicate<T>`
1233 ///
1234 /// # Returns
1235 ///
1236 /// Returns `RcConditionalTransformer<T, R>`
1237 ///
1238 /// # Examples
1239 ///
1240 /// ## Basic usage with or_else
1241 ///
1242 /// ```rust
1243 /// use prism3_function::{Transformer, RcTransformer};
1244 ///
1245 /// let double = RcTransformer::new(|x: i32| x * 2);
1246 /// let identity = RcTransformer::<i32, i32>::identity();
1247 /// let conditional = double.when(|x: &i32| *x > 0).or_else(identity);
1248 ///
1249 /// let conditional_clone = conditional.clone();
1250 ///
1251 /// assert_eq!(conditional.transform(5), 10);
1252 /// assert_eq!(conditional_clone.transform(-5), -5);
1253 /// ```
1254 ///
1255 /// ## Preserving predicate with clone
1256 ///
1257 /// ```rust
1258 /// use prism3_function::{Transformer, RcTransformer, RcPredicate};
1259 ///
1260 /// let double = RcTransformer::new(|x: i32| x * 2);
1261 /// let is_positive = RcPredicate::new(|x: &i32| *x > 0);
1262 ///
1263 /// // Clone to preserve original predicate
1264 /// let conditional = double.when(is_positive.clone())
1265 /// .or_else(RcTransformer::identity());
1266 ///
1267 /// assert_eq!(conditional.transform(5), 10);
1268 ///
1269 /// // Original predicate still usable
1270 /// assert!(is_positive.test(&3));
1271 /// ```
1272 pub fn when<P>(self, predicate: P) -> RcConditionalTransformer<T, R>
1273 where
1274 P: Predicate<T> + 'static,
1275 {
1276 RcConditionalTransformer {
1277 transformer: self,
1278 predicate: predicate.into_rc(),
1279 }
1280 }
1281}
1282
1283impl<T, R> RcTransformer<T, R>
1284where
1285 T: 'static,
1286 R: Clone + 'static,
1287{
1288 /// Creates a constant transformer
1289 ///
1290 /// # Examples
1291 ///
1292 /// ```rust
1293 /// use prism3_function::{RcTransformer, Transformer};
1294 ///
1295 /// let constant = RcTransformer::constant("hello");
1296 /// assert_eq!(constant.transform(123), "hello");
1297 /// ```
1298 pub fn constant(value: R) -> RcTransformer<T, R> {
1299 RcTransformer::new(move |_| value.clone())
1300 }
1301}
1302
1303impl<T, R> Transformer<T, R> for RcTransformer<T, R> {
1304 fn transform(&self, input: T) -> R {
1305 (self.function)(input)
1306 }
1307
1308 fn into_box(self) -> BoxTransformer<T, R>
1309 where
1310 T: 'static,
1311 R: 'static,
1312 {
1313 BoxTransformer {
1314 function: Box::new(move |x| self.transform(x)),
1315 }
1316 }
1317
1318 fn into_rc(self) -> RcTransformer<T, R>
1319 where
1320 T: 'static,
1321 R: 'static,
1322 {
1323 // Zero-cost: directly return itself
1324 self
1325 }
1326
1327 fn into_arc(self) -> ArcTransformer<T, R>
1328 where
1329 Self: Send + Sync,
1330 T: Send + Sync + 'static,
1331 R: Send + Sync + 'static,
1332 {
1333 unreachable!(
1334 "RcTransformer cannot be converted to ArcTransformer because Rc \
1335 is not Send + Sync"
1336 )
1337 }
1338
1339 fn into_fn(self) -> impl Fn(T) -> R
1340 where
1341 T: 'static,
1342 R: 'static,
1343 {
1344 move |t: T| self.transform(t)
1345 }
1346}
1347
1348impl<T, R> Clone for RcTransformer<T, R> {
1349 fn clone(&self) -> Self {
1350 RcTransformer {
1351 function: Rc::clone(&self.function),
1352 }
1353 }
1354}
1355
1356// ============================================================================
1357// RcConditionalTransformer - Rc-based Conditional Transformer
1358// ============================================================================
1359
1360/// RcConditionalTransformer struct
1361///
1362/// A single-threaded conditional transformer that only executes when a
1363/// predicate is satisfied. Uses `RcTransformer` and `RcPredicate` for shared
1364/// ownership within a single thread.
1365///
1366/// This type is typically created by calling `RcTransformer::when()` and is
1367/// designed to work with the `or_else()` method to create if-then-else logic.
1368///
1369/// # Features
1370///
1371/// - **Shared Ownership**: Cloneable via `Rc`, multiple owners allowed
1372/// - **Single-Threaded**: Not thread-safe, cannot be sent across threads
1373/// - **Conditional Execution**: Only transforms when predicate returns `true`
1374/// - **No Lock Overhead**: More efficient than `ArcConditionalTransformer`
1375///
1376/// # Examples
1377///
1378/// ```rust
1379/// use prism3_function::{Transformer, RcTransformer};
1380///
1381/// let double = RcTransformer::new(|x: i32| x * 2);
1382/// let identity = RcTransformer::<i32, i32>::identity();
1383/// let conditional = double.when(|x: &i32| *x > 0).or_else(identity);
1384///
1385/// let conditional_clone = conditional.clone();
1386///
1387/// assert_eq!(conditional.transform(5), 10);
1388/// assert_eq!(conditional_clone.transform(-5), -5);
1389/// ```
1390///
1391/// # Author
1392///
1393/// Haixing Hu
1394pub struct RcConditionalTransformer<T, R> {
1395 transformer: RcTransformer<T, R>,
1396 predicate: RcPredicate<T>,
1397}
1398
1399impl<T, R> RcConditionalTransformer<T, R>
1400where
1401 T: 'static,
1402 R: 'static,
1403{
1404 /// Adds an else branch (single-threaded shared version)
1405 ///
1406 /// Executes the original transformer when the condition is satisfied,
1407 /// otherwise executes else_transformer.
1408 ///
1409 /// # Parameters
1410 ///
1411 /// * `else_transformer` - The transformer for the else branch, can be:
1412 /// - Closure: `|x: T| -> R`
1413 /// - `RcTransformer<T, R>`, `BoxTransformer<T, R>`
1414 /// - Any type implementing `Transformer<T, R>`
1415 ///
1416 /// # Returns
1417 ///
1418 /// Returns the composed `RcTransformer<T, R>`
1419 ///
1420 /// # Examples
1421 ///
1422 /// ## Using a closure (recommended)
1423 ///
1424 /// ```rust
1425 /// use prism3_function::{Transformer, RcTransformer};
1426 ///
1427 /// let double = RcTransformer::new(|x: i32| x * 2);
1428 /// let conditional = double.when(|x: &i32| *x > 0).or_else(|x: i32| -x);
1429 ///
1430 /// assert_eq!(conditional.transform(5), 10);
1431 /// assert_eq!(conditional.transform(-5), 5);
1432 /// ```
1433 pub fn or_else<F>(self, else_transformer: F) -> RcTransformer<T, R>
1434 where
1435 F: Transformer<T, R> + 'static,
1436 {
1437 let pred = self.predicate;
1438 let then_trans = self.transformer;
1439 RcTransformer::new(move |t| {
1440 if pred.test(&t) {
1441 then_trans.transform(t)
1442 } else {
1443 else_transformer.transform(t)
1444 }
1445 })
1446 }
1447}
1448
1449impl<T, R> Clone for RcConditionalTransformer<T, R> {
1450 /// Clones the conditional transformer
1451 ///
1452 /// Creates a new instance that shares the underlying transformer and
1453 /// predicate with the original instance.
1454 fn clone(&self) -> Self {
1455 Self {
1456 transformer: self.transformer.clone(),
1457 predicate: self.predicate.clone(),
1458 }
1459 }
1460}
1461
1462// ============================================================================
1463// Blanket implementation for standard Fn trait
1464// ============================================================================
1465
1466/// Implement Transformer<T, R> for any type that implements Fn(T) -> R
1467///
1468/// This allows closures and function pointers to be used directly with our
1469/// Transformer trait without wrapping.
1470///
1471/// # Examples
1472///
1473/// ```rust
1474/// use prism3_function::Transformer;
1475///
1476/// fn double(x: i32) -> i32 { x * 2 }
1477///
1478/// assert_eq!(double.transform(21), 42);
1479///
1480/// let triple = |x: i32| x * 3;
1481/// assert_eq!(triple.transform(14), 42);
1482/// ```
1483///
1484/// # Author
1485///
1486/// Hu Haixing
1487impl<F, T, R> Transformer<T, R> for F
1488where
1489 F: Fn(T) -> R,
1490 T: 'static,
1491 R: 'static,
1492{
1493 fn transform(&self, input: T) -> R {
1494 self(input)
1495 }
1496
1497 fn into_box(self) -> BoxTransformer<T, R>
1498 where
1499 Self: Sized + 'static,
1500 {
1501 BoxTransformer::new(self)
1502 }
1503
1504 fn into_rc(self) -> RcTransformer<T, R>
1505 where
1506 Self: Sized + 'static,
1507 {
1508 RcTransformer::new(self)
1509 }
1510
1511 fn into_arc(self) -> ArcTransformer<T, R>
1512 where
1513 Self: Sized + Send + Sync + 'static,
1514 T: Send + Sync + 'static,
1515 R: Send + Sync + 'static,
1516 {
1517 ArcTransformer::new(self)
1518 }
1519
1520 fn into_fn(self) -> impl Fn(T) -> R
1521 where
1522 Self: Sized + 'static,
1523 {
1524 move |t: T| self(t)
1525 }
1526}
1527
1528// ============================================================================
1529// FnTransformerOps - Extension trait for closure transformers
1530// ============================================================================
1531
1532/// Extension trait for closures implementing `Fn(T) -> R`
1533///
1534/// Provides composition methods (`and_then`, `compose`, `when`) for closures
1535/// and function pointers without requiring explicit wrapping in
1536/// `BoxTransformer`, `RcTransformer`, or `ArcTransformer`.
1537///
1538/// This trait is automatically implemented for all closures and function
1539/// pointers that implement `Fn(T) -> R`.
1540///
1541/// # Design Rationale
1542///
1543/// While closures automatically implement `Transformer<T, R>` through blanket
1544/// implementation, they don't have access to instance methods like `and_then`,
1545/// `compose`, and `when`. This extension trait provides those methods,
1546/// returning `BoxTransformer` for maximum flexibility.
1547///
1548/// # Examples
1549///
1550/// ## Chain composition with and_then
1551///
1552/// ```rust
1553/// use prism3_function::{Transformer, FnTransformerOps};
1554///
1555/// let double = |x: i32| x * 2;
1556/// let to_string = |x: i32| x.to_string();
1557///
1558/// let composed = double.and_then(to_string);
1559/// assert_eq!(composed.transform(21), "42");
1560/// ```
1561///
1562/// ## Reverse composition with compose
1563///
1564/// ```rust
1565/// use prism3_function::{Transformer, FnTransformerOps};
1566///
1567/// let double = |x: i32| x * 2;
1568/// let add_one = |x: i32| x + 1;
1569///
1570/// let composed = double.compose(add_one);
1571/// assert_eq!(composed.transform(5), 12); // (5 + 1) * 2
1572/// ```
1573///
1574/// ## Conditional transformation with when
1575///
1576/// ```rust
1577/// use prism3_function::{Transformer, FnTransformerOps};
1578///
1579/// let double = |x: i32| x * 2;
1580/// let conditional = double.when(|x: &i32| *x > 0).or_else(|x: i32| -x);
1581///
1582/// assert_eq!(conditional.transform(5), 10);
1583/// assert_eq!(conditional.transform(-5), 5);
1584/// ```
1585///
1586/// # Author
1587///
1588/// Hu Haixing
1589pub trait FnTransformerOps<T, R>: Fn(T) -> R + Sized + 'static {
1590 /// Chain composition - applies self first, then after
1591 ///
1592 /// Creates a new transformer that applies this transformer first, then
1593 /// applies the after transformer to the result. Consumes self and returns
1594 /// a `BoxTransformer`.
1595 ///
1596 /// # Type Parameters
1597 ///
1598 /// * `S` - The output type of the after transformer
1599 /// * `F` - The type of the after transformer (must implement Transformer<R, S>)
1600 ///
1601 /// # Parameters
1602 ///
1603 /// * `after` - The transformer to apply after self. **Note: This parameter
1604 /// is passed by value and will transfer ownership.** If you need to
1605 /// preserve the original transformer, clone it first (if it implements
1606 /// `Clone`). Can be:
1607 /// - A closure: `|x: R| -> S`
1608 /// - A function pointer: `fn(R) -> S`
1609 /// - A `BoxTransformer<R, S>`
1610 /// - An `RcTransformer<R, S>`
1611 /// - An `ArcTransformer<R, S>`
1612 /// - Any type implementing `Transformer<R, S>`
1613 ///
1614 /// # Returns
1615 ///
1616 /// A new `BoxTransformer<T, S>` representing the composition
1617 ///
1618 /// # Examples
1619 ///
1620 /// ## Direct value passing (ownership transfer)
1621 ///
1622 /// ```rust
1623 /// use prism3_function::{Transformer, FnTransformerOps, BoxTransformer};
1624 ///
1625 /// let double = |x: i32| x * 2;
1626 /// let to_string = BoxTransformer::new(|x: i32| x.to_string());
1627 ///
1628 /// // to_string is moved here
1629 /// let composed = double.and_then(to_string);
1630 /// assert_eq!(composed.transform(21), "42");
1631 /// // to_string.transform(5); // Would not compile - moved
1632 /// ```
1633 ///
1634 /// ## Preserving original with clone
1635 ///
1636 /// ```rust
1637 /// use prism3_function::{Transformer, FnTransformerOps, BoxTransformer};
1638 ///
1639 /// let double = |x: i32| x * 2;
1640 /// let to_string = BoxTransformer::new(|x: i32| x.to_string());
1641 ///
1642 /// // Clone to preserve original
1643 /// let composed = double.and_then(to_string.clone());
1644 /// assert_eq!(composed.transform(21), "42");
1645 ///
1646 /// // Original still usable
1647 /// assert_eq!(to_string.transform(5), "5");
1648 /// ```
1649 fn and_then<S, F>(self, after: F) -> BoxTransformer<T, S>
1650 where
1651 S: 'static,
1652 F: Transformer<R, S> + 'static,
1653 T: 'static,
1654 R: 'static,
1655 {
1656 BoxTransformer::new(move |x: T| after.transform(self(x)))
1657 }
1658
1659 /// Reverse composition - applies before first, then self
1660 ///
1661 /// Creates a new transformer that applies the before transformer first,
1662 /// then applies this transformer to the result. Consumes self and returns
1663 /// a `BoxTransformer`.
1664 ///
1665 /// # Type Parameters
1666 ///
1667 /// * `S` - The input type of the before transformer
1668 /// * `F` - The type of the before transformer (must implement Transformer<S, T>)
1669 ///
1670 /// # Parameters
1671 ///
1672 /// * `before` - The transformer to apply before self. **Note: This parameter
1673 /// is passed by value and will transfer ownership.** If you need to
1674 /// preserve the original transformer, clone it first (if it implements
1675 /// `Clone`). Can be:
1676 /// - A closure: `|x: S| -> T`
1677 /// - A function pointer: `fn(S) -> T`
1678 /// - A `BoxTransformer<S, T>`
1679 /// - An `RcTransformer<S, T>`
1680 /// - An `ArcTransformer<S, T>`
1681 /// - Any type implementing `Transformer<S, T>`
1682 ///
1683 /// # Returns
1684 ///
1685 /// A new `BoxTransformer<S, R>` representing the composition
1686 ///
1687 /// # Examples
1688 ///
1689 /// ## Direct value passing (ownership transfer)
1690 ///
1691 /// ```rust
1692 /// use prism3_function::{Transformer, FnTransformerOps, BoxTransformer};
1693 ///
1694 /// let double = |x: i32| x * 2;
1695 /// let add_one = BoxTransformer::new(|x: i32| x + 1);
1696 ///
1697 /// // add_one is moved here
1698 /// let composed = double.compose(add_one);
1699 /// assert_eq!(composed.transform(5), 12); // (5 + 1) * 2
1700 /// // add_one.transform(3); // Would not compile - moved
1701 /// ```
1702 ///
1703 /// ## Preserving original with clone
1704 ///
1705 /// ```rust
1706 /// use prism3_function::{Transformer, FnTransformerOps, BoxTransformer};
1707 ///
1708 /// let double = |x: i32| x * 2;
1709 /// let add_one = BoxTransformer::new(|x: i32| x + 1);
1710 ///
1711 /// // Clone to preserve original
1712 /// let composed = double.compose(add_one.clone());
1713 /// assert_eq!(composed.transform(5), 12); // (5 + 1) * 2
1714 ///
1715 /// // Original still usable
1716 /// assert_eq!(add_one.transform(3), 4);
1717 /// ```
1718 fn compose<S, F>(self, before: F) -> BoxTransformer<S, R>
1719 where
1720 S: 'static,
1721 F: Transformer<S, T> + 'static,
1722 T: 'static,
1723 R: 'static,
1724 {
1725 BoxTransformer::new(move |x: S| self(before.transform(x)))
1726 }
1727
1728 /// Creates a conditional transformer
1729 ///
1730 /// Returns a transformer that only executes when a predicate is satisfied.
1731 /// You must call `or_else()` to provide an alternative transformer for when
1732 /// the condition is not satisfied.
1733 ///
1734 /// # Parameters
1735 ///
1736 /// * `predicate` - The condition to check. **Note: This parameter is passed
1737 /// by value and will transfer ownership.** If you need to preserve the
1738 /// original predicate, clone it first (if it implements `Clone`). Can be:
1739 /// - A closure: `|x: &T| -> bool`
1740 /// - A function pointer: `fn(&T) -> bool`
1741 /// - A `BoxPredicate<T>`
1742 /// - An `RcPredicate<T>`
1743 /// - An `ArcPredicate<T>`
1744 /// - Any type implementing `Predicate<T>`
1745 ///
1746 /// # Returns
1747 ///
1748 /// Returns `BoxConditionalTransformer<T, R>`
1749 ///
1750 /// # Examples
1751 ///
1752 /// ## Basic usage with or_else
1753 ///
1754 /// ```rust
1755 /// use prism3_function::{Transformer, FnTransformerOps};
1756 ///
1757 /// let double = |x: i32| x * 2;
1758 /// let conditional = double.when(|x: &i32| *x > 0).or_else(|x: i32| -x);
1759 ///
1760 /// assert_eq!(conditional.transform(5), 10);
1761 /// assert_eq!(conditional.transform(-5), 5);
1762 /// ```
1763 ///
1764 /// ## Preserving predicate with clone
1765 ///
1766 /// ```rust
1767 /// use prism3_function::{Transformer, FnTransformerOps, BoxPredicate};
1768 ///
1769 /// let double = |x: i32| x * 2;
1770 /// let is_positive = BoxPredicate::new(|x: &i32| *x > 0);
1771 ///
1772 /// // Clone to preserve original predicate
1773 /// let conditional = double.when(is_positive.clone())
1774 /// .or_else(|x: i32| -x);
1775 ///
1776 /// assert_eq!(conditional.transform(5), 10);
1777 ///
1778 /// // Original predicate still usable
1779 /// assert!(is_positive.test(&3));
1780 /// ```
1781 fn when<P>(self, predicate: P) -> BoxConditionalTransformer<T, R>
1782 where
1783 P: Predicate<T> + 'static,
1784 T: 'static,
1785 R: 'static,
1786 {
1787 BoxTransformer::new(self).when(predicate)
1788 }
1789}
1790
1791/// Blanket implementation of FnTransformerOps for all closures
1792///
1793/// Automatically implements `FnTransformerOps<T, R>` for any type that
1794/// implements `Fn(T) -> R`.
1795///
1796/// # Author
1797///
1798/// Hu Haixing
1799impl<T, R, F> FnTransformerOps<T, R> for F where F: Fn(T) -> R + 'static {}
1800
1801// ============================================================================
1802// UnaryOperator Trait - Marker trait for Transformer<T, T>
1803// ============================================================================
1804
1805/// UnaryOperator trait - marker trait for unary operators
1806///
1807/// A unary operator transforms a value of type `T` to another value of the
1808/// same type `T`. This trait extends `Transformer<T, T>` to provide semantic
1809/// clarity for same-type transformations. Equivalent to Java's `UnaryOperator<T>`
1810/// which extends `Function<T, T>`.
1811///
1812/// # Automatic Implementation
1813///
1814/// This trait is automatically implemented for all types that implement
1815/// `Transformer<T, T>`, so you don't need to implement it manually.
1816///
1817/// # Type Parameters
1818///
1819/// * `T` - The type of both input and output values
1820///
1821/// # Examples
1822///
1823/// ## Using in generic constraints
1824///
1825/// ```rust
1826/// use prism3_function::{UnaryOperator, Transformer};
1827///
1828/// fn apply_twice<T, O>(value: T, op: O) -> T
1829/// where
1830/// O: UnaryOperator<T>,
1831/// T: Clone,
1832/// {
1833/// let result = op.transform(value.clone());
1834/// op.transform(result)
1835/// }
1836///
1837/// let increment = |x: i32| x + 1;
1838/// assert_eq!(apply_twice(5, increment), 7); // (5 + 1) + 1
1839/// ```
1840///
1841/// ## With concrete types
1842///
1843/// ```rust
1844/// use prism3_function::{BoxUnaryOperator, UnaryOperator, Transformer};
1845///
1846/// fn create_incrementer() -> BoxUnaryOperator<i32> {
1847/// BoxUnaryOperator::new(|x| x + 1)
1848/// }
1849///
1850/// let op = create_incrementer();
1851/// assert_eq!(op.transform(41), 42);
1852/// ```
1853///
1854/// # Author
1855///
1856/// Hu Haixing
1857pub trait UnaryOperator<T>: Transformer<T, T> {}
1858
1859/// Blanket implementation of UnaryOperator for all Transformer<T, T>
1860///
1861/// This automatically implements `UnaryOperator<T>` for any type that
1862/// implements `Transformer<T, T>`.
1863///
1864/// # Author
1865///
1866/// Hu Haixing
1867impl<F, T> UnaryOperator<T> for F
1868where
1869 F: Transformer<T, T>,
1870 T: 'static,
1871{
1872 // empty
1873}
1874
1875// ============================================================================
1876// Type Aliases for UnaryOperator (Transformer<T, T>)
1877// ============================================================================
1878
1879/// Type alias for `BoxTransformer<T, T>`
1880///
1881/// Represents a unary operator that transforms a value of type `T` to another
1882/// value of the same type `T`, with single ownership semantics. Equivalent to
1883/// Java's `UnaryOperator<T>`.
1884///
1885/// # Examples
1886///
1887/// ```rust
1888/// use prism3_function::{BoxUnaryOperator, Transformer};
1889///
1890/// let increment: BoxUnaryOperator<i32> = BoxUnaryOperator::new(|x| x + 1);
1891/// assert_eq!(increment.transform(41), 42);
1892/// ```
1893///
1894/// # Author
1895///
1896/// Hu Haixing
1897pub type BoxUnaryOperator<T> = BoxTransformer<T, T>;
1898
1899/// Type alias for `ArcTransformer<T, T>`
1900///
1901/// Represents a thread-safe unary operator that transforms a value of type `T`
1902/// to another value of the same type `T`. Equivalent to Java's `UnaryOperator<T>`
1903/// with shared, thread-safe ownership.
1904///
1905/// # Examples
1906///
1907/// ```rust
1908/// use prism3_function::{ArcUnaryOperator, Transformer};
1909///
1910/// let double: ArcUnaryOperator<i32> = ArcUnaryOperator::new(|x| x * 2);
1911/// let double_clone = double.clone();
1912/// assert_eq!(double.transform(21), 42);
1913/// assert_eq!(double_clone.transform(21), 42);
1914/// ```
1915///
1916/// # Author
1917///
1918/// Hu Haixing
1919pub type ArcUnaryOperator<T> = ArcTransformer<T, T>;
1920
1921/// Type alias for `RcTransformer<T, T>`
1922///
1923/// Represents a single-threaded unary operator that transforms a value of type
1924/// `T` to another value of the same type `T`. Equivalent to Java's
1925/// `UnaryOperator<T>` with shared, single-threaded ownership.
1926///
1927/// # Examples
1928///
1929/// ```rust
1930/// use prism3_function::{RcUnaryOperator, Transformer};
1931///
1932/// let negate: RcUnaryOperator<i32> = RcUnaryOperator::new(|x: i32| -x);
1933/// let negate_clone = negate.clone();
1934/// assert_eq!(negate.transform(42), -42);
1935/// assert_eq!(negate_clone.transform(42), -42);
1936/// ```
1937///
1938/// # Author
1939///
1940/// Hu Haixing
1941pub type RcUnaryOperator<T> = RcTransformer<T, T>;