Skip to main content

karpal_optics/
review.rs

1use crate::optic::Optic;
2
3/// A write-only optic that can construct a target from a value.
4///
5/// This is the "review" (construction) component of a prism,
6/// without any matching capability.
7pub struct Review<T, B> {
8    build: fn(B) -> T,
9}
10
11impl<T, B> Optic for Review<T, B> {}
12
13impl<T, B> Review<T, B> {
14    pub fn new(build: fn(B) -> T) -> Self {
15        Self { build }
16    }
17
18    pub fn review(&self, b: B) -> T {
19        (self.build)(b)
20    }
21}
22
23#[cfg(test)]
24mod tests {
25    use super::*;
26
27    #[derive(Debug, PartialEq)]
28    enum Shape {
29        Circle(f64),
30    }
31
32    #[test]
33    fn review_build() {
34        let review = Review::new(Shape::Circle);
35        assert_eq!(review.review(5.0), Shape::Circle(5.0));
36    }
37
38    #[test]
39    fn review_from_prism() {
40        use crate::prism::Prism;
41        let prism = Prism::new(
42            |s: Shape| match s {
43                Shape::Circle(r) => Ok(r),
44            },
45            Shape::Circle,
46        );
47        let review = prism.to_review();
48        assert_eq!(review.review(10.0), Shape::Circle(10.0));
49    }
50
51    #[test]
52    fn review_from_iso() {
53        use crate::iso::Iso;
54        let iso = Iso::new(|n: &i32| *n as f64, |f: f64| f as i32);
55        let review = iso.to_review();
56        assert_eq!(review.review(3.14), 3);
57    }
58}