ToOptional
Re-marking every field of an existing builder as optional.
Overview
Context-Generic Programming (CGP) builds a struct generically, and its optional builder
lets the fields arrive in any order. HasOptionalBuilder starts one
from nothing. ToOptional is the conversion for the case where you already hold a partial value and
want to relax it. Every field is re-marked to IsOptional, whatever state it was in (a set field
becomes Some(value), an absent one becomes None), and from there the value behaves like any
other optional builder: SetOptional applies, and either
FinalizeOptional or
CanFinalizeWithDefault ends it.
It is the conversion optional_builder() is built from, which is the shortest way to describe both:
one starts fresh and converts, the other converts something you already have.
Definition
ToOptional carries the re-marked builder type as an associated Output and converts a partial value
into it:
pub trait ToOptional {
type Output;
fn to_optional(self) -> Self::Output;
}
Self is any partial builder, and Output is the same partial companion type with every marker set
to IsOptional. to_optional takes self, consuming the builder and returning the re-marked one.
The trait does not declare a supertrait; it is a blanket impl
over TransformMapFields, so any partial value whose
fields can be re-marked gains it, with nothing to implement by hand. It is not in the prelude; the
optional-field layer lives in cgp-field-extra.
Usage
It is not in the prelude. Import it from cgp::extra::field::impls:
use cgp::extra::field::impls::ToOptional;
You call it on a partial value, as builder.to_optional().
Examples
Relaxing a partly filled core builder, and then a complete value:
use cgp::core::field::traits::{BuildField, HasBuilder, IntoBuilder};
use cgp::extra::field::impls::{FinalizeOptional, SetOptional, ToOptional};
use cgp::prelude::*;
#[derive(Debug, PartialEq, CgpData)]
pub struct Context {
pub foo: String,
pub bar: u64,
}
pub fn demo() {
// `foo` is set before the conversion and survives it as `Some`.
let context = Context::builder()
.build_field(PhantomData::<Symbol!("foo")>, "foo".to_owned())
.to_optional()
.set(PhantomData::<Symbol!("bar")>, 42)
.finalize_optional()
.unwrap();
assert_eq!(context.foo, "foo");
// Every field of a complete value becomes `Some`, so one can be overwritten.
let context = context
.into_builder()
.to_optional()
.set(PhantomData::<Symbol!("bar")>, 7)
.finalize_optional()
.unwrap();
assert_eq!(context.bar, 7);
}
The already-set foo survives the first conversion as Some("foo"), which distinguishes this from
starting over with optional_builder(). The second conversion starts
from into_builder, so every field is Some and set overwrites
bar.
When to use it
Reach for it when a builder already exists and its strictness has become the wrong shape.
HasOptionalBuilderwhen nothing has been built yet.optional_builder()isbuilder().to_optional()and reads better.ToOptionalwhen a core builder is partly filled, because a routine handed it to you, or because the first few fields were known and the rest are not.IntoBuilderthento_optionalto relax a complete value, typically before overwriting some of its fields.- Stay on the core builder if the remaining fields are known and set once. The conversion costs the compile-time completeness check.
Under the hood
ToOptional is a blanket impl over a TransformMapFields
walk carrying the TransformOptional marker, targeting IsOptional:
impl<Context> ToOptional for Context
where
Context: TransformMapFields<TransformOptional, IsOptional>,
{
type Output = Context::Output;
fn to_optional(self) -> Self::Output {
self.transform_map_fields()
}
}
That walk visits each field of the target's HasFields shape, uses
UpdateField to take the field out and learn its current marker,
applies the transform, and writes it back under IsOptional. The transform's impls decide the
value: IsPresent becomes Some(value) and IsNothing becomes None. TransformOptional lacks
an impl from IsOptional, so a builder that is already optional cannot be converted again, as
Common Mistakes shows.
Its mirror image is CanFinalizeWithDefault, which runs the same walk
with TransformMapDefault toward IsPresent. Both operations are the
same recursion with a different marker, which is why the defaulted and optional workflows behave so
symmetrically.
Common Mistakes
It is not in the prelude. Import from cgp::extra::field::impls.
It consumes the builder and returns a differently-typed one, so the original binding is gone.
A field already set survives as Some. It is not reset, which is the difference from
optional_builder() and is easy to assume the other way round.
Converting gives up the compile-time completeness check for the fields that were still absent. From
here a missing field is an Err or a default rather than a compile error.
It does not apply to a builder that is already optional. Converting the result of
optional_builder() again:
let _ = Context::optional_builder().to_optional();
does not find a TransformOptional conversion from IsOptional, and
fails with:
error[E0599]: the method `to_optional` exists for struct `__PartialContext<IsOptional, IsOptional>`, but its trait bounds were not satisfied
...
= note: the following trait bounds were not satisfied:
`__PartialContext<IsOptional, IsOptional>: TransformMapFields<TransformOptional, IsOptional>`
It is not reversible. from_optional does not exist; getting back to a strict configuration
means finalizing, through FinalizeOptional or
CanFinalizeWithDefault.
A field whose type is already Option<T> becomes Option<Option<T>> in the slot. That is correct
(the outer layer is the builder's presence tracking) and reads confusingly in an error.
Related constructs
HasOptionalBuilder: the entry point built from this conversion.SetOptional: setting a field once every marker isIsOptional.FinalizeOptionalandCanFinalizeWithDefault: the two endings.TransformOptional: the marker this walk carries.TransformMapFields: the walk itself.IntoBuilder: how a complete value becomes a builder to convert.HasBuilder: the core family this relaxes.MapType: theIsOptionalmarker.
The ideas behind it:
- Extensible records: partial records, and where relaxing presence fits.
Source
to_optional.rs:ToOptional,HasOptionalBuilder, andTransformOptional
An AI agent wrote this page using the CGP knowledge base. Its content was verified against the library's source. See How AI is used in this project.