From 435c3e174b20e81e72cb4c0042671ac7a5173f2b Mon Sep 17 00:00:00 2001 From: Andrew Liu Date: Tue, 22 Dec 2020 16:21:52 -0800 Subject: [PATCH] [Rust] Impl IsObjectRef for Array (#7138) * impl isobjectref for array * array test * cargo fmt --- rust/tvm-rt/src/array.rs | 34 ++++++++++++++++++++++++++++++++-- 1 file changed, 32 insertions(+), 2 deletions(-) diff --git a/rust/tvm-rt/src/array.rs b/rust/tvm-rt/src/array.rs index 1b0ce8399d1f..5abf66708f45 100644 --- a/rust/tvm-rt/src/array.rs +++ b/rust/tvm-rt/src/array.rs @@ -45,6 +45,26 @@ external! { fn array_size(array: ObjectRef) -> i64; } +impl IsObjectRef for Array { + type Object = Object; + fn as_ptr(&self) -> Option<&ObjectPtr> { + self.object.as_ptr() + } + fn into_ptr(self) -> Option> { + self.object.into_ptr() + } + fn from_ptr(object_ptr: Option>) -> Self { + let object_ref = match object_ptr { + Some(o) => o.into(), + _ => panic!(), + }; + Array { + object: object_ref, + _data: PhantomData, + } + } +} + impl Array { pub fn from_vec(data: Vec) -> Result> { let iter = data.into_iter().map(T::into_arg_value).collect(); @@ -131,8 +151,8 @@ impl FromIterator for Array { } } -impl From> for ArgValue<'static> { - fn from(array: Array) -> ArgValue<'static> { +impl<'a, T: IsObjectRef> From> for ArgValue<'a> { + fn from(array: Array) -> ArgValue<'a> { array.object.into() } } @@ -172,6 +192,7 @@ impl<'a, T: IsObjectRef> TryFrom for Array { mod tests { use super::Array; use crate::function::Result; + use crate::object::{IsObjectRef, ObjectRef}; use crate::string::String; #[test] @@ -183,4 +204,13 @@ mod tests { assert_eq!(array.get(2)?.to_string(), "baz"); Ok(()) } + + #[test] + fn downcast() -> Result<()> { + let vec: Vec = vec!["foo".into(), "bar".into(), "baz".into()]; + let array: ObjectRef = ObjectRef::from_ptr(Array::from_vec(vec)?.into_ptr()); + let array: Array = array.downcast::>().unwrap(); + assert_eq!(array.get(1)?.downcast::().unwrap(), "bar"); + Ok(()) + } }