From 0b7e94626b6409fcaa4024088246a32327468248 Mon Sep 17 00:00:00 2001 From: David Renshaw Date: Mon, 23 Sep 2024 14:10:21 -0400 Subject: [PATCH] add dynamic_struct::{Builder, Reader}::downcast() --- capnp/src/dynamic_struct.rs | 24 ++++++++++++++++++++++++ capnp/src/dynamic_value.rs | 18 +++--------------- 2 files changed, 27 insertions(+), 15 deletions(-) diff --git a/capnp/src/dynamic_struct.rs b/capnp/src/dynamic_struct.rs index a8a4c866b..aecafc010 100644 --- a/capnp/src/dynamic_struct.rs +++ b/capnp/src/dynamic_struct.rs @@ -232,6 +232,18 @@ impl<'a> Reader<'a> { let field = self.schema.get_field_by_name(field_name)?; self.has(field) } + + /// Downcasts the `Reader` into a specific struct type. Panics if the + /// expected type does not match the value. + pub fn downcast(self) -> T::Reader<'a> { + assert!( + Into::::into(crate::introspect::TypeVariant::Struct( + self.schema.raw + )) + .may_downcast_to(T::introspect()) + ); + self.reader.into() + } } /// A mutable dynamically-typed struct. @@ -773,6 +785,18 @@ impl<'a> Builder<'a> { } Ok(()) } + + /// Downcasts the `Builder` into a specific struct type. Panics if the + /// expected type does not match the value. + pub fn downcast(self) -> T::Builder<'a> { + assert!( + Into::::into(crate::introspect::TypeVariant::Struct( + self.schema.raw + )) + .may_downcast_to(T::introspect()) + ); + self.builder.into() + } } impl<'a> crate::traits::SetterInput for Reader<'a> { diff --git a/capnp/src/dynamic_value.rs b/capnp/src/dynamic_value.rs index 8ef956327..3a049edf6 100644 --- a/capnp/src/dynamic_value.rs +++ b/capnp/src/dynamic_value.rs @@ -77,14 +77,8 @@ impl<'a> Reader<'a> { /// the current way the `Introspect` and `OwnedStruct` traits are set up does not /// seem to allow this. pub fn downcast_struct(self) -> T::Reader<'a> { - let sb: dynamic_struct::Reader = self.downcast(); - assert!( - Into::::into(crate::introspect::TypeVariant::Struct( - sb.schema.raw - )) - .may_downcast_to(T::introspect()) - ); - sb.reader.into() + let sr: dynamic_struct::Reader = self.downcast(); + sr.downcast::() } } @@ -243,13 +237,7 @@ impl<'a> Builder<'a> { /// seem to allow this. pub fn downcast_struct(self) -> T::Builder<'a> { let sb: dynamic_struct::Builder = self.downcast(); - assert!( - Into::::into(crate::introspect::TypeVariant::Struct( - sb.schema.raw - )) - .may_downcast_to(T::introspect()) - ); - sb.builder.into() + sb.downcast::() } }