From 237107c971707d297c1f2d3e536ca52289ae4206 Mon Sep 17 00:00:00 2001 From: HampusM Date: Sun, 5 Jul 2026 02:02:53 +0200 Subject: feat(engine-reflection): add Reflection impl for Option --- engine-reflection/src/lib.rs | 77 ++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 77 insertions(+) (limited to 'engine-reflection/src') diff --git a/engine-reflection/src/lib.rs b/engine-reflection/src/lib.rs index 62fa4f5..8436e65 100644 --- a/engine-reflection/src/lib.rs +++ b/engine-reflection/src/lib.rs @@ -421,6 +421,83 @@ unsafe impl Reflection for &'static T }); } +unsafe impl Reflection for Option +{ + const TYPE_REFLECTION: &Type = &Type::Enum(Enum { + variants: &[ + EnumVariant { + name: "Some", + fields: Some(EnumVariantFields::Unnamed { + fields: &[EnumVariantField { + name: None, + index: 0, + type_id: TypeId::of::(), + get_type_name: FnWithDebug::new(|| type_name::()), + get_type: FnWithDebug::new(|| Some(T::type_reflection())), + }], + }), + try_write_new_to: |dst, fields| { + let dst = dst + .downcast_mut::() + .ok_or(EnumVariantWriteNewToError::WrongDstType)?; + + let value_field = fields + .next() + .ok_or(EnumVariantWriteNewToError::TooFewFields)? + .downcast::() + .map_err(|_| EnumVariantWriteNewToError::WrongFieldType)?; + + if fields.next().is_some() { + return Err(EnumVariantWriteNewToError::TooManyFields); + } + + *dst = Some(*value_field); + + Ok(()) + }, + }, + EnumVariant { + name: "None", + fields: None, + try_write_new_to: |dst, fields| { + let dst = dst + .downcast_mut::() + .ok_or(EnumVariantWriteNewToError::WrongDstType)?; + + if fields.next().is_some() { + return Err(EnumVariantWriteNewToError::TooManyFields); + } + + *dst = None; + + Ok(()) + }, + }, + ], + is_unit_only: false, + get_default_value: || Some(|| Box::new(Option::::None)), + cast_dyn_any: |ptr| ptr.cast::(), + get_variant_reflection: |target| { + let target = target.downcast_ref::()?; + + Some(target.get_variant_reflection()) + }, + }); +} + +unsafe impl EnumReflectionExt for Option +{ + fn get_variant_reflection(&self) -> &'static EnumVariant + { + let ty = unsafe { Self::type_reflection().as_enum().unwrap_unchecked() }; + + match self { + Some(_) => &ty.variants[0], + None => &ty.variants[1], + } + } +} + #[derive(Clone)] pub struct FnWithDebug { -- cgit v1.2.3-18-g5258