Skip to main content

karpal_optics/
review.rs

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