Skip to content

Commit

Permalink
add dynamic_struct::{Builder, Reader}::downcast()
Browse files Browse the repository at this point in the history
  • Loading branch information
dwrensha committed Sep 23, 2024
1 parent ee107e9 commit 0b7e946
Show file tree
Hide file tree
Showing 2 changed files with 27 additions and 15 deletions.
24 changes: 24 additions & 0 deletions capnp/src/dynamic_struct.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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<T: crate::traits::OwnedStruct>(self) -> T::Reader<'a> {
assert!(
Into::<crate::introspect::Type>::into(crate::introspect::TypeVariant::Struct(
self.schema.raw
))
.may_downcast_to(T::introspect())
);
self.reader.into()
}
}

/// A mutable dynamically-typed struct.
Expand Down Expand Up @@ -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<T: crate::traits::OwnedStruct>(self) -> T::Builder<'a> {
assert!(
Into::<crate::introspect::Type>::into(crate::introspect::TypeVariant::Struct(
self.schema.raw
))
.may_downcast_to(T::introspect())
);
self.builder.into()
}
}

impl<'a> crate::traits::SetterInput<crate::any_pointer::Owned> for Reader<'a> {
Expand Down
18 changes: 3 additions & 15 deletions capnp/src/dynamic_value.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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<T: crate::traits::OwnedStruct>(self) -> T::Reader<'a> {
let sb: dynamic_struct::Reader = self.downcast();
assert!(
Into::<crate::introspect::Type>::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::<T>()
}
}

Expand Down Expand Up @@ -243,13 +237,7 @@ impl<'a> Builder<'a> {
/// seem to allow this.
pub fn downcast_struct<T: crate::traits::OwnedStruct>(self) -> T::Builder<'a> {
let sb: dynamic_struct::Builder = self.downcast();
assert!(
Into::<crate::introspect::Type>::into(crate::introspect::TypeVariant::Struct(
sb.schema.raw
))
.may_downcast_to(T::introspect())
);
sb.builder.into()
sb.downcast::<T>()
}
}

Expand Down

0 comments on commit 0b7e946

Please sign in to comment.