Skip to main content

cgp_field_extra/impls/
to_optional.rs

1use cgp_field::impls::{IsNothing, IsOptional, IsPresent};
2use cgp_field::traits::{HasBuilder, TransformMap, TransformMapFields};
3
4pub trait HasOptionalBuilder {
5    type Builder;
6
7    fn optional_builder() -> Self::Builder;
8}
9
10impl<Context, Builder> HasOptionalBuilder for Context
11where
12    Context: HasBuilder,
13    Context::Builder: ToOptional<Output = Builder>,
14{
15    type Builder = Builder;
16
17    fn optional_builder() -> Self::Builder {
18        Self::builder().to_optional()
19    }
20}
21
22pub trait ToOptional {
23    type Output;
24
25    fn to_optional(self) -> Self::Output;
26}
27
28impl<Context> ToOptional for Context
29where
30    Context: TransformMapFields<TransformOptional, IsOptional>,
31{
32    type Output = Context::Output;
33
34    fn to_optional(self) -> Self::Output {
35        self.transform_map_fields()
36    }
37}
38
39pub struct TransformOptional;
40
41impl<T> TransformMap<IsPresent, IsOptional, T> for TransformOptional {
42    fn transform_mapped(value: T) -> Option<T> {
43        Some(value)
44    }
45}
46
47impl<T> TransformMap<IsNothing, IsOptional, T> for TransformOptional {
48    fn transform_mapped(_value: ()) -> Option<T> {
49        None
50    }
51}