-
Notifications
You must be signed in to change notification settings - Fork 257
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
feat(Rust): Support serialization and deserialization of trait objects #1797
Open
theweipeng
wants to merge
7
commits into
apache:main
Choose a base branch
from
theweipeng:xlang_customtrait
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from all commits
Commits
Show all changes
7 commits
Select commit
Hold shift + click to select a range
d53afac
Support serialization and deserialization of trait objects
theweipeng 729848a
fix typo
theweipeng 1771580
add license header
theweipeng 1540bc1
cargo fmt
theweipeng a15b226
fix CI
theweipeng fd97ad0
1
theweipeng b60587b
1
theweipeng File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,42 @@ | ||
// Licensed to the Apache Software Foundation (ASF) under one | ||
// or more contributor license agreements. See the NOTICE file | ||
// distributed with this work for additional information | ||
// regarding copyright ownership. The ASF licenses this file | ||
// to you under the Apache License, Version 2.0 (the | ||
// "License"); you may not use this file except in compliance | ||
// with the License. You may obtain a copy of the License at | ||
// | ||
// http://www.apache.org/licenses/LICENSE-2.0 | ||
// | ||
// Unless required by applicable law or agreed to in writing, | ||
// software distributed under the License is distributed on an | ||
// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY | ||
// KIND, either express or implied. See the License for the | ||
// specific language governing permissions and limitations | ||
// under the License. | ||
|
||
use crate::error::Error; | ||
use mem::transmute; | ||
use std::any::TypeId; | ||
use std::mem; | ||
|
||
pub struct MaybeTraitObject { | ||
ptr: *const u8, | ||
type_id: TypeId, | ||
} | ||
|
||
impl MaybeTraitObject { | ||
pub fn new<T: 'static>(value: T) -> MaybeTraitObject { | ||
let ptr = unsafe { transmute::<Box<T>, *const u8>(Box::new(value)) }; | ||
let type_id = TypeId::of::<T>(); | ||
MaybeTraitObject { ptr, type_id } | ||
} | ||
|
||
pub fn to_trait_object<T: 'static>(self) -> Result<T, Error> { | ||
if self.type_id == TypeId::of::<T>() { | ||
Ok(unsafe { *(transmute::<*const u8, Box<T>>(self.ptr)) }) | ||
} else { | ||
Err(Error::ConvertToTraitObjectError {}) | ||
} | ||
} | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,18 @@ | ||
// Licensed to the Apache Software Foundation (ASF) under one | ||
// or more contributor license agreements. See the NOTICE file | ||
// distributed with this work for additional information | ||
// regarding copyright ownership. The ASF licenses this file | ||
// to you under the Apache License, Version 2.0 (the | ||
// "License"); you may not use this file except in compliance | ||
// with the License. You may obtain a copy of the License at | ||
// | ||
// http://www.apache.org/licenses/LICENSE-2.0 | ||
// | ||
// Unless required by applicable law or agreed to in writing, | ||
// software distributed under the License is distributed on an | ||
// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY | ||
// KIND, either express or implied. See the License for the | ||
// specific language governing permissions and limitations | ||
// under the License. | ||
|
||
pub mod maybe_trait_object; |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
|
@@ -18,99 +18,83 @@ | |
use super::context::{ReadContext, WriteContext}; | ||
use crate::error::Error; | ||
use crate::fury::Fury; | ||
use crate::serializer::StructSerializer; | ||
use crate::raw::maybe_trait_object::MaybeTraitObject; | ||
use crate::serializer::{Serializer, SS}; | ||
use std::any::TypeId; | ||
use std::{any::Any, collections::HashMap}; | ||
|
||
pub struct Harness { | ||
serializer: fn(&dyn Any, &mut WriteContext), | ||
deserializer: fn(&mut ReadContext) -> Result<Box<dyn Any>, Error>, | ||
} | ||
|
||
impl Harness { | ||
pub fn new( | ||
serializer: fn(&dyn Any, &mut WriteContext), | ||
deserializer: fn(&mut ReadContext) -> Result<Box<dyn Any>, Error>, | ||
) -> Harness { | ||
Harness { | ||
serializer, | ||
deserializer, | ||
} | ||
} | ||
|
||
pub fn get_serializer(&self) -> fn(&dyn Any, &mut WriteContext) { | ||
self.serializer | ||
} | ||
|
||
pub fn get_deserializer(&self) -> fn(&mut ReadContext) -> Result<Box<dyn Any>, Error> { | ||
self.deserializer | ||
} | ||
} | ||
pub type TraitObjectDeserializer = fn(&mut ReadContext) -> Result<MaybeTraitObject, Error>; | ||
|
||
pub struct ClassInfo { | ||
type_def: Vec<u8>, | ||
type_id: u32, | ||
fury_type_id: u32, | ||
rust_type_id: TypeId, | ||
trait_object_serializer: fn(&dyn Any, &mut WriteContext), | ||
trait_object_deserializer: HashMap<TypeId, TraitObjectDeserializer>, | ||
} | ||
|
||
fn serialize<T: 'static + Serializer>(this: &dyn Any, context: &mut WriteContext) { | ||
let this = this.downcast_ref::<T>().unwrap(); | ||
T::serialize(this, context) | ||
} | ||
|
||
impl ClassInfo { | ||
pub fn new<T: StructSerializer>(fury: &Fury, type_id: u32) -> ClassInfo { | ||
pub fn new<T: Serializer>(fury: &Fury, type_id: u32) -> ClassInfo { | ||
ClassInfo { | ||
type_def: T::type_def(fury), | ||
type_id, | ||
fury_type_id: type_id, | ||
rust_type_id: TypeId::of::<T>(), | ||
trait_object_serializer: serialize::<T>, | ||
trait_object_deserializer: T::get_trait_object_deserializer(), | ||
} | ||
} | ||
|
||
pub fn get_type_id(&self) -> u32 { | ||
self.type_id | ||
pub fn associate(&mut self, type_id: TypeId, func: TraitObjectDeserializer) { | ||
self.trait_object_deserializer.insert(type_id, func); | ||
} | ||
|
||
pub fn get_rust_type_id(&self) -> TypeId { | ||
self.rust_type_id | ||
} | ||
|
||
pub fn get_fury_type_id(&self) -> u32 { | ||
self.fury_type_id | ||
} | ||
|
||
pub fn get_type_def(&self) -> &Vec<u8> { | ||
&self.type_def | ||
} | ||
|
||
pub fn get_serializer(&self) -> fn(&dyn Any, &mut WriteContext) { | ||
self.trait_object_serializer | ||
} | ||
|
||
pub fn get_trait_object_deserializer<T: 'static>(&self) -> Option<&TraitObjectDeserializer> { | ||
let type_id = TypeId::of::<T>(); | ||
self.trait_object_deserializer.get(&type_id) | ||
} | ||
} | ||
|
||
#[derive(Default)] | ||
pub struct ClassResolver { | ||
serialize_map: HashMap<u32, Harness>, | ||
type_id_map: HashMap<TypeId, u32>, | ||
fury_type_id_map: HashMap<u32, TypeId>, | ||
class_info_map: HashMap<TypeId, ClassInfo>, | ||
} | ||
|
||
impl ClassResolver { | ||
pub fn get_class_info(&self, type_id: TypeId) -> &ClassInfo { | ||
pub fn get_class_info_by_rust_type(&self, type_id: TypeId) -> &ClassInfo { | ||
self.class_info_map.get(&type_id).unwrap() | ||
} | ||
|
||
pub fn register<T: StructSerializer>(&mut self, class_info: ClassInfo, id: u32) { | ||
fn serializer<T2: 'static + StructSerializer>(this: &dyn Any, context: &mut WriteContext) { | ||
let this = this.downcast_ref::<T2>(); | ||
match this { | ||
Some(v) => { | ||
T2::serialize(v, context); | ||
} | ||
None => todo!(), | ||
} | ||
} | ||
|
||
fn deserializer<T2: 'static + StructSerializer>( | ||
context: &mut ReadContext, | ||
) -> Result<Box<dyn Any>, Error> { | ||
match T2::deserialize(context) { | ||
Ok(v) => Ok(Box::new(v)), | ||
Err(e) => Err(e), | ||
} | ||
} | ||
self.type_id_map.insert(TypeId::of::<T>(), id); | ||
self.serialize_map | ||
.insert(id, Harness::new(serializer::<T>, deserializer::<T>)); | ||
self.class_info_map.insert(TypeId::of::<T>(), class_info); | ||
} | ||
|
||
pub fn get_harness_by_type(&self, type_id: TypeId) -> Option<&Harness> { | ||
self.get_harness(*self.type_id_map.get(&type_id).unwrap()) | ||
pub fn get_class_info_by_fury_type(&self, type_id: u32) -> &ClassInfo { | ||
let type_id = self.fury_type_id_map.get(&type_id).unwrap(); | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Too many unwrap here, how about return a Result? There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Yes. The codebase contain too many unwrap, I will fix it one by one. |
||
self.class_info_map.get(type_id).unwrap() | ||
} | ||
|
||
pub fn get_harness(&self, id: u32) -> Option<&Harness> { | ||
self.serialize_map.get(&id) | ||
pub fn register<T: Serializer>(&mut self, class_info: ClassInfo, id: u32) -> &mut ClassInfo { | ||
let type_id = TypeId::of::<T>(); | ||
self.fury_type_id_map.insert(id, type_id); | ||
self.class_info_map.insert(type_id, class_info); | ||
self.class_info_map.get_mut(&type_id).unwrap() | ||
} | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
If user don't call this function, then
T
is leaked?If it's, we can impl Drop for MaybeTraitObject to release memory..
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Great catch, I will fixed it.