You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@fory.apache.org by ch...@apache.org on 2025/10/08 02:50:03 UTC
(fory) branch main updated: feat(Rust): named_xx se/de && ext se/de && add unittest (#2712)
This is an automated email from the ASF dual-hosted git repository.
chaokunyang pushed a commit to branch main
in repository https://gitbox.apache.org/repos/asf/fory.git
The following commit(s) were added to refs/heads/main by this push:
new 4b0e8980f feat(Rust): named_xx se/de && ext se/de && add unittest (#2712)
4b0e8980f is described below
commit 4b0e8980f9e3a9cbc216755d88651e22d13bd640
Author: urlyy <li...@gmail.com>
AuthorDate: Wed Oct 8 10:49:59 2025 +0800
feat(Rust): named_xx se/de && ext se/de && add unittest (#2712)
## What does this PR do?
1. support `NamedXx` se/de
2. support `EXT`/`NAMEDEXT` se/de
3. fullfil unit test
## Related issues
close #2710
## Does this PR introduce any user-facing change?
- [ ] Does this PR introduce any public API change?
- [ ] Does this PR introduce any binary protocol compatibility change?
---------
Co-authored-by: Shawn Yang <sh...@gmail.com>
Co-authored-by: Shawn Yang <ch...@apache.org>
---
.../test/java/org/apache/fory/RustXlangTest.java | 182 ++++++-
rust/fory-core/src/fory.rs | 43 +-
rust/fory-core/src/meta/meta_string.rs | 24 -
rust/fory-core/src/meta/mod.rs | 5 +-
rust/fory-core/src/meta/type_meta.rs | 144 +++++-
rust/fory-core/src/resolver/meta_resolver.rs | 4 +-
rust/fory-core/src/resolver/metastring_resolver.rs | 382 +++++++++++++-
rust/fory-core/src/resolver/type_resolver.rs | 170 +++----
rust/fory-core/src/serializer/any.rs | 16 +-
rust/fory-core/src/serializer/bool.rs | 10 +-
rust/fory-core/src/serializer/collection.rs | 18 +-
rust/fory-core/src/serializer/datetime.rs | 18 +-
rust/fory-core/src/serializer/enum_.rs | 24 +-
rust/fory-core/src/serializer/map.rs | 13 +-
rust/fory-core/src/serializer/mod.rs | 131 ++++-
rust/fory-core/src/serializer/number.rs | 10 +-
rust/fory-core/src/serializer/primitive_list.rs | 15 +-
rust/fory-core/src/serializer/skip.rs | 53 +-
rust/fory-core/src/serializer/string.rs | 10 +-
rust/fory-core/src/serializer/struct_.rs | 16 +-
rust/fory-core/src/serializer/trait_object.rs | 8 +-
rust/fory-core/src/types.rs | 24 +-
rust/fory-derive/src/object/misc.rs | 17 +-
rust/fory-derive/src/object/read.rs | 6 +-
rust/fory-derive/src/object/serializer.rs | 8 +-
rust/fory-derive/src/object/util.rs | 46 +-
rust/fory-derive/src/object/write.rs | 2 +-
rust/fory-derive/src/util.rs | 1 +
.../src/meta => tests/tests/compatible}/mod.rs | 18 +-
rust/tests/tests/compatible/test_basic_type.rs | 489 ++++++++++++++++++
rust/tests/tests/compatible/test_container.rs | 565 +++++++++++++++++++++
.../test_struct.rs} | 8 +-
rust/tests/tests/compatible/test_struct_enum.rs | 560 ++++++++++++++++++++
rust/{fory-core/src/meta => tests/tests}/mod.rs | 15 +-
rust/tests/tests/test_complex_struct.rs | 6 +
rust/tests/tests/test_cross_language.rs | 225 ++++++--
rust/tests/tests/test_ext.rs | 6 +-
rust/tests/tests/test_rc_arc_trait_object.rs | 1 +
38 files changed, 2934 insertions(+), 359 deletions(-)
diff --git a/java/fory-core/src/test/java/org/apache/fory/RustXlangTest.java b/java/fory-core/src/test/java/org/apache/fory/RustXlangTest.java
index 4a8269ce7..f19367d6f 100644
--- a/java/fory-core/src/test/java/org/apache/fory/RustXlangTest.java
+++ b/java/fory-core/src/test/java/org/apache/fory/RustXlangTest.java
@@ -40,6 +40,7 @@ import org.apache.fory.logging.Logger;
import org.apache.fory.logging.LoggerFactory;
import org.apache.fory.memory.MemoryBuffer;
import org.apache.fory.memory.MemoryUtils;
+import org.apache.fory.serializer.Serializer;
import org.apache.fory.serializer.StringSerializer;
import org.apache.fory.test.TestUtils;
import org.apache.fory.util.MurmurHash3;
@@ -53,8 +54,6 @@ import org.testng.annotations.Test;
@Test
public class RustXlangTest extends ForyTestBase {
private static final Logger LOG = LoggerFactory.getLogger(RustXlangTest.class);
- private static final String PYTHON_EXECUTABLE = "python";
- private static final String PYTHON_MODULE = "pyfory.tests.test_cross_language";
private static final String RUST_EXECUTABLE = "cargo";
private static final String RUST_MODULE = "test_cross_language";
@@ -73,8 +72,6 @@ public class RustXlangTest extends ForyTestBase {
"--ignored",
// Exact match test name rather than prefix matching.
"--exact");
- private static final List<String> pyBaseCommand =
- Arrays.asList(PYTHON_EXECUTABLE, "-m", PYTHON_MODULE, "<TESTCASE>", "<DATA_FILE>");
private static final int RUST_TESTCASE_INDEX = 4;
@@ -122,11 +119,12 @@ public class RustXlangTest extends ForyTestBase {
testMap(Language.RUST, command);
command.set(RUST_TESTCASE_INDEX, "test_integer");
testInteger(Language.RUST, command);
- }
-
- @Test
- public void testPy() {
- List<String> command = pyBaseCommand;
+ command.set(RUST_TESTCASE_INDEX, "test_skip_id_custom");
+ testSkipIdCustom(Language.RUST, command);
+ command.set(RUST_TESTCASE_INDEX, "test_skip_name_custom");
+ testSkipNameCustom(Language.RUST, command);
+ command.set(RUST_TESTCASE_INDEX, "test_consistent_named");
+ testConsistentNamed(Language.RUST, command);
}
private void testBuffer(Language language, List<String> command) throws IOException {
@@ -674,6 +672,172 @@ public class RustXlangTest extends ForyTestBase {
Assert.assertNull(fory.deserialize(buffer2));
}
+ static class MyStruct {
+ int id;
+
+ public MyStruct(int id) {
+ this.id = id;
+ }
+ }
+
+ @Data
+ static class MyExt {
+ int id;
+
+ public MyExt(int id) {
+ this.id = id;
+ }
+
+ public MyExt() {}
+ }
+
+ private static class MyExtSerializer extends Serializer<MyExt> {
+
+ public MyExtSerializer(Fory fory, Class<MyExt> cls) {
+ super(fory, cls);
+ }
+
+ @Override
+ public void write(MemoryBuffer buffer, MyExt value) {
+ xwrite(buffer, value);
+ }
+
+ @Override
+ public MyExt read(MemoryBuffer buffer) {
+ return xread(buffer);
+ }
+
+ @Override
+ public void xwrite(MemoryBuffer buffer, MyExt value) {
+ buffer.writeVarInt32(value.id);
+ }
+
+ @SuppressWarnings("unchecked")
+ @Override
+ public MyExt xread(MemoryBuffer buffer) {
+ MyExt obj = new MyExt();
+ obj.id = buffer.readVarInt32();
+ return obj;
+ }
+ }
+
+ @Data
+ static class MyWrapper {
+ Color color;
+ MyExt my_ext;
+ MyStruct my_struct;
+ }
+
+ @Data
+ static class EmptyWrapper {}
+
+ private void _testSkipCustom(
+ Fory fory1, Fory fory2, Language language, List<String> command, String caseName)
+ throws IOException {
+ MyWrapper wrapper = new MyWrapper();
+ wrapper.color = Color.White;
+ MyStruct myStruct = new MyStruct(42);
+ MyExt myExt = new MyExt(43);
+ wrapper.my_ext = myExt;
+ wrapper.my_struct = myStruct;
+ byte[] serialize = fory1.serialize(wrapper);
+ Path dataFile = Files.createTempFile(caseName, "data");
+ Pair<Map<String, String>, File> env_workdir =
+ setFilePath(language, command, dataFile, serialize);
+ Assert.assertTrue(executeCommand(command, 30, env_workdir.getLeft(), env_workdir.getRight()));
+ MemoryBuffer buffer2 = MemoryUtils.wrap(Files.readAllBytes(dataFile));
+ EmptyWrapper newWrapper = (EmptyWrapper) fory2.deserialize(buffer2);
+ Assert.assertEquals(newWrapper, new EmptyWrapper());
+ }
+
+ private void testSkipIdCustom(Language language, List<String> command)
+ throws java.io.IOException {
+ Fory fory1 =
+ Fory.builder()
+ .withLanguage(Language.XLANG)
+ .withCompatibleMode(CompatibleMode.COMPATIBLE)
+ .withCodegen(false)
+ .build();
+ fory1.register(Color.class, 101);
+ fory1.register(MyStruct.class, 102);
+ fory1.register(MyExt.class, 103);
+ fory1.registerSerializer(MyExt.class, MyExtSerializer.class);
+ fory1.register(MyWrapper.class, 104);
+ Fory fory2 =
+ Fory.builder()
+ .withLanguage(Language.XLANG)
+ .withCompatibleMode(CompatibleMode.COMPATIBLE)
+ .withCodegen(false)
+ .build();
+ fory2.register(MyExt.class, 103);
+ fory2.registerSerializer(MyExt.class, MyExtSerializer.class);
+ fory2.register(EmptyWrapper.class, 104);
+ _testSkipCustom(fory1, fory2, language, command, "test_skip_id_custom");
+ }
+
+ private void testSkipNameCustom(Language language, List<String> command)
+ throws java.io.IOException {
+ Fory fory1 =
+ Fory.builder()
+ .withLanguage(Language.XLANG)
+ .withCompatibleMode(CompatibleMode.COMPATIBLE)
+ .withCodegen(false)
+ .build();
+ fory1.register(Color.class, "color");
+ fory1.register(MyStruct.class, "my_struct");
+ fory1.register(MyExt.class, "my_ext");
+ fory1.registerSerializer(MyExt.class, MyExtSerializer.class);
+ fory1.register(MyWrapper.class, "my_wrapper");
+ Fory fory2 =
+ Fory.builder()
+ .withLanguage(Language.XLANG)
+ .withCompatibleMode(CompatibleMode.COMPATIBLE)
+ .withCodegen(false)
+ .build();
+ fory2.register(MyExt.class, "my_ext");
+ fory2.registerSerializer(MyExt.class, MyExtSerializer.class);
+ fory2.register(EmptyWrapper.class, "my_wrapper");
+ _testSkipCustom(fory1, fory2, language, command, "test_skip_name_custom");
+ }
+
+ private void testConsistentNamed(Language language, List<String> command)
+ throws java.io.IOException {
+ Fory fory =
+ Fory.builder()
+ .withLanguage(Language.XLANG)
+ .withCompatibleMode(CompatibleMode.SCHEMA_CONSISTENT)
+ .withCodegen(false)
+ .withClassVersionCheck(false)
+ .build();
+ fory.register(Color.class, "color");
+ fory.register(MyStruct.class, "my_struct");
+ fory.register(MyExt.class, "my_ext");
+ fory.registerSerializer(MyExt.class, MyExtSerializer.class);
+
+ MyStruct myStruct = new MyStruct(42);
+ MyExt myExt = new MyExt(43);
+ MemoryBuffer buffer = MemoryBuffer.newHeapBuffer(32);
+ fory.serialize(buffer, Color.White);
+ fory.serialize(buffer, Color.White);
+ fory.serialize(buffer, Color.White);
+ // todo: checkVersion
+ // fory.serialize(buffer, myStruct);
+ fory.serialize(buffer, myExt);
+ fory.serialize(buffer, myExt);
+ fory.serialize(buffer, myExt);
+ byte[] bytes = buffer.getBytes(0, buffer.writerIndex());
+ Path dataFile = Files.createTempFile("test_consistent_named", "data");
+ Pair<Map<String, String>, File> env_workdir = setFilePath(language, command, dataFile, bytes);
+ Assert.assertTrue(executeCommand(command, 30, env_workdir.getLeft(), env_workdir.getRight()));
+ MemoryBuffer buffer2 = MemoryUtils.wrap(Files.readAllBytes(dataFile));
+ Assert.assertEquals(fory.deserialize(buffer2), Color.White);
+ Assert.assertEquals(fory.deserialize(buffer2), Color.White);
+ Assert.assertEquals(fory.deserialize(buffer2), Color.White);
+ Assert.assertEquals(fory.deserialize(buffer2), myExt);
+ Assert.assertEquals(fory.deserialize(buffer2), myExt);
+ Assert.assertEquals(fory.deserialize(buffer2), myExt);
+ }
+
/**
* Execute an external command.
*
diff --git a/rust/fory-core/src/fory.rs b/rust/fory-core/src/fory.rs
index f48d69a21..a94d5810a 100644
--- a/rust/fory-core/src/fory.rs
+++ b/rust/fory-core/src/fory.rs
@@ -20,6 +20,7 @@ use crate::ensure;
use crate::error::Error;
use crate::resolver::context::ReadContext;
use crate::resolver::context::WriteContext;
+use crate::resolver::metastring_resolver::MetaStringResolver;
use crate::resolver::type_resolver::{TypeInfo, TypeResolver};
use crate::serializer::ForyDefault;
use crate::serializer::{Serializer, StructSerializer};
@@ -30,6 +31,8 @@ use crate::types::{
};
use crate::util::get_ext_actual_type_id;
use anyhow::anyhow;
+use std::cell::RefCell;
+use std::rc::Rc;
static EMPTY_STRING: String = String::new();
@@ -38,6 +41,7 @@ pub struct Fory {
xlang: bool,
share_meta: bool,
type_resolver: TypeResolver,
+ metastring_resolver: Rc<RefCell<MetaStringResolver>>,
compress_string: bool,
}
@@ -48,6 +52,7 @@ impl Default for Fory {
xlang: true,
share_meta: false,
type_resolver: TypeResolver::default(),
+ metastring_resolver: Rc::from(RefCell::from(MetaStringResolver::default())),
compress_string: false,
}
}
@@ -83,6 +88,14 @@ impl Fory {
self.share_meta
}
+ pub fn get_type_resolver(&self) -> &TypeResolver {
+ &self.type_resolver
+ }
+
+ pub fn get_metastring_resolver(&self) -> Rc<RefCell<MetaStringResolver>> {
+ Rc::clone(&self.metastring_resolver)
+ }
+
pub fn write_head<T: Serializer>(&self, is_none: bool, writer: &mut Writer) {
const HEAD_SIZE: usize = 10;
writer.reserve(T::fory_reserved_space() + SIZE_OF_REF_AND_TYPE + HEAD_SIZE);
@@ -147,7 +160,9 @@ impl Fory {
pub fn deserialize<T: Serializer + ForyDefault>(&self, bf: &[u8]) -> Result<T, Error> {
let reader = Reader::new(bf);
let mut context = ReadContext::new(self, reader);
- self.deserialize_with_context(&mut context)
+ let result = self.deserialize_with_context(&mut context);
+ assert_eq!(context.reader.slice_after_cursor().len(), 0);
+ result
}
pub fn deserialize_with_context<T: Serializer + ForyDefault>(
@@ -198,10 +213,6 @@ impl Fory {
context.writer.dump()
}
- pub fn get_type_resolver(&self) -> &TypeResolver {
- &self.type_resolver
- }
-
pub fn register<T: 'static + StructSerializer + Serializer + ForyDefault>(&mut self, id: u32) {
let actual_type_id = T::fory_actual_type_id(id, false, &self.mode);
let type_info =
@@ -228,7 +239,7 @@ impl Fory {
pub fn register_serializer<T: Serializer + ForyDefault>(&mut self, id: u32) {
let actual_type_id = get_ext_actual_type_id(id, false);
- let type_info = TypeInfo::new_with_empty_def::<T>(
+ let type_info = TypeInfo::new_with_empty_fields::<T>(
self,
actual_type_id,
&EMPTY_STRING,
@@ -238,25 +249,29 @@ impl Fory {
self.type_resolver.register_serializer::<T>(&type_info);
}
- pub fn register_serializer_by_name<T: Serializer + ForyDefault>(
+ pub fn register_serializer_by_namespace<T: Serializer + ForyDefault>(
&mut self,
- type_name: &str,
namespace: &str,
+ type_name: &str,
) {
- let actual_type_id = get_ext_actual_type_id(0, false);
+ let actual_type_id = get_ext_actual_type_id(0, true);
let type_info =
- TypeInfo::new_with_empty_def::<T>(self, actual_type_id, namespace, type_name, true);
+ TypeInfo::new_with_empty_fields::<T>(self, actual_type_id, namespace, type_name, true);
self.type_resolver.register_serializer::<T>(&type_info);
}
+
+ pub fn register_serializer_by_name<T: Serializer + ForyDefault>(&mut self, type_name: &str) {
+ self.register_serializer_by_namespace::<T>("", type_name);
+ }
}
-pub fn write<T: Serializer>(this: &T, context: &mut WriteContext, is_field: bool) {
- T::fory_write(this, context, is_field);
+pub fn write_data<T: Serializer>(this: &T, context: &mut WriteContext, is_field: bool) {
+ T::fory_write_data(this, context, is_field);
}
-pub fn read<T: Serializer + ForyDefault>(
+pub fn read_data<T: Serializer + ForyDefault>(
context: &mut ReadContext,
is_field: bool,
) -> Result<T, Error> {
- T::fory_read(context, is_field)
+ T::fory_read_data(context, is_field)
}
diff --git a/rust/fory-core/src/meta/meta_string.rs b/rust/fory-core/src/meta/meta_string.rs
index bddc8f11a..513232fe4 100644
--- a/rust/fory-core/src/meta/meta_string.rs
+++ b/rust/fory-core/src/meta/meta_string.rs
@@ -43,30 +43,6 @@ pub enum Encoding {
AllToLowerSpecial = 0x04,
}
-#[derive(Clone, Debug, Default, Hash, PartialEq, Eq)]
-pub struct MetaStringBytes {
- pub data: Vec<u8>,
- pub hash: i64,
-}
-
-impl MetaStringBytes {
- pub fn from(_str: &MetaString) -> Self {
- unimplemented!()
- // let bytes = str.bytes.clone();
- // let value = (murmurhash3_x64_128(&bytes, 47).0 as i64).abs();
- // let hash = if value == 0 { value+256 } else { value } & 0xffffffffffffff00;
- // let hash = hash | (str.encoding.clone() as i64 & HEADER_MASK);
- // Self {
- // data: bytes,
- // hash,
- // }
- }
-
- pub fn to(&self) -> MetaString {
- unimplemented!()
- }
-}
-
#[derive(Debug, Clone, Default)]
pub struct MetaString {
pub original: String,
diff --git a/rust/fory-core/src/meta/mod.rs b/rust/fory-core/src/meta/mod.rs
index 7ec3239aa..d80a13eb8 100644
--- a/rust/fory-core/src/meta/mod.rs
+++ b/rust/fory-core/src/meta/mod.rs
@@ -20,9 +20,8 @@ mod string_util;
mod type_meta;
pub use meta_string::{
- Encoding, MetaString, MetaStringBytes, MetaStringDecoder, MetaStringEncoder,
- FIELD_NAME_DECODER, FIELD_NAME_ENCODER, NAMESPACE_DECODER, NAMESPACE_ENCODER,
- TYPE_NAME_DECODER, TYPE_NAME_ENCODER,
+ Encoding, MetaString, MetaStringDecoder, MetaStringEncoder, FIELD_NAME_DECODER,
+ FIELD_NAME_ENCODER, NAMESPACE_DECODER, NAMESPACE_ENCODER, TYPE_NAME_DECODER, TYPE_NAME_ENCODER,
};
pub use string_util::{buffer_rw_string, get_latin1_length, is_latin, murmurhash3_x64_128};
pub use type_meta::{
diff --git a/rust/fory-core/src/meta/type_meta.rs b/rust/fory-core/src/meta/type_meta.rs
index d45f921da..88581e729 100644
--- a/rust/fory-core/src/meta/type_meta.rs
+++ b/rust/fory-core/src/meta/type_meta.rs
@@ -19,9 +19,9 @@ use crate::buffer::{Reader, Writer};
use crate::error::Error;
use crate::meta::{
murmurhash3_x64_128, Encoding, MetaString, MetaStringDecoder, FIELD_NAME_DECODER,
- FIELD_NAME_ENCODER, NAMESPACE_DECODER,
+ FIELD_NAME_ENCODER, NAMESPACE_DECODER, TYPE_NAME_DECODER,
};
-use crate::types::TypeId;
+use crate::types::{TypeId, FINAL_TYPES, PRIMITIVE_ARRAY_TYPES, PRIMITIVE_TYPES};
use anyhow::anyhow;
use std::clone::Clone;
use std::cmp::min;
@@ -356,7 +356,7 @@ impl TypeMetaLayer {
}
pub fn read_type_name(reader: &mut Reader) -> MetaString {
- Self::read_name(reader, &NAMESPACE_DECODER, TYPE_NAME_ENCODINGS)
+ Self::read_name(reader, &TYPE_NAME_DECODER, TYPE_NAME_ENCODINGS)
}
fn to_bytes(&self) -> Result<Vec<u8>, Error> {
@@ -385,6 +385,132 @@ impl TypeMetaLayer {
Ok(writer.dump())
}
+ fn sort_field_infos(field_infos: &[FieldInfo]) -> Vec<FieldInfo> {
+ // group
+ let mut primitive_fields = Vec::new();
+ let mut nullable_primitive_fields = Vec::new();
+ let mut final_fields = Vec::new();
+ let mut other_fields = Vec::new();
+ let mut unknown_fields = Vec::new();
+ let mut collection_fields = Vec::new();
+ let mut map_fields = Vec::new();
+ for field_info in field_infos.iter() {
+ let mut type_id = field_info.field_type.type_id;
+ if type_id == TypeId::ForyNullable as u32 {
+ type_id = field_info.field_type.generics.first().unwrap().type_id;
+ if PRIMITIVE_TYPES.contains(&type_id) {
+ nullable_primitive_fields.push(field_info.clone());
+ continue;
+ }
+ }
+ let internal_id = type_id & 0xff;
+ if PRIMITIVE_TYPES.contains(&type_id) {
+ primitive_fields.push(field_info.clone());
+ } else if PRIMITIVE_ARRAY_TYPES.contains(&type_id)
+ || FINAL_TYPES.contains(&type_id)
+ || [TypeId::ENUM as u32, TypeId::NAMED_ENUM as u32].contains(&internal_id)
+ {
+ final_fields.push(field_info.clone());
+ } else if [TypeId::LIST as u32, TypeId::SET as u32].contains(&type_id) {
+ collection_fields.push(field_info.clone());
+ } else if TypeId::MAP as u32 == type_id {
+ map_fields.push(field_info.clone());
+ } else if [
+ TypeId::COMPATIBLE_STRUCT as u32,
+ TypeId::NAMED_COMPATIBLE_STRUCT as u32,
+ TypeId::EXT as u32,
+ TypeId::NAMED_EXT as u32,
+ ]
+ .contains(&internal_id)
+ {
+ other_fields.push(field_info.clone());
+ } else if internal_id == TypeId::UNKNOWN as u32 {
+ unknown_fields.push(field_info.clone());
+ } else {
+ unreachable!("type_id: {type_id}");
+ }
+ }
+ fn sorter(a: &FieldInfo, b: &FieldInfo) -> std::cmp::Ordering {
+ let a_id = if a.field_type.type_id == TypeId::ForyNullable as u32 {
+ a.field_type.generics.first().unwrap().type_id
+ } else {
+ a.field_type.type_id
+ };
+ let b_id = if b.field_type.type_id == TypeId::ForyNullable as u32 {
+ b.field_type.generics.first().unwrap().type_id
+ } else {
+ b.field_type.type_id
+ };
+ let a_field_name = &a.field_name;
+ let b_field_name = &b.field_name;
+ a_id.cmp(&b_id).then_with(|| a_field_name.cmp(b_field_name))
+ }
+ fn get_primitive_type_size(type_id_num: u32) -> i32 {
+ let type_id = TypeId::try_from(type_id_num as i16).unwrap();
+ match type_id {
+ TypeId::BOOL => 1,
+ TypeId::INT8 => 1,
+ TypeId::INT16 => 2,
+ TypeId::INT32 => 4,
+ TypeId::VAR_INT32 => 4,
+ TypeId::INT64 => 8,
+ TypeId::VAR_INT64 => 8,
+ TypeId::FLOAT16 => 2,
+ TypeId::FLOAT32 => 4,
+ TypeId::FLOAT64 => 8,
+ _ => unreachable!(),
+ }
+ }
+ fn is_compress(type_id: u32) -> bool {
+ [
+ TypeId::INT32 as u32,
+ TypeId::INT64 as u32,
+ TypeId::VAR_INT32 as u32,
+ TypeId::VAR_INT64 as u32,
+ ]
+ .contains(&type_id)
+ }
+ fn numeric_sorter(a: &FieldInfo, b: &FieldInfo) -> std::cmp::Ordering {
+ let (a_id, b_id) = {
+ // for nullable_primitive
+ if a.field_type.type_id == TypeId::ForyNullable as u32 {
+ (
+ a.field_type.generics.first().unwrap().type_id,
+ b.field_type.generics.first().unwrap().type_id,
+ )
+ } else {
+ (a.field_type.type_id, b.field_type.type_id)
+ }
+ };
+ let a_field_name = &a.field_name;
+ let b_field_name = &b.field_name;
+ let compress_a = is_compress(a_id);
+ let compress_b = is_compress(b_id);
+ let size_a = get_primitive_type_size(a_id);
+ let size_b = get_primitive_type_size(b_id);
+ compress_a
+ .cmp(&compress_b)
+ .then_with(|| size_b.cmp(&size_a))
+ .then_with(|| a_field_name.cmp(b_field_name))
+ }
+ primitive_fields.sort_by(numeric_sorter);
+ nullable_primitive_fields.sort_by(numeric_sorter);
+ final_fields.sort_by(sorter);
+ other_fields.sort_by(sorter);
+ unknown_fields.sort_by(sorter);
+ collection_fields.sort_by(sorter);
+ map_fields.sort_by(sorter);
+ let mut sorted_field_infos = Vec::with_capacity(field_infos.len());
+ sorted_field_infos.extend(primitive_fields);
+ sorted_field_infos.extend(nullable_primitive_fields);
+ sorted_field_infos.extend(final_fields);
+ sorted_field_infos.extend(other_fields);
+ sorted_field_infos.extend(unknown_fields);
+ sorted_field_infos.extend(collection_fields);
+ sorted_field_infos.extend(map_fields);
+ sorted_field_infos
+ }
+
fn from_bytes(reader: &mut Reader) -> TypeMetaLayer {
let meta_header = reader.read_u8();
let register_by_name = (meta_header & REGISTER_BY_NAME_FLAG) != 0;
@@ -398,7 +524,7 @@ impl TypeMetaLayer {
if register_by_name {
namespace = Self::read_namespace(reader);
type_name = Self::read_type_name(reader);
- type_id = TypeId::UNKNOWN as u32;
+ type_id = 0;
} else {
type_id = reader.read_varuint32();
let empty_name = MetaString::default();
@@ -409,8 +535,14 @@ impl TypeMetaLayer {
for _ in 0..num_fields {
field_infos.push(FieldInfo::from_bytes(reader));
}
-
- TypeMetaLayer::new(type_id, namespace, type_name, register_by_name, field_infos)
+ let sorted_field_infos = Self::sort_field_infos(&field_infos);
+ TypeMetaLayer::new(
+ type_id,
+ namespace,
+ type_name,
+ register_by_name,
+ sorted_field_infos,
+ )
}
}
diff --git a/rust/fory-core/src/resolver/meta_resolver.rs b/rust/fory-core/src/resolver/meta_resolver.rs
index 6434d9c06..fc13edb0e 100644
--- a/rust/fory-core/src/resolver/meta_resolver.rs
+++ b/rust/fory-core/src/resolver/meta_resolver.rs
@@ -36,8 +36,8 @@ impl MetaReaderResolver {
let meta_size = reader.read_varuint32();
// self.reading_type_defs.reserve(meta_size as usize);
for _ in 0..meta_size {
- self.reading_type_defs
- .push(Rc::new(TypeMeta::from_bytes(reader)));
+ let type_meta = TypeMeta::from_bytes(reader);
+ self.reading_type_defs.push(Rc::new(type_meta));
}
reader.get_cursor()
}
diff --git a/rust/fory-core/src/resolver/metastring_resolver.rs b/rust/fory-core/src/resolver/metastring_resolver.rs
index 88c540583..71489d0ea 100644
--- a/rust/fory-core/src/resolver/metastring_resolver.rs
+++ b/rust/fory-core/src/resolver/metastring_resolver.rs
@@ -15,28 +15,388 @@
// specific language governing permissions and limitations
// under the License.
-use crate::meta::{MetaString, MetaStringBytes};
use std::collections::HashMap;
+use std::convert::TryInto;
+
+use crate::buffer::Writer;
+use crate::meta::murmurhash3_x64_128;
+use crate::meta::{Encoding, MetaString};
+use crate::resolver::context::{ReadContext, WriteContext};
+
+#[derive(Debug, Clone, PartialEq, Eq, Hash)]
+pub struct MetaStringBytes {
+ pub bytes: Vec<u8>,
+ pub hash_code: i64,
+ pub encoding: Encoding,
+ pub first8: u64,
+ pub second8: u64,
+ pub dynamic_write_id: i16,
+}
+
+const HEADER_MASK: i64 = 0xff;
+
+fn byte_to_encoding(byte: u8) -> Encoding {
+ match byte {
+ 0 => Encoding::Utf8,
+ 1 => Encoding::LowerSpecial,
+ 2 => Encoding::LowerUpperDigitSpecial,
+ 3 => Encoding::FirstToLowerSpecial,
+ 4 => Encoding::AllToLowerSpecial,
+ _ => unreachable!(),
+ }
+}
+
+impl MetaStringBytes {
+ pub const DEFAULT_DYNAMIC_WRITE_STRING_ID: i16 = -1;
+ pub const EMPTY: MetaStringBytes = MetaStringBytes {
+ bytes: Vec::new(),
+ hash_code: 0,
+ encoding: Encoding::Utf8,
+ first8: 0,
+ second8: 0,
+ dynamic_write_id: MetaStringBytes::DEFAULT_DYNAMIC_WRITE_STRING_ID,
+ };
+
+ pub fn new(
+ bytes: Vec<u8>,
+ hash_code: i64,
+ encoding: Encoding,
+ first8: u64,
+ second8: u64,
+ ) -> Self {
+ MetaStringBytes {
+ bytes,
+ hash_code,
+ encoding,
+ first8,
+ second8,
+ dynamic_write_id: MetaStringBytes::DEFAULT_DYNAMIC_WRITE_STRING_ID,
+ }
+ }
+
+ pub fn decode_lossy(&self) -> String {
+ String::from_utf8_lossy(&self.bytes).into_owned()
+ }
+
+ pub(crate) fn from_metastring(meta_string: &MetaString) -> Self {
+ let bytes = meta_string.bytes.to_vec();
+ let mut hash_code = murmurhash3_x64_128(&bytes, 47).0 as i64;
+ hash_code = hash_code.abs();
+ if hash_code == 0 {
+ hash_code += 256;
+ }
+ hash_code = (hash_code as u64 & 0xffffffffffffff00) as i64;
+ let encoding = meta_string.encoding;
+ let header = encoding as i64 & HEADER_MASK;
+ hash_code |= header;
+ let header = (hash_code & HEADER_MASK) as u8;
+ let encoding = byte_to_encoding(header);
+ let mut data = bytes.clone();
+ if data.len() < 16 {
+ data.resize(16, 0);
+ }
+ let first8 = u64::from_le_bytes(data[0..8].try_into().unwrap());
+ let second8 = u64::from_le_bytes(data[8..16].try_into().unwrap());
+ Self::new(bytes, hash_code, encoding, first8, second8)
+ }
+}
#[derive(Default)]
pub struct MetaStringResolver {
- metastring_to_bytes_map: HashMap<MetaString, MetaStringBytes>,
+ meta_string_bytes_to_string: HashMap<MetaStringBytes, String>,
+
+ hash_to_meta: HashMap<i64, MetaStringBytes>,
+
+ small_map: HashMap<(u64, u64, u8), MetaStringBytes>,
+
+ meta_string_to_bytes: HashMap<MetaString, MetaStringBytes>,
+
+ dynamic_written: Vec<Option<MetaStringBytes>>,
+ dynamic_read: Vec<Option<MetaStringBytes>>,
+
+ dynamic_write_id: usize,
+ dynamic_read_id: usize,
}
impl MetaStringResolver {
+ const INITIAL_CAPACITY: usize = 8;
+ const SMALL_STRING_THRESHOLD: usize = 16;
+
pub fn new() -> Self {
- Self {
- metastring_to_bytes_map: HashMap::new(),
+ MetaStringResolver {
+ meta_string_bytes_to_string: HashMap::with_capacity(Self::INITIAL_CAPACITY),
+ hash_to_meta: HashMap::with_capacity(Self::INITIAL_CAPACITY),
+ small_map: HashMap::with_capacity(Self::INITIAL_CAPACITY),
+ meta_string_to_bytes: HashMap::with_capacity(Self::INITIAL_CAPACITY),
+ dynamic_written: vec![None; 32],
+ dynamic_read: vec![None; 32],
+ dynamic_write_id: 0,
+ dynamic_read_id: 0,
+ }
+ }
+
+ pub fn get_or_create_meta_string_bytes(&mut self, m: &MetaString) -> MetaStringBytes {
+ if let Some(b) = self.meta_string_to_bytes.get(m) {
+ return b.clone();
+ }
+ let bytes = m.bytes.clone();
+ let hash_code = murmurhash3_x64_128(&bytes, 47).0 as i64;
+ let encoding = m.encoding;
+ let mut first8: u64 = 0;
+ let mut second8: u64 = 0;
+ for (i, b) in bytes.iter().take(8).enumerate() {
+ first8 |= (*b as u64) << (8 * i);
+ }
+ if bytes.len() > 8 {
+ for j in 0..usize::min(8, bytes.len() - 8) {
+ second8 |= (bytes[8 + j] as u64) << (8 * j);
+ }
+ }
+ let msb = MetaStringBytes::new(bytes.clone(), hash_code, encoding, first8, second8);
+ self.meta_string_to_bytes.insert(m.clone(), msb.clone());
+ msb
+ }
+
+ pub fn write_meta_string_bytes_with_flag(&mut self, w: &mut Writer, mut mb: MetaStringBytes) {
+ let id = mb.dynamic_write_id;
+ if id == MetaStringBytes::DEFAULT_DYNAMIC_WRITE_STRING_ID {
+ // allocate id
+ let id_usize = self.dynamic_write_id;
+ self.dynamic_write_id += 1;
+ mb.dynamic_write_id = id_usize as i16;
+ // grow dynamic_written if needed
+ if id_usize >= self.dynamic_written.len() {
+ self.dynamic_written.resize(id_usize * 2, None);
+ }
+ self.dynamic_written[id_usize] = Some(mb.clone());
+
+ let len = mb.bytes.len();
+ // last bit `1` indicates class is written by name instead of registered id.
+ let header = ((len as u32) << 2) | 0b1;
+ w.write_varuint32(header);
+
+ if len > Self::SMALL_STRING_THRESHOLD {
+ w.write_i64(mb.hash_code);
+ } else {
+ w.write_u8(mb.encoding as i16 as u8);
+ }
+ w.write_bytes(&mb.bytes);
+ } else {
+ // write id reference: ((id + 1) << 2) | 0b11
+ let header = ((id as u32 + 1) << 2) | 0b11;
+ w.write_varuint32(header);
+ }
+ }
+
+ pub fn write_meta_string_bytes(&mut self, context: &mut WriteContext, ms: &MetaString) {
+ let mut mb = MetaStringBytes::from_metastring(ms);
+ let id = mb.dynamic_write_id;
+ if id == MetaStringBytes::DEFAULT_DYNAMIC_WRITE_STRING_ID {
+ let id_usize = self.dynamic_write_id;
+ self.dynamic_write_id += 1;
+ mb.dynamic_write_id = id_usize as i16;
+ if id_usize >= self.dynamic_written.len() {
+ self.dynamic_written.resize(id_usize * 2 + 1, None);
+ }
+ self.dynamic_written[id_usize] = Some(mb.clone());
+
+ let len = mb.bytes.len();
+ context.writer.write_varuint32((len as u32) << 1);
+ if len > Self::SMALL_STRING_THRESHOLD {
+ context.writer.write_i64(mb.hash_code);
+ } else {
+ context.writer.write_u8(mb.encoding as i16 as u8);
+ }
+ context.writer.write_bytes(&mb.bytes);
+ } else {
+ let header = ((id as u32 + 1) << 1) | 1;
+ context.writer.write_varuint32(header);
+ }
+ }
+
+ pub fn read_meta_string_bytes_with_flag(
+ &mut self,
+ context: &mut ReadContext,
+ header: u32,
+ ) -> MetaStringBytes {
+ let len = (header >> 2) as usize;
+ if (header & 0b10) == 0 {
+ // by-name path
+ if len <= Self::SMALL_STRING_THRESHOLD {
+ let mb = self.read_small_meta_string_bytes(context, len);
+ self.update_dynamic_string(mb.clone());
+ mb
+ } else {
+ let hash_code = context.reader.read_i64();
+ let mb = self.read_big_meta_string_bytes(context, len, hash_code);
+ self.update_dynamic_string(mb.clone());
+ mb
+ }
+ } else {
+ let idx = len - 1;
+ self.dynamic_read[idx]
+ .as_ref()
+ .expect("dynamic id not found")
+ .clone()
+ }
+ }
+
+ pub fn read_meta_string_bytes(&mut self, context: &mut ReadContext) -> MetaStringBytes {
+ let header = context.reader.read_varuint32();
+ let len = (header >> 1) as usize;
+ if (header & 0b1) == 0 {
+ if len > Self::SMALL_STRING_THRESHOLD {
+ let hash_code = context.reader.read_i64();
+ let mb = self.read_big_meta_string_bytes(context, len, hash_code);
+ self.update_dynamic_string(mb.clone());
+ mb
+ } else {
+ let mb = self.read_small_meta_string_bytes(context, len);
+ self.update_dynamic_string(mb.clone());
+ mb
+ }
+ } else {
+ let idx = len - 1;
+ self.dynamic_read[idx]
+ .as_ref()
+ .expect("dynamic id not found")
+ .clone()
+ }
+ }
+
+ fn read_big_meta_string_bytes(
+ &mut self,
+ context: &mut ReadContext,
+ len: usize,
+ hash_code: i64,
+ ) -> MetaStringBytes {
+ if let Some(existing) = self.hash_to_meta.get(&hash_code) {
+ // skip bytes
+ context.reader.skip(len as u32);
+ existing.clone()
+ } else {
+ let slice = context.reader.read_bytes(len);
+ let bytes = slice.to_vec();
+ let mb = {
+ // compute first8/second8 like createSmall
+ let mut first8: u64 = 0;
+ let mut second8: u64 = 0;
+ for (i, b) in bytes.iter().enumerate().take(8) {
+ first8 |= (*b as u64) << (8 * i);
+ }
+ if bytes.len() > 8 {
+ for j in 0..usize::min(8, bytes.len() - 8) {
+ second8 |= (bytes[8 + j] as u64) << (8 * j);
+ }
+ }
+ MetaStringBytes::new(bytes, hash_code, Encoding::Utf8, first8, second8)
+ };
+ self.hash_to_meta.insert(hash_code, mb.clone());
+ mb
+ }
+ }
+
+ fn read_small_meta_string_bytes(
+ &mut self,
+ context: &mut ReadContext,
+ len: usize,
+ ) -> MetaStringBytes {
+ let encoding_val = context.reader.read_u8();
+ if len == 0 {
+ // assert encoding is UTF-8
+ debug_assert_eq!(encoding_val, Encoding::Utf8 as i16 as u8);
+ return MetaStringBytes::EMPTY.clone();
+ }
+ let (v1, v2) = if len <= 8 {
+ let v1 = Self::read_bytes_as_u64(context, len);
+ (v1, 0u64)
+ } else {
+ let v1 = context.reader.read_i64() as u64;
+ let v2 = Self::read_bytes_as_u64(context, len - 8);
+ (v1, v2)
+ };
+ let key = (v1, v2, encoding_val);
+ if let Some(existing) = self.small_map.get(&key) {
+ existing.clone()
+ } else {
+ let mut data = Vec::with_capacity(len);
+ for i in 0..usize::min(8, len) {
+ data.push(((v1 >> (8 * i)) & 0xFF) as u8);
+ }
+ if len > 8 {
+ for j in 0..(len - 8) {
+ data.push(((v2 >> (8 * j)) & 0xFF) as u8);
+ }
+ }
+ let mut data_trimmed = data;
+ data_trimmed.truncate(len);
+ let hash_code = (murmurhash3_x64_128(&data_trimmed, 47).0 as i64).abs();
+ let hash_code =
+ (hash_code as u64 & 0xffffffffffffff00_u64) as i64 | (encoding_val as i64);
+ let mb = MetaStringBytes::new(
+ data_trimmed.clone(),
+ hash_code,
+ byte_to_encoding(encoding_val),
+ v1,
+ v2,
+ );
+ self.small_map.insert(key, mb.clone());
+ mb
+ }
+ }
+
+ fn read_bytes_as_u64(context: &mut ReadContext, len: usize) -> u64 {
+ let mut v: u64 = 0;
+ let slice = context.reader.read_bytes(len);
+ for (i, b) in slice.iter().take(len).enumerate() {
+ v |= (*b as u64) << (8 * i);
+ }
+ v
+ }
+
+ fn update_dynamic_string(&mut self, mb: MetaStringBytes) {
+ let id = self.dynamic_read_id;
+ self.dynamic_read_id += 1;
+ if id >= self.dynamic_read.len() {
+ self.dynamic_read.resize(id * 2 + 1, None);
+ }
+ self.dynamic_read[id] = Some(mb);
+ }
+
+ pub fn reset(&mut self) {
+ self.reset_read();
+ self.reset_write();
+ }
+
+ pub fn reset_read(&mut self) {
+ if self.dynamic_read_id != 0 {
+ for i in 0..self.dynamic_read_id {
+ self.dynamic_read[i] = None;
+ }
+ self.dynamic_read_id = 0;
+ }
+ }
+
+ pub fn reset_write(&mut self) {
+ if self.dynamic_write_id != 0 {
+ for i in 0..self.dynamic_write_id {
+ if let Some(ref mut mb) = self.dynamic_written[i] {
+ mb.dynamic_write_id = MetaStringBytes::DEFAULT_DYNAMIC_WRITE_STRING_ID;
+ }
+ self.dynamic_written[i] = None;
+ }
+ self.dynamic_write_id = 0;
}
}
- pub fn encode_metastring(&mut self, str: &MetaString) -> MetaStringBytes {
- if let Some(existing) = self.metastring_to_bytes_map.get(str) {
- return existing.clone();
+ pub fn read_meta_string(&mut self, context: &mut ReadContext) -> String {
+ let mb = self.read_meta_string_bytes(context);
+ if let Some(s) = self.meta_string_bytes_to_string.get(&mb) {
+ s.clone()
+ } else {
+ let s = mb.decode_lossy();
+ self.meta_string_bytes_to_string.insert(mb, s.clone());
+ s
}
- let metastring_bytes = MetaStringBytes::from(str);
- self.metastring_to_bytes_map
- .insert(str.clone(), metastring_bytes.clone());
- metastring_bytes
}
}
diff --git a/rust/fory-core/src/resolver/type_resolver.rs b/rust/fory-core/src/resolver/type_resolver.rs
index d6f3f58ad..2d17aa760 100644
--- a/rust/fory-core/src/resolver/type_resolver.rs
+++ b/rust/fory-core/src/resolver/type_resolver.rs
@@ -19,62 +19,60 @@ use super::context::{ReadContext, WriteContext};
use crate::error::Error;
use crate::fory::Fory;
use crate::meta::{
- MetaString, NAMESPACE_ENCODER, NAMESPACE_ENCODINGS, TYPE_NAME_ENCODER, TYPE_NAME_ENCODINGS,
+ MetaString, TypeMeta, NAMESPACE_ENCODER, NAMESPACE_ENCODINGS, TYPE_NAME_ENCODER,
+ TYPE_NAME_ENCODINGS,
};
use crate::serializer::{ForyDefault, Serializer, StructSerializer};
use std::cell::RefCell;
-use std::sync::Arc;
use std::{any::Any, collections::HashMap};
-type SerializerFn = fn(&dyn Any, &mut WriteContext, is_field: bool);
-type DeserializerFn =
+type WriteFn = fn(&dyn Any, &mut WriteContext, is_field: bool);
+type ReadFn =
fn(&mut ReadContext, is_field: bool, skip_ref_flag: bool) -> Result<Box<dyn Any>, Error>;
-type SerializerNoRefFn = fn(&dyn Any, &mut WriteContext, is_field: bool);
-type DeserializerNoRefFn = fn(&mut ReadContext, is_field: bool) -> Result<Box<dyn Any>, Error>;
-type ToSerializerFn = fn(Box<dyn Any>) -> Result<Box<dyn crate::serializer::Serializer>, Error>;
-pub type ExtWriteFn = dyn Fn(&dyn Any, &mut WriteContext, bool) + Send + Sync;
-pub type ExtReadFn = dyn Fn(&mut ReadContext, bool) -> Result<Box<dyn Any>, Error> + Send + Sync;
+type WriteDataFn = fn(&dyn Any, &mut WriteContext, is_field: bool);
+type ReadDataFn = fn(&mut ReadContext, is_field: bool) -> Result<Box<dyn Any>, Error>;
+type ToSerializerFn = fn(Box<dyn Any>) -> Result<Box<dyn Serializer>, Error>;
pub struct Harness {
- serializer: SerializerFn,
- deserializer: DeserializerFn,
- serializer_no_ref: SerializerNoRefFn,
- deserializer_no_ref: DeserializerNoRefFn,
+ write_fn: WriteFn,
+ read_fn: ReadFn,
+ write_data_fn: WriteDataFn,
+ read_data_fn: ReadDataFn,
to_serializer: ToSerializerFn,
}
impl Harness {
pub fn new(
- serializer: SerializerFn,
- deserializer: DeserializerFn,
- serializer_no_ref: SerializerNoRefFn,
- deserializer_no_ref: DeserializerNoRefFn,
+ write_fn: WriteFn,
+ read_fn: ReadFn,
+ write_data_fn: WriteDataFn,
+ read_data_fn: ReadDataFn,
to_serializer: ToSerializerFn,
) -> Harness {
Harness {
- serializer,
- deserializer,
- serializer_no_ref,
- deserializer_no_ref,
+ write_fn,
+ read_fn,
+ write_data_fn,
+ read_data_fn,
to_serializer,
}
}
- pub fn get_serializer(&self) -> SerializerFn {
- self.serializer
+ pub fn get_write_fn(&self) -> WriteFn {
+ self.write_fn
}
- pub fn get_deserializer(&self) -> DeserializerFn {
- self.deserializer
+ pub fn get_read_fn(&self) -> ReadFn {
+ self.read_fn
}
- pub fn get_serializer_no_ref(&self) -> SerializerNoRefFn {
- self.serializer_no_ref
+ pub fn get_write_data_fn(&self) -> WriteDataFn {
+ self.write_data_fn
}
- pub fn get_deserializer_no_ref(&self) -> DeserializerNoRefFn {
- self.deserializer_no_ref
+ pub fn get_read_data_fn(&self) -> ReadDataFn {
+ self.read_data_fn
}
pub fn get_to_serializer(&self) -> ToSerializerFn {
@@ -82,36 +80,6 @@ impl Harness {
}
}
-pub struct ExtHarness {
- write_fn: Arc<ExtWriteFn>,
- read_fn: Arc<ExtReadFn>,
-}
-
-impl ExtHarness {
- pub fn new<T, W, R>(write_fn: W, read_fn: R) -> ExtHarness
- where
- T: 'static,
- W: Fn(&T, &mut WriteContext, bool) + Send + Sync + 'static,
- R: Fn(&mut ReadContext, bool) -> Result<T, Error> + Send + Sync + 'static,
- {
- Self {
- write_fn: Arc::new(move |obj, ctx, is_field| {
- let obj = obj.downcast_ref::<T>().unwrap();
- write_fn(obj, ctx, is_field);
- }),
- read_fn: Arc::new(move |ctx, is_field| Ok(Box::new(read_fn(ctx, is_field)?))),
- }
- }
-
- pub fn get_write_fn(&self) -> Arc<ExtWriteFn> {
- Arc::clone(&self.write_fn)
- }
-
- pub fn get_read_fn(&self) -> Arc<ExtReadFn> {
- Arc::clone(&self.read_fn)
- }
-}
-
#[derive(Clone, Debug)]
pub struct TypeInfo {
type_def: Vec<u8>,
@@ -150,7 +118,7 @@ impl TypeInfo {
}
}
- pub fn new_with_empty_def<T: Serializer>(
+ pub fn new_with_empty_fields<T: Serializer>(
_fory: &Fory,
type_id: u32,
namespace: &str,
@@ -163,8 +131,16 @@ impl TypeInfo {
let type_name_metastring = TYPE_NAME_ENCODER
.encode_with_encodings(type_name, TYPE_NAME_ENCODINGS)
.unwrap();
+ let meta = TypeMeta::from_fields(
+ type_id,
+ namespace_metastring.clone(),
+ type_name_metastring.clone(),
+ register_by_name,
+ vec![],
+ );
+ let type_def = meta.to_bytes().unwrap();
TypeInfo {
- type_def: vec![],
+ type_def,
type_id,
namespace: namespace_metastring,
type_name: type_name_metastring,
@@ -196,8 +172,6 @@ impl TypeInfo {
pub struct TypeResolver {
serializer_map: HashMap<u32, Harness>,
name_serializer_map: HashMap<(MetaString, MetaString), Harness>,
- ext_serializer_map: HashMap<u32, ExtHarness>,
- ext_name_serializer_map: HashMap<(MetaString, MetaString), ExtHarness>,
type_id_map: HashMap<std::any::TypeId, u32>,
type_name_map: HashMap<std::any::TypeId, (MetaString, MetaString)>,
type_info_cache: HashMap<std::any::TypeId, TypeInfo>,
@@ -213,8 +187,6 @@ impl Default for TypeResolver {
let mut resolver = TypeResolver {
serializer_map: HashMap::new(),
name_serializer_map: HashMap::new(),
- ext_serializer_map: HashMap::new(),
- ext_name_serializer_map: HashMap::new(),
type_id_map: HashMap::new(),
type_name_map: HashMap::new(),
type_info_cache: HashMap::new(),
@@ -293,7 +265,7 @@ impl TypeResolver {
&mut self,
type_info: &TypeInfo,
) {
- fn serializer<T2: 'static + Serializer>(
+ fn write<T2: 'static + Serializer>(
this: &dyn Any,
context: &mut WriteContext,
is_field: bool,
@@ -315,7 +287,7 @@ impl TypeResolver {
}
}
- fn deserializer<T2: 'static + Serializer + ForyDefault>(
+ fn read<T2: 'static + Serializer + ForyDefault>(
context: &mut ReadContext,
is_field: bool,
skip_ref_flag: bool,
@@ -331,7 +303,7 @@ impl TypeResolver {
}
}
- fn serializer_no_ref<T2: 'static + Serializer>(
+ fn write_data<T2: 'static + Serializer>(
this: &dyn Any,
context: &mut WriteContext,
is_field: bool,
@@ -345,7 +317,7 @@ impl TypeResolver {
}
}
- fn deserializer_no_ref<T2: 'static + Serializer + ForyDefault>(
+ fn read_data<T2: 'static + Serializer + ForyDefault>(
context: &mut ReadContext,
is_field: bool,
) -> Result<Box<dyn Any>, Error> {
@@ -357,9 +329,9 @@ impl TypeResolver {
fn to_serializer<T2: 'static + Serializer>(
boxed_any: Box<dyn Any>,
- ) -> Result<Box<dyn crate::serializer::Serializer>, Error> {
+ ) -> Result<Box<dyn Serializer>, Error> {
match boxed_any.downcast::<T2>() {
- Ok(concrete) => Ok(Box::new(*concrete) as Box<dyn crate::serializer::Serializer>),
+ Ok(concrete) => Ok(Box::new(*concrete) as Box<dyn Serializer>),
Err(_) => Err(Error::Other(anyhow::anyhow!(
"Failed to downcast to concrete type"
))),
@@ -393,10 +365,10 @@ impl TypeResolver {
self.name_serializer_map.insert(
key,
Harness::new(
- serializer::<T>,
- deserializer::<T>,
- serializer_no_ref::<T>,
- deserializer_no_ref::<T>,
+ write::<T>,
+ read::<T>,
+ write_data::<T>,
+ read_data::<T>,
to_serializer::<T>,
),
);
@@ -409,10 +381,10 @@ impl TypeResolver {
self.serializer_map.insert(
type_id,
Harness::new(
- serializer::<T>,
- deserializer::<T>,
- serializer_no_ref::<T>,
- deserializer_no_ref::<T>,
+ write::<T>,
+ read::<T>,
+ write_data::<T>,
+ read_data::<T>,
to_serializer::<T>,
),
);
@@ -420,7 +392,7 @@ impl TypeResolver {
}
pub fn register_serializer<T: Serializer + ForyDefault>(&mut self, type_info: &TypeInfo) {
- fn serializer<T2: 'static + Serializer>(
+ fn write<T2: 'static + Serializer>(
this: &dyn Any,
context: &mut WriteContext,
is_field: bool,
@@ -434,7 +406,7 @@ impl TypeResolver {
}
}
- fn deserializer<T2: 'static + Serializer + ForyDefault>(
+ fn read<T2: 'static + Serializer + ForyDefault>(
context: &mut ReadContext,
is_field: bool,
skip_ref_flag: bool,
@@ -452,7 +424,7 @@ impl TypeResolver {
}
}
- fn serializer_no_ref<T2: 'static + Serializer>(
+ fn write_data<T2: 'static + Serializer>(
this: &dyn Any,
context: &mut WriteContext,
is_field: bool,
@@ -466,7 +438,7 @@ impl TypeResolver {
}
}
- fn deserializer_no_ref<T2: 'static + Serializer + ForyDefault>(
+ fn read_data<T2: 'static + Serializer + ForyDefault>(
context: &mut ReadContext,
is_field: bool,
) -> Result<Box<dyn Any>, Error> {
@@ -506,10 +478,10 @@ impl TypeResolver {
self.name_serializer_map.insert(
key,
Harness::new(
- serializer::<T>,
- deserializer::<T>,
- serializer_no_ref::<T>,
- deserializer_no_ref::<T>,
+ write::<T>,
+ read::<T>,
+ write_data::<T>,
+ read_data::<T>,
to_serializer::<T>,
),
);
@@ -522,10 +494,10 @@ impl TypeResolver {
self.serializer_map.insert(
type_id,
Harness::new(
- serializer::<T>,
- deserializer::<T>,
- serializer_no_ref::<T>,
- deserializer_no_ref::<T>,
+ write::<T>,
+ read::<T>,
+ write_data::<T>,
+ read_data::<T>,
to_serializer::<T>,
),
);
@@ -549,17 +521,17 @@ impl TypeResolver {
self.name_serializer_map.get(&key)
}
- pub fn get_ext_harness(&self, id: u32) -> Option<&ExtHarness> {
- self.ext_serializer_map.get(&id)
+ pub fn get_ext_harness(&self, id: u32) -> &Harness {
+ self.serializer_map
+ .get(&id)
+ .unwrap_or_else(|| panic!("ext type must be registered in both peers"))
}
- pub fn get_ext_name_harness(
- &self,
- namespace: &MetaString,
- type_name: &MetaString,
- ) -> Option<&ExtHarness> {
+ pub fn get_ext_name_harness(&self, namespace: &MetaString, type_name: &MetaString) -> &Harness {
let key = (namespace.clone(), type_name.clone());
- self.ext_name_serializer_map.get(&key)
+ self.name_serializer_map
+ .get(&key)
+ .expect("named_ext type must be registered in both peers")
}
pub fn get_sorted_field_names<T: StructSerializer>(
diff --git a/rust/fory-core/src/serializer/any.rs b/rust/fory-core/src/serializer/any.rs
index 6ada17f55..f72a0a086 100644
--- a/rust/fory-core/src/serializer/any.rs
+++ b/rust/fory-core/src/serializer/any.rs
@@ -30,7 +30,7 @@ pub fn serialize_any_box(any_box: &Box<dyn Any>, context: &mut WriteContext, is_
let concrete_type_id = (**any_box).type_id();
let harness = context.write_any_typeinfo(concrete_type_id);
- let serializer_fn = harness.get_serializer_no_ref();
+ let serializer_fn = harness.get_write_data_fn();
serializer_fn(&**any_box, context, is_field);
}
@@ -43,7 +43,7 @@ pub fn deserialize_any_box(context: &mut ReadContext) -> Result<Box<dyn Any>, Er
)));
}
let harness = context.read_any_typeinfo();
- let deserializer_fn = harness.get_deserializer_no_ref();
+ let deserializer_fn = harness.get_read_data_fn();
deserializer_fn(context, true)
}
@@ -109,7 +109,7 @@ impl Serializer for Rc<dyn Any> {
if !context.ref_writer.try_write_rc_ref(context.writer, self) {
let concrete_type_id = (**self).type_id();
let harness = context.write_any_typeinfo(concrete_type_id);
- let serializer_fn = harness.get_serializer_no_ref();
+ let serializer_fn = harness.get_write_data_fn();
serializer_fn(&**self, context, is_field);
}
}
@@ -134,13 +134,13 @@ impl Serializer for Rc<dyn Any> {
}
RefFlag::NotNullValue => {
let harness = context.read_any_typeinfo();
- let deserializer_fn = harness.get_deserializer_no_ref();
+ let deserializer_fn = harness.get_read_data_fn();
let boxed = deserializer_fn(context, true)?;
Ok(Rc::<dyn Any>::from(boxed))
}
RefFlag::RefValue => {
let harness = context.read_any_typeinfo();
- let deserializer_fn = harness.get_deserializer_no_ref();
+ let deserializer_fn = harness.get_read_data_fn();
let boxed = deserializer_fn(context, true)?;
let rc: Rc<dyn Any> = Rc::from(boxed);
context.ref_reader.store_rc_ref(rc.clone());
@@ -192,7 +192,7 @@ impl Serializer for Arc<dyn Any> {
if !context.ref_writer.try_write_arc_ref(context.writer, self) {
let concrete_type_id = (**self).type_id();
let harness = context.write_any_typeinfo(concrete_type_id);
- let serializer_fn = harness.get_serializer_no_ref();
+ let serializer_fn = harness.get_write_data_fn();
serializer_fn(&**self, context, is_field);
}
}
@@ -217,13 +217,13 @@ impl Serializer for Arc<dyn Any> {
}
RefFlag::NotNullValue => {
let harness = context.read_any_typeinfo();
- let deserializer_fn = harness.get_deserializer_no_ref();
+ let deserializer_fn = harness.get_read_data_fn();
let boxed = deserializer_fn(context, true)?;
Ok(Arc::<dyn Any>::from(boxed))
}
RefFlag::RefValue => {
let harness = context.read_any_typeinfo();
- let deserializer_fn = harness.get_deserializer_no_ref();
+ let deserializer_fn = harness.get_read_data_fn();
let boxed = deserializer_fn(context, true)?;
let arc: Arc<dyn Any> = Arc::from(boxed);
context.ref_reader.store_arc_ref(arc.clone());
diff --git a/rust/fory-core/src/serializer/bool.rs b/rust/fory-core/src/serializer/bool.rs
index 541de9bd3..aedc14ff0 100644
--- a/rust/fory-core/src/serializer/bool.rs
+++ b/rust/fory-core/src/serializer/bool.rs
@@ -19,7 +19,7 @@ use crate::error::Error;
use crate::fory::Fory;
use crate::resolver::context::ReadContext;
use crate::resolver::context::WriteContext;
-use crate::serializer::{ForyDefault, Serializer};
+use crate::serializer::{read_type_info, write_type_info, ForyDefault, Serializer};
use crate::types::TypeId;
use std::mem;
@@ -47,6 +47,14 @@ impl Serializer for bool {
fn as_any(&self) -> &dyn std::any::Any {
self
}
+
+ fn fory_write_type_info(context: &mut WriteContext, is_field: bool) {
+ write_type_info::<Self>(context, is_field);
+ }
+
+ fn fory_read_type_info(context: &mut ReadContext, is_field: bool) {
+ read_type_info::<Self>(context, is_field);
+ }
}
impl ForyDefault for bool {
diff --git a/rust/fory-core/src/serializer/collection.rs b/rust/fory-core/src/serializer/collection.rs
index 0a95f16c0..979a8a281 100644
--- a/rust/fory-core/src/serializer/collection.rs
+++ b/rust/fory-core/src/serializer/collection.rs
@@ -19,7 +19,7 @@ use crate::error::Error;
use crate::resolver::context::ReadContext;
use crate::resolver::context::WriteContext;
use crate::serializer::{ForyDefault, Serializer};
-use crate::types::Mode;
+use crate::types::PRIMITIVE_ARRAY_TYPES;
// const TRACKING_REF: u8 = 0b1;
@@ -36,9 +36,10 @@ pub fn write_collection_type_info(
is_field: bool,
collection_type_id: u32,
) {
- if *context.get_fory().get_mode() == Mode::Compatible && !is_field {
- context.writer.write_varuint32(collection_type_id);
+ if is_field {
+ return;
}
+ context.writer.write_varuint32(collection_type_id);
}
pub fn write_collection<'a, T: Serializer + 'a, I: IntoIterator<Item = &'a T>>(
@@ -93,10 +94,15 @@ pub fn read_collection_type_info(
is_field: bool,
collection_type_id: u32,
) {
- if *context.get_fory().get_mode() == Mode::Compatible && !is_field {
- let remote_collection_type_id = context.reader.read_varuint32();
- assert_eq!(remote_collection_type_id, collection_type_id);
+ if is_field {
+ return;
+ }
+ let remote_collection_type_id = context.reader.read_varuint32();
+ assert_eq!(collection_type_id, remote_collection_type_id);
+ if PRIMITIVE_ARRAY_TYPES.contains(&remote_collection_type_id) {
+ panic!("Vec<number> belongs to the `number_array` type, and Vec<Option<number>> belongs to the `list` type. You should not read data of type `number_array` as data of type `list`");
}
+ assert_eq!(remote_collection_type_id, collection_type_id);
}
pub fn read_collection<C, T>(context: &mut ReadContext) -> Result<C, Error>
diff --git a/rust/fory-core/src/serializer/datetime.rs b/rust/fory-core/src/serializer/datetime.rs
index b1d47a2f5..52bc2c714 100644
--- a/rust/fory-core/src/serializer/datetime.rs
+++ b/rust/fory-core/src/serializer/datetime.rs
@@ -19,8 +19,8 @@ use crate::error::Error;
use crate::fory::Fory;
use crate::resolver::context::ReadContext;
use crate::resolver::context::WriteContext;
-use crate::serializer::ForyDefault;
use crate::serializer::Serializer;
+use crate::serializer::{read_type_info, write_type_info, ForyDefault};
use crate::types::TypeId;
use crate::util::EPOCH;
use anyhow::anyhow;
@@ -61,6 +61,14 @@ impl Serializer for NaiveDateTime {
fn as_any(&self) -> &dyn std::any::Any {
self
}
+
+ fn fory_write_type_info(context: &mut WriteContext, is_field: bool) {
+ write_type_info::<Self>(context, is_field);
+ }
+
+ fn fory_read_type_info(context: &mut ReadContext, is_field: bool) {
+ read_type_info::<Self>(context, is_field);
+ }
}
impl Serializer for NaiveDate {
@@ -93,6 +101,14 @@ impl Serializer for NaiveDate {
fn as_any(&self) -> &dyn std::any::Any {
self
}
+
+ fn fory_write_type_info(context: &mut WriteContext, is_field: bool) {
+ write_type_info::<Self>(context, is_field);
+ }
+
+ fn fory_read_type_info(context: &mut ReadContext, is_field: bool) {
+ read_type_info::<Self>(context, is_field);
+ }
}
impl ForyDefault for NaiveDateTime {
diff --git a/rust/fory-core/src/serializer/enum_.rs b/rust/fory-core/src/serializer/enum_.rs
index fc95494f8..c1ae7c7e3 100644
--- a/rust/fory-core/src/serializer/enum_.rs
+++ b/rust/fory-core/src/serializer/enum_.rs
@@ -59,13 +59,19 @@ pub fn write_type_info<T: Serializer>(context: &mut WriteContext, is_field: bool
let meta_index = context.push_meta(rs_type_id) as u32;
context.writer.write_varuint32(meta_index);
} else {
- let resolver = context.get_fory().get_type_resolver();
- let type_info = resolver.get_type_info(rs_type_id);
- let _namespace = type_info.get_namespace().to_owned();
- let _type_name = type_info.get_type_name().to_owned();
- unimplemented!("unimplement NamedEnum::write_type_info when non-share_meta")
- // context.writer.write_bytes(namespace.bytes.as_slice());
- // context.writer.write_bytes(type_name.bytes.as_slice());
+ let type_info = context
+ .get_fory()
+ .get_type_resolver()
+ .get_type_info(rs_type_id);
+ let namespace = type_info.get_namespace().to_owned();
+ let type_name = type_info.get_type_name().to_owned();
+ let resolver = context.get_fory().get_metastring_resolver();
+ resolver
+ .borrow_mut()
+ .write_meta_string_bytes(context, &namespace);
+ resolver
+ .borrow_mut()
+ .write_meta_string_bytes(context, &type_name);
}
}
@@ -84,7 +90,9 @@ pub fn read_type_info<T: Serializer>(context: &mut ReadContext, is_field: bool)
if context.get_fory().is_share_meta() {
let _meta_index = context.reader.read_varuint32();
} else {
- unimplemented!("unimplement NamedEnum::read_type_info when non-share_meta")
+ let resolver = context.get_fory().get_metastring_resolver();
+ resolver.borrow_mut().read_meta_string_bytes(context);
+ resolver.borrow_mut().read_meta_string_bytes(context);
}
}
diff --git a/rust/fory-core/src/serializer/map.rs b/rust/fory-core/src/serializer/map.rs
index 6e07e0749..a278af5c2 100644
--- a/rust/fory-core/src/serializer/map.rs
+++ b/rust/fory-core/src/serializer/map.rs
@@ -19,7 +19,10 @@ use crate::error::Error;
use crate::fory::Fory;
use crate::resolver::context::ReadContext;
use crate::resolver::context::WriteContext;
-use crate::serializer::{read_ref_info_data, write_ref_info_data, ForyDefault, Serializer};
+use crate::serializer::{
+ read_ref_info_data, read_type_info, write_ref_info_data, write_type_info, ForyDefault,
+ Serializer,
+};
use crate::types::{TypeId, SIZE_OF_REF_AND_TYPE};
use std::collections::HashMap;
use std::mem;
@@ -240,6 +243,14 @@ impl<K: Serializer + ForyDefault + Eq + std::hash::Hash, V: Serializer + ForyDef
fn as_any(&self) -> &dyn std::any::Any {
self
}
+
+ fn fory_write_type_info(context: &mut WriteContext, is_field: bool) {
+ write_type_info::<Self>(context, is_field);
+ }
+
+ fn fory_read_type_info(context: &mut ReadContext, is_field: bool) {
+ read_type_info::<Self>(context, is_field);
+ }
}
impl<K, V> ForyDefault for HashMap<K, V> {
diff --git a/rust/fory-core/src/serializer/mod.rs b/rust/fory-core/src/serializer/mod.rs
index 3e632502a..8836221d4 100644
--- a/rust/fory-core/src/serializer/mod.rs
+++ b/rust/fory-core/src/serializer/mod.rs
@@ -17,9 +17,11 @@
use crate::error::Error;
use crate::fory::Fory;
-use crate::meta::MetaString;
+use crate::meta::{MetaString, NAMESPACE_DECODER, TYPE_NAME_DECODER};
use crate::resolver::context::{ReadContext, WriteContext};
-use crate::types::{Mode, RefFlag, PRIMITIVE_TYPES};
+use crate::types::{Mode, RefFlag, TypeId, PRIMITIVE_TYPES};
+use anyhow::anyhow;
+use std::any::Any;
pub mod any;
mod arc;
@@ -96,6 +98,23 @@ pub fn read_ref_info_data<T: Serializer + ForyDefault>(
}
}
+fn write_type_info<T: Serializer>(context: &mut WriteContext, is_field: bool) {
+ if is_field {
+ return;
+ }
+ let type_id = T::fory_get_type_id(context.get_fory());
+ context.writer.write_varuint32(type_id);
+}
+
+fn read_type_info<T: Serializer>(context: &mut ReadContext, is_field: bool) {
+ if is_field {
+ return;
+ }
+ let local_type_id = T::fory_get_type_id(context.get_fory());
+ let remote_type_id = context.reader.read_varuint32();
+ assert_eq!(local_type_id, remote_type_id);
+}
+
pub fn get_skip_ref_flag<T: Serializer>(fory: &Fory) -> bool {
let elem_type_id = T::fory_get_type_id(fory);
!T::fory_is_option() && PRIMITIVE_TYPES.contains(&elem_type_id)
@@ -168,24 +187,98 @@ pub trait Serializer: 'static {
0
}
- fn fory_write_type_info(context: &mut WriteContext, is_field: bool)
+ fn fory_write_type_info(context: &mut WriteContext, _is_field: bool)
+ where
+ Self: Sized,
+ {
+ // default implementation only for ext/named_ext
+ let type_id = Self::fory_get_type_id(context.get_fory());
+ context.writer.write_varuint32(type_id);
+ if type_id & 0xff == TypeId::EXT as u32 {
+ return;
+ }
+ let rs_type_id = std::any::TypeId::of::<Self>();
+ if context.get_fory().is_share_meta() {
+ let meta_index = context.push_meta(rs_type_id) as u32;
+ context.writer.write_varuint32(meta_index);
+ } else {
+ let type_info = {
+ let type_resolver = context.get_fory().get_type_resolver();
+ type_resolver.get_type_info(rs_type_id)
+ };
+ let namespace = type_info.get_namespace().to_owned();
+ let type_name = type_info.get_type_name().to_owned();
+ let resolver = context.get_fory().get_metastring_resolver();
+ resolver
+ .borrow_mut()
+ .write_meta_string_bytes(context, &namespace);
+ resolver
+ .borrow_mut()
+ .write_meta_string_bytes(context, &type_name);
+ }
+ }
+
+ fn fory_read_type_info(context: &mut ReadContext, _is_field: bool)
where
Self: Sized,
{
- if !is_field {
- let type_id = Self::fory_get_type_id(context.get_fory());
- context.writer.write_varuint32(type_id);
+ // default implementation only for ext/named_ext
+ let local_type_id = Self::fory_get_type_id(context.get_fory());
+ let remote_type_id = context.reader.read_varuint32();
+ assert_eq!(local_type_id, remote_type_id);
+ if local_type_id & 0xff == TypeId::EXT as u32 {
+ return;
+ }
+ if context.get_fory().is_share_meta() {
+ let _meta_index = context.reader.read_varuint32();
+ } else {
+ let resolver = context.get_fory().get_metastring_resolver();
+ resolver.borrow_mut().read_meta_string_bytes(context);
+ resolver.borrow_mut().read_meta_string_bytes(context);
}
}
- fn fory_read_type_info(context: &mut ReadContext, is_field: bool)
+ // only used by struct/enum/ext
+ fn fory_read_compatible(context: &mut ReadContext) -> Result<Self, Error>
where
Self: Sized,
{
- if !is_field {
- let remote_type_id = context.reader.read_varuint32();
- let local_type_id = Self::fory_get_type_id(context.get_fory());
- assert_eq!(remote_type_id, local_type_id);
+ // default logic only for ext/named_ext
+ let remote_type_id = context.reader.read_varuint32();
+ let local_type_id = Self::fory_get_type_id(context.get_fory());
+ assert_eq!(remote_type_id, local_type_id);
+ if local_type_id & 0xff == TypeId::EXT as u32 {
+ let type_resolver = context.get_fory().get_type_resolver();
+ type_resolver
+ .get_ext_harness(local_type_id)
+ .get_read_data_fn()(context, true)
+ .and_then(|b: Box<dyn Any>| {
+ b.downcast::<Self>()
+ .map(|boxed_self| *boxed_self)
+ .map_err(|_| anyhow!("downcast to Self failed").into())
+ })
+ } else {
+ let (namespace, type_name) = if context.get_fory().is_share_meta() {
+ let meta_index = context.reader.read_varuint32();
+ let type_def = context.get_meta(meta_index as usize);
+ (type_def.get_namespace(), type_def.get_type_name())
+ } else {
+ let resolver = context.get_fory().get_metastring_resolver();
+ let nsb = resolver.borrow_mut().read_meta_string_bytes(context);
+ let tsb = resolver.borrow_mut().read_meta_string_bytes(context);
+ let ns = NAMESPACE_DECODER.decode(&nsb.bytes, nsb.encoding)?;
+ let ts = TYPE_NAME_DECODER.decode(&tsb.bytes, tsb.encoding)?;
+ (ns, ts)
+ };
+ let type_resolver = context.get_fory().get_type_resolver();
+ type_resolver
+ .get_ext_name_harness(&namespace, &type_name)
+ .get_read_data_fn()(context, true)
+ .and_then(|b: Box<dyn Any>| {
+ b.downcast::<Self>()
+ .map(|boxed_self| *boxed_self)
+ .map_err(|_| anyhow!("downcast to Self failed").into())
+ })
}
}
@@ -200,14 +293,7 @@ pub trait Serializer: 'static {
std::any::TypeId::of::<Self>()
}
- fn fory_as_any(&self) -> &dyn std::any::Any
- where
- Self: Sized,
- {
- self
- }
-
- fn as_any(&self) -> &dyn std::any::Any;
+ fn as_any(&self) -> &dyn Any;
}
pub trait StructSerializer: Serializer + 'static {
@@ -228,13 +314,6 @@ pub trait StructSerializer: Serializer + 'static {
struct_::actual_type_id(type_id, register_by_name, mode)
}
- fn fory_read_compatible(_context: &mut ReadContext) -> Result<Self, Error>
- where
- Self: Sized,
- {
- unimplemented!()
- }
-
fn fory_get_sorted_field_names(_fory: &Fory) -> Vec<String> {
unimplemented!()
}
diff --git a/rust/fory-core/src/serializer/number.rs b/rust/fory-core/src/serializer/number.rs
index ca4c8c5ed..a830fc361 100644
--- a/rust/fory-core/src/serializer/number.rs
+++ b/rust/fory-core/src/serializer/number.rs
@@ -20,7 +20,7 @@ use crate::error::Error;
use crate::fory::Fory;
use crate::resolver::context::ReadContext;
use crate::resolver::context::WriteContext;
-use crate::serializer::{ForyDefault, Serializer};
+use crate::serializer::{read_type_info, write_type_info, ForyDefault, Serializer};
use crate::types::TypeId;
macro_rules! impl_num_serializer {
@@ -49,6 +49,14 @@ macro_rules! impl_num_serializer {
fn as_any(&self) -> &dyn std::any::Any {
self
}
+
+ fn fory_write_type_info(context: &mut WriteContext, is_field: bool) {
+ write_type_info::<Self>(context, is_field);
+ }
+
+ fn fory_read_type_info(context: &mut ReadContext, is_field: bool) {
+ read_type_info::<Self>(context, is_field);
+ }
}
impl ForyDefault for $ty {
fn fory_default() -> Self {
diff --git a/rust/fory-core/src/serializer/primitive_list.rs b/rust/fory-core/src/serializer/primitive_list.rs
index fe236daac..736305e23 100644
--- a/rust/fory-core/src/serializer/primitive_list.rs
+++ b/rust/fory-core/src/serializer/primitive_list.rs
@@ -35,9 +35,10 @@ pub fn fory_write_data<T>(this: &[T], context: &mut WriteContext) {
}
pub fn fory_write_type_info(context: &mut WriteContext, is_field: bool, type_id: TypeId) {
- if *context.get_fory().get_mode() == crate::types::Mode::Compatible && !is_field {
- context.writer.write_varuint32(type_id as u32);
+ if is_field {
+ return;
}
+ context.writer.write_varuint32(type_id as u32);
}
pub fn fory_read_data<T>(context: &mut ReadContext) -> Result<Vec<T>, Error> {
@@ -57,10 +58,14 @@ pub fn fory_read_data<T>(context: &mut ReadContext) -> Result<Vec<T>, Error> {
}
pub fn fory_read_type_info(context: &mut ReadContext, is_field: bool, type_id: TypeId) {
- if *context.get_fory().get_mode() == crate::types::Mode::Compatible && !is_field {
- let remote_type_id = context.reader.read_varuint32();
- assert_eq!(remote_type_id, type_id as u32);
+ if is_field {
+ return;
}
+ let remote_type_id = context.reader.read_varuint32();
+ if remote_type_id == TypeId::LIST as u32 {
+ panic!("Vec<number> belongs to the `number_array` type, and Vec<Option<number>> belongs to the `list` type. You should not read data of type `list` as data of type `number_array`");
+ }
+ assert_eq!(remote_type_id, type_id as u32);
}
pub fn fory_reserved_space<T>() -> usize {
diff --git a/rust/fory-core/src/serializer/skip.rs b/rust/fory-core/src/serializer/skip.rs
index d27aa7e74..b43f7c82e 100644
--- a/rust/fory-core/src/serializer/skip.rs
+++ b/rust/fory-core/src/serializer/skip.rs
@@ -113,22 +113,22 @@ pub fn skip_field_value(
}
if header & crate::serializer::map::KEY_NULL != 0 {
// let read_ref_flag = get_read_ref_flag(value_type);
- skip_field_value(context, value_type, false).unwrap();
+ skip_field_value(context, value_type, false)?;
len_counter += 1;
continue;
}
if header & crate::serializer::map::VALUE_NULL != 0 {
// let read_ref_flag = get_read_ref_flag(key_type);
- skip_field_value(context, key_type, false).unwrap();
+ skip_field_value(context, key_type, false)?;
len_counter += 1;
continue;
}
let chunk_size = context.reader.read_u8();
for _ in (0..chunk_size).enumerate() {
// let read_ref_flag = get_read_ref_flag(key_type);
- skip_field_value(context, key_type, false).unwrap();
+ skip_field_value(context, key_type, false)?;
// let read_ref_flag = get_read_ref_flag(value_type);
- skip_field_value(context, value_type, false).unwrap();
+ skip_field_value(context, value_type, false)?;
}
len_counter += chunk_size as u32;
}
@@ -137,6 +137,29 @@ pub fn skip_field_value(
} else if type_id == TypeId::NAMED_ENUM {
let _ordinal = context.reader.read_varuint32();
Ok(())
+ } else if type_id == TypeId::NAMED_COMPATIBLE_STRUCT {
+ let remote_type_id = context.reader.read_varuint32();
+ assert_eq!(type_id_num, remote_type_id);
+ let meta_index = context.reader.read_varuint32();
+ let type_meta = context.get_meta(meta_index as usize);
+ let field_infos = type_meta.get_field_infos().to_vec();
+ for field_info in field_infos.iter() {
+ let nullable_field_type =
+ NullableFieldType::from(field_info.field_type.clone());
+ let read_ref_flag = get_read_ref_flag(&nullable_field_type);
+ skip_field_value(context, &nullable_field_type, read_ref_flag)?;
+ }
+ Ok(())
+ } else if type_id == TypeId::NAMED_EXT {
+ let remote_type_id = context.reader.read_varuint32();
+ assert_eq!(type_id_num, remote_type_id);
+ let meta_index = context.reader.read_varuint32();
+ let type_meta = context.get_meta(meta_index as usize);
+ let type_resolver = context.get_fory().get_type_resolver();
+ type_resolver
+ .get_ext_name_harness(&type_meta.get_namespace(), &type_meta.get_type_name())
+ .get_read_data_fn()(context, true)?;
+ Ok(())
} else {
unreachable!("unimplemented type: {:?}", type_id);
}
@@ -144,16 +167,14 @@ pub fn skip_field_value(
Err(_) => {
let internal_id = type_id_num & 0xff;
const COMPATIBLE_STRUCT_ID: u32 = TypeId::COMPATIBLE_STRUCT as u32;
- const NAMED_COMPATIBLE_STRUCT_ID: u32 = TypeId::NAMED_COMPATIBLE_STRUCT as u32;
const EXT_ID: u32 = TypeId::EXT as u32;
- const NAMED_EXT_ID: u32 = TypeId::NAMED_EXT as u32;
const ENUM_ID: u32 = TypeId::ENUM as u32;
- if internal_id == COMPATIBLE_STRUCT_ID || internal_id == NAMED_COMPATIBLE_STRUCT_ID {
+ if internal_id == COMPATIBLE_STRUCT_ID {
let remote_type_id = context.reader.read_varuint32();
let meta_index = context.reader.read_varuint32();
- let type_def = context.get_meta(meta_index as usize);
- assert_eq!(remote_type_id, type_def.get_type_id());
- let field_infos = type_def.get_field_infos().to_vec();
+ let type_meta = context.get_meta(meta_index as usize);
+ assert_eq!(remote_type_id, type_meta.get_type_id());
+ let field_infos = type_meta.get_field_infos().to_vec();
for field_info in field_infos.iter() {
let nullable_field_type =
NullableFieldType::from(field_info.field_type.clone());
@@ -163,16 +184,14 @@ pub fn skip_field_value(
} else if internal_id == ENUM_ID {
let _ordinal = context.reader.read_varuint32();
} else if internal_id == EXT_ID {
+ let remote_type_id = context.reader.read_varuint32();
+ assert_eq!(remote_type_id, type_id_num);
let type_resolver = context.get_fory().get_type_resolver();
type_resolver
.get_ext_harness(type_id_num)
- .unwrap()
- .get_read_fn()(context, true)
- .unwrap();
- } else if internal_id == NAMED_EXT_ID {
- unimplemented!("NAMED_EXT_ID");
- // let type_resolver = context.get_fory().get_type_resolver();
- // type_resolver.get_ext_name_harness(type_id_num).unwrap().get_read_fn()(context, true).unwrap();
+ .get_read_data_fn()(context, true)?;
+ } else {
+ unreachable!("unimplemented skipped type: {:?}", type_id_num);
}
Ok(())
}
diff --git a/rust/fory-core/src/serializer/string.rs b/rust/fory-core/src/serializer/string.rs
index 1ffa47328..65c2eb77b 100644
--- a/rust/fory-core/src/serializer/string.rs
+++ b/rust/fory-core/src/serializer/string.rs
@@ -20,7 +20,7 @@ use crate::fory::Fory;
use crate::meta::get_latin1_length;
use crate::resolver::context::ReadContext;
use crate::resolver::context::WriteContext;
-use crate::serializer::{ForyDefault, Serializer};
+use crate::serializer::{read_type_info, write_type_info, ForyDefault, Serializer};
use crate::types::TypeId;
use std::mem;
@@ -86,6 +86,14 @@ impl Serializer for String {
fn as_any(&self) -> &dyn std::any::Any {
self
}
+
+ fn fory_write_type_info(context: &mut WriteContext, is_field: bool) {
+ write_type_info::<Self>(context, is_field);
+ }
+
+ fn fory_read_type_info(context: &mut ReadContext, is_field: bool) {
+ read_type_info::<Self>(context, is_field);
+ }
}
impl ForyDefault for String {
diff --git a/rust/fory-core/src/serializer/struct_.rs b/rust/fory-core/src/serializer/struct_.rs
index 06ffb64b3..b8b553c72 100644
--- a/rust/fory-core/src/serializer/struct_.rs
+++ b/rust/fory-core/src/serializer/struct_.rs
@@ -79,9 +79,15 @@ pub fn write_type_info<T: Serializer>(context: &mut WriteContext, _is_field: boo
.get_fory()
.get_type_resolver()
.get_type_info(rs_type_id);
- let _namespace = type_info.get_namespace();
- let _type_name = type_info.get_type_name();
- unimplemented!("unimplement NamedStruct::write_type_info in consistent_mode")
+ let namespace = type_info.get_namespace().to_owned();
+ let type_name = type_info.get_type_name().to_owned();
+ let resolver = context.get_fory().get_metastring_resolver();
+ resolver
+ .borrow_mut()
+ .write_meta_string_bytes(context, &namespace);
+ resolver
+ .borrow_mut()
+ .write_meta_string_bytes(context, &type_name);
}
} else if type_id & 0xff == TypeId::NAMED_COMPATIBLE_STRUCT as u32
|| type_id & 0xff == TypeId::COMPATIBLE_STRUCT as u32
@@ -101,7 +107,9 @@ pub fn read_type_info<T: Serializer>(context: &mut ReadContext, _is_field: bool)
if context.get_fory().is_share_meta() {
let _meta_index = context.reader.read_varuint32();
} else {
- unimplemented!("unimplement NamedStruct::read_type_info when non-share_meta")
+ let resolver = context.get_fory().get_metastring_resolver();
+ resolver.borrow_mut().read_meta_string_bytes(context);
+ resolver.borrow_mut().read_meta_string_bytes(context);
}
} else if local_type_id & 0xff == TypeId::NAMED_COMPATIBLE_STRUCT as u32
|| local_type_id & 0xff == TypeId::COMPATIBLE_STRUCT as u32
diff --git a/rust/fory-core/src/serializer/trait_object.rs b/rust/fory-core/src/serializer/trait_object.rs
index 3be82443c..96533e1ff 100644
--- a/rust/fory-core/src/serializer/trait_object.rs
+++ b/rust/fory-core/src/serializer/trait_object.rs
@@ -397,7 +397,7 @@ macro_rules! impl_smart_pointer_serializer {
let any_obj = <dyn $trait_name as $crate::serializer::Serializer>::as_any(&*self.0);
let concrete_type_id = any_obj.type_id();
let harness = context.write_any_typeinfo(concrete_type_id);
- let serializer_fn = harness.get_serializer_no_ref();
+ let serializer_fn = harness.get_write_data_fn();
serializer_fn(any_obj, context, is_field);
}
}
@@ -426,7 +426,7 @@ macro_rules! impl_smart_pointer_serializer {
}
RefFlag::NotNullValue => {
let harness = context.read_any_typeinfo();
- let deserializer_fn = harness.get_deserializer_no_ref();
+ let deserializer_fn = harness.get_read_data_fn();
let boxed_any = deserializer_fn(context, is_field)?;
$(
@@ -444,7 +444,7 @@ macro_rules! impl_smart_pointer_serializer {
}
RefFlag::RefValue => {
let harness = context.read_any_typeinfo();
- let deserializer_fn = harness.get_deserializer_no_ref();
+ let deserializer_fn = harness.get_read_data_fn();
let boxed_any = deserializer_fn(context, is_field)?;
$(
@@ -561,7 +561,7 @@ impl Serializer for Box<dyn Serializer> {
let type_resolver = context.get_fory().get_type_resolver();
if let Some(harness) = type_resolver.get_harness(fory_type_id) {
- let deserializer_fn = harness.get_deserializer();
+ let deserializer_fn = harness.get_read_fn();
let to_serializer_fn = harness.get_to_serializer();
let boxed_any = deserializer_fn(context, is_field, true)?;
let trait_object = to_serializer_fn(boxed_any)?;
diff --git a/rust/fory-core/src/types.rs b/rust/fory-core/src/types.rs
index 8e98a0c3f..5ec2d5403 100644
--- a/rust/fory-core/src/types.rs
+++ b/rust/fory-core/src/types.rs
@@ -134,17 +134,21 @@ pub static PRIMITIVE_TYPES: [u32; 7] = [
TypeId::FLOAT64 as u32,
];
-pub static FINAL_TYPES: [TypeId; 3] = [TypeId::STRING, TypeId::LOCAL_DATE, TypeId::TIMESTAMP];
+pub static FINAL_TYPES: [u32; 3] = [
+ TypeId::STRING as u32,
+ TypeId::LOCAL_DATE as u32,
+ TypeId::TIMESTAMP as u32,
+];
-pub static PRIMITIVE_ARRAY_TYPES: [TypeId; 8] = [
- TypeId::BOOL_ARRAY,
- TypeId::BINARY,
- TypeId::INT8_ARRAY,
- TypeId::INT16_ARRAY,
- TypeId::INT32_ARRAY,
- TypeId::INT64_ARRAY,
- TypeId::FLOAT32_ARRAY,
- TypeId::FLOAT64_ARRAY,
+pub static PRIMITIVE_ARRAY_TYPES: [u32; 8] = [
+ TypeId::BOOL_ARRAY as u32,
+ TypeId::BINARY as u32,
+ TypeId::INT8_ARRAY as u32,
+ TypeId::INT16_ARRAY as u32,
+ TypeId::INT32_ARRAY as u32,
+ TypeId::INT64_ARRAY as u32,
+ TypeId::FLOAT32_ARRAY as u32,
+ TypeId::FLOAT64_ARRAY as u32,
];
pub static BASIC_TYPE_NAMES: [&str; 10] = [
diff --git a/rust/fory-derive/src/object/misc.rs b/rust/fory-derive/src/object/misc.rs
index ee943214c..28ba6d2b5 100644
--- a/rust/fory-derive/src/object/misc.rs
+++ b/rust/fory-derive/src/object/misc.rs
@@ -83,7 +83,6 @@ pub fn gen_type_def(fields: &[&Field]) -> TokenStream {
let field_infos = fields.iter().map(|field| {
let ty = &field.ty;
let name = format!("{}", field.ident.as_ref().expect("should be field name"));
-
match classify_trait_object_field(ty) {
TraitObjectField::None => {
let generic_tree = parse_generic_tree(ty);
@@ -92,6 +91,22 @@ pub fn gen_type_def(fields: &[&Field]) -> TokenStream {
fory_core::meta::FieldInfo::new(#name, #generic_token)
}
}
+ TraitObjectField::VecRc(_) | TraitObjectField::VecArc(_) => {
+ quote! {
+ fory_core::meta::FieldInfo::new(#name, fory_core::meta::FieldType {
+ type_id: fory_core::types::TypeId::LIST as u32,
+ generics: Vec::new()
+ })
+ }
+ }
+ TraitObjectField::HashMapRc(..) | TraitObjectField::HashMapArc(..) => {
+ quote! {
+ fory_core::meta::FieldInfo::new(#name, fory_core::meta::FieldType {
+ type_id: fory_core::types::TypeId::MAP as u32,
+ generics: Vec::new()
+ })
+ }
+ }
_ => {
quote! {
fory_core::meta::FieldInfo::new(#name, fory_core::meta::FieldType {
diff --git a/rust/fory-derive/src/object/read.rs b/rust/fory-derive/src/object/read.rs
index ae4a2d819..e31b5bdb5 100644
--- a/rust/fory-derive/src/object/read.rs
+++ b/rust/fory-derive/src/object/read.rs
@@ -102,7 +102,7 @@ fn gen_read_match_arm(field: &Field, private_ident: &Ident) -> TokenStream {
.get_harness(fory_type_id)
.expect("Type not registered for trait object field");
- let deserializer_fn = harness.get_deserializer();
+ let deserializer_fn = harness.get_read_fn();
let any_box = deserializer_fn(context, true, false)?;
let base_type_id = fory_type_id >> 8;
@@ -293,7 +293,7 @@ fn gen_read_compatible_match_arm(field: &Field, var_name: &Ident) -> TokenStream
.get_type_resolver()
.get_harness(fory_type_id)
.expect("Type not registered for trait object field");
- let deserializer_fn = harness.get_deserializer();
+ let deserializer_fn = harness.get_read_fn();
let any_box = deserializer_fn(context, true, false).unwrap();
let base_type_id = fory_type_id >> 8;
#var_name = #helper_mod::#from_any_fn(any_box, base_type_id).unwrap();
@@ -436,7 +436,7 @@ pub fn gen_read(struct_ident: &Ident) -> TokenStream {
<Self as fory_core::serializer::Serializer>::fory_read_data(context, false)
},
fory_core::types::Mode::Compatible => {
- <#struct_ident as fory_core::serializer::StructSerializer>::fory_read_compatible(context)
+ <#struct_ident as fory_core::serializer::Serializer>::fory_read_compatible(context)
},
_ => unreachable!()
}
diff --git a/rust/fory-derive/src/object/serializer.rs b/rust/fory-derive/src/object/serializer.rs
index 6646dd617..ca75547de 100644
--- a/rust/fory-derive/src/object/serializer.rs
+++ b/rust/fory-derive/src/object/serializer.rs
@@ -140,10 +140,6 @@ pub fn derive_serializer(ast: &syn::DeriveInput) -> TokenStream {
fn fory_type_def(fory: &fory_core::fory::Fory, type_id: u32, namespace: fory_core::meta::MetaString, type_name: fory_core::meta::MetaString, register_by_name: bool) -> Vec<u8> {
#type_def_ts
}
-
- fn fory_read_compatible(context: &mut fory_core::resolver::context::ReadContext) -> Result<Self, fory_core::error::Error> {
- #read_compatible_ts
- }
}
impl fory_core::serializer::Serializer for #name {
fn fory_get_type_id(fory: &fory_core::fory::Fory) -> u32 {
@@ -185,6 +181,10 @@ pub fn derive_serializer(ast: &syn::DeriveInput) -> TokenStream {
fn fory_read(context: &mut fory_core::resolver::context::ReadContext, is_field: bool) -> Result<Self, fory_core::error::Error> {
#read_ts
}
+
+ fn fory_read_compatible(context: &mut fory_core::resolver::context::ReadContext) -> Result<Self, fory_core::error::Error> {
+ #read_compatible_ts
+ }
}
impl #name {
#deserialize_nullable_ts
diff --git a/rust/fory-derive/src/object/util.rs b/rust/fory-derive/src/object/util.rs
index 4dde75605..3698b5e74 100644
--- a/rust/fory-derive/src/object/util.rs
+++ b/rust/fory-derive/src/object/util.rs
@@ -433,15 +433,20 @@ impl NullableTypeNode {
} else {
let type_id = cur_remote_nullable_type.type_id;
let internal_id = type_id & 0xff;
- Some(if internal_id == COMPATIBLE_STRUCT_ID || internal_id == NAMED_COMPATIBLE_STRUCT_ID {
- <#nullable_ty as fory_core::serializer::StructSerializer>::fory_read_compatible(context)
+ Some(
+ if internal_id == COMPATIBLE_STRUCT_ID
+ || internal_id == NAMED_COMPATIBLE_STRUCT_ID
+ || internal_id == ENUM_ID
+ || internal_id == NAMED_ENUM_ID
+ || internal_id == EXT_ID
+ || internal_id == NAMED_EXT_ID
+ {
+ <#nullable_ty as fory_core::serializer::Serializer>::fory_read_compatible(context)
.map_err(fory_core::error::Error::from)?
- } else if internal_id == ENUM_ID || internal_id == NAMED_ENUM_ID {
- <#nullable_ty as fory_core::serializer::StructSerializer>::fory_read_compatible(context)
- .map_err(fory_core::error::Error::from)?
- } else {
- unimplemented!()
- })
+ } else {
+ unimplemented!()
+ }
+ )
};
Ok::<#ty, fory_core::error::Error>(res1)
}
@@ -452,14 +457,17 @@ impl NullableTypeNode {
} else {
let type_id = cur_remote_nullable_type.type_id;
let internal_id = type_id & 0xff;
- if internal_id == COMPATIBLE_STRUCT_ID || internal_id == NAMED_COMPATIBLE_STRUCT_ID {
- <#nullable_ty as fory_core::serializer::StructSerializer>::fory_read_compatible(context)
- .map_err(fory_core::error::Error::from)?
- } else if internal_id == ENUM_ID || internal_id == NAMED_ENUM_ID {
- <#nullable_ty as fory_core::serializer::StructSerializer>::fory_read_compatible(context)
+ if internal_id == COMPATIBLE_STRUCT_ID
+ || internal_id == NAMED_COMPATIBLE_STRUCT_ID
+ || internal_id == ENUM_ID
+ || internal_id == NAMED_ENUM_ID
+ || internal_id == EXT_ID
+ || internal_id == NAMED_EXT_ID
+ {
+ <#nullable_ty as fory_core::serializer::Serializer>::fory_read_compatible(context)
.map_err(fory_core::error::Error::from)?
} else {
- unimplemented!("")
+ unimplemented!()
}
};
Ok::<#ty, fory_core::error::Error>(res2)
@@ -470,6 +478,8 @@ impl NullableTypeNode {
const ENUM_ID: u32 = fory_core::types::TypeId::ENUM as u32;
const NAMED_COMPATIBLE_STRUCT_ID: u32 = fory_core::types::TypeId::NAMED_COMPATIBLE_STRUCT as u32;
const NAMED_ENUM_ID: u32 = fory_core::types::TypeId::NAMED_ENUM as u32;
+ const EXT_ID: u32 = fory_core::types::TypeId::EXT as u32;
+ const NAMED_EXT_ID: u32 = fory_core::types::TypeId::NAMED_EXT as u32;
#ts
}
};
@@ -979,7 +989,13 @@ pub(super) fn get_sort_fields_ts(fields: &[&Field]) -> TokenStream {
quote! {
let field_type_id = <#ty_type as fory_core::serializer::Serializer>::fory_get_type_id(fory);
let internal_id = field_type_id & 0xff;
- if internal_id == fory_core::types::TypeId::COMPATIBLE_STRUCT as u32 || internal_id == fory_core::types::TypeId::NAMED_COMPATIBLE_STRUCT as u32 || internal_id == fory_core::types::TypeId::STRUCT as u32 || internal_id == fory_core::types::TypeId::NAMED_STRUCT as u32 {
+ if internal_id == fory_core::types::TypeId::COMPATIBLE_STRUCT as u32
+ || internal_id == fory_core::types::TypeId::NAMED_COMPATIBLE_STRUCT as u32
+ || internal_id == fory_core::types::TypeId::STRUCT as u32
+ || internal_id == fory_core::types::TypeId::NAMED_STRUCT as u32
+ || internal_id == fory_core::types::TypeId::EXT as u32
+ || internal_id == fory_core::types::TypeId::NAMED_EXT as u32
+ {
other_fields.push((field_type_id, #name.to_string()));
} else if internal_id == fory_core::types::TypeId::ENUM as u32 || internal_id == fory_core::types::TypeId::NAMED_ENUM as u32 {
final_fields.push((field_type_id, #name.to_string()));
diff --git a/rust/fory-derive/src/object/write.rs b/rust/fory-derive/src/object/write.rs
index 65fea320c..ef849dda3 100644
--- a/rust/fory-derive/src/object/write.rs
+++ b/rust/fory-derive/src/object/write.rs
@@ -118,7 +118,7 @@ fn gen_write_match_arm(field: &Field) -> TokenStream {
.get_harness(fory_type_id)
.expect("Harness not found for trait object field");
- let serializer_fn = harness.get_serializer();
+ let serializer_fn = harness.get_write_fn();
serializer_fn(any_ref, context, true);
}
}
diff --git a/rust/fory-derive/src/util.rs b/rust/fory-derive/src/util.rs
index 66373dfc1..537aa5fda 100644
--- a/rust/fory-derive/src/util.rs
+++ b/rust/fory-derive/src/util.rs
@@ -107,6 +107,7 @@ pub enum CollectionTraitInfo {
VecArc(String),
HashMapRc(Box<Type>, String),
HashMapArc(Box<Type>, String),
+ // todo HashSet
}
/// Check if a type is a collection containing Rc<dyn Trait> or Arc<dyn Trait>
diff --git a/rust/fory-core/src/meta/mod.rs b/rust/tests/tests/compatible/mod.rs
similarity index 61%
copy from rust/fory-core/src/meta/mod.rs
copy to rust/tests/tests/compatible/mod.rs
index 7ec3239aa..5e072284a 100644
--- a/rust/fory-core/src/meta/mod.rs
+++ b/rust/tests/tests/compatible/mod.rs
@@ -15,17 +15,7 @@
// specific language governing permissions and limitations
// under the License.
-mod meta_string;
-mod string_util;
-mod type_meta;
-
-pub use meta_string::{
- Encoding, MetaString, MetaStringBytes, MetaStringDecoder, MetaStringEncoder,
- FIELD_NAME_DECODER, FIELD_NAME_ENCODER, NAMESPACE_DECODER, NAMESPACE_ENCODER,
- TYPE_NAME_DECODER, TYPE_NAME_ENCODER,
-};
-pub use string_util::{buffer_rw_string, get_latin1_length, is_latin, murmurhash3_x64_128};
-pub use type_meta::{
- FieldInfo, FieldType, NullableFieldType, TypeMeta, TypeMetaLayer, NAMESPACE_ENCODINGS,
- TYPE_NAME_ENCODINGS,
-};
+mod test_basic_type;
+mod test_container;
+mod test_struct;
+mod test_struct_enum;
diff --git a/rust/tests/tests/compatible/test_basic_type.rs b/rust/tests/tests/compatible/test_basic_type.rs
new file mode 100644
index 000000000..1c9c9d69b
--- /dev/null
+++ b/rust/tests/tests/compatible/test_basic_type.rs
@@ -0,0 +1,489 @@
+// 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 chrono::{NaiveDate, NaiveDateTime};
+use fory_core::buffer::{Reader, Writer};
+use fory_core::fory::Fory;
+use fory_core::resolver::context::{ReadContext, WriteContext};
+use fory_core::types::Mode::Compatible;
+
+// primitive_val
+const BOOL_VAL: bool = true;
+const I8_VAL: i8 = 42;
+const I16_VAL: i16 = 43;
+const I32_VAL: i32 = 44;
+const I64_VAL: i64 = 45;
+const F32_VAL: f32 = 46.0;
+const F64_VAL: f64 = 47.0;
+// string
+const STR_LATIN1_VAL: &str = "Çüéâäà åçêëèïî";
+// time
+#[allow(deprecated)]
+const TIMESTAMP_VAL: NaiveDateTime = NaiveDateTime::from_timestamp(100, 0);
+#[allow(deprecated)]
+const LOCAL_DATE_VAL: NaiveDate = NaiveDate::from_ymd(2021, 11, 23);
+
+const BOOL_ARRAY: [bool; 1] = [true];
+const INT8_ARRAY: [i8; 1] = [48];
+const INT16_ARRAY: [i16; 1] = [49];
+const INT32_ARRAY: [i32; 1] = [50];
+const INT64_ARRAY: [i64; 1] = [51];
+const FLOAT32_ARRAY: [f32; 1] = [52.0];
+const FLOAT64_ARRAY: [f64; 1] = [53.0];
+
+fn serialize_non_null(fory: &Fory, context: &mut WriteContext) {
+ fory.serialize_with_context(&BOOL_VAL, context);
+ fory.serialize_with_context(&I8_VAL, context);
+ fory.serialize_with_context(&I16_VAL, context);
+ fory.serialize_with_context(&I32_VAL, context);
+ fory.serialize_with_context(&I64_VAL, context);
+ fory.serialize_with_context(&F32_VAL, context);
+ fory.serialize_with_context(&F64_VAL, context);
+ fory.serialize_with_context(&STR_LATIN1_VAL.to_string(), context);
+ fory.serialize_with_context(&LOCAL_DATE_VAL, context);
+ fory.serialize_with_context(&TIMESTAMP_VAL, context);
+
+ fory.serialize_with_context(&BOOL_ARRAY.to_vec(), context);
+ fory.serialize_with_context(&INT8_ARRAY.to_vec(), context);
+ fory.serialize_with_context(&INT16_ARRAY.to_vec(), context);
+ fory.serialize_with_context(&INT32_ARRAY.to_vec(), context);
+ fory.serialize_with_context(&INT64_ARRAY.to_vec(), context);
+ fory.serialize_with_context(&FLOAT32_ARRAY.to_vec(), context);
+ fory.serialize_with_context(&FLOAT64_ARRAY.to_vec(), context);
+}
+
+fn serialize_nullable(fory: &Fory, context: &mut WriteContext) {
+ fory.serialize_with_context(&Some(BOOL_VAL), context);
+ fory.serialize_with_context(&Some(I8_VAL), context);
+ fory.serialize_with_context(&Some(I16_VAL), context);
+ fory.serialize_with_context(&Some(I32_VAL), context);
+ fory.serialize_with_context(&Some(I64_VAL), context);
+ fory.serialize_with_context(&Some(F32_VAL), context);
+ fory.serialize_with_context(&Some(F64_VAL), context);
+ fory.serialize_with_context(&Some(STR_LATIN1_VAL.to_string()), context);
+ fory.serialize_with_context(&Some(LOCAL_DATE_VAL), context);
+ fory.serialize_with_context(&Some(TIMESTAMP_VAL), context);
+
+ fory.serialize_with_context(&Some(BOOL_ARRAY.to_vec()), context);
+ fory.serialize_with_context(&Some(INT8_ARRAY.to_vec()), context);
+ fory.serialize_with_context(&Some(INT16_ARRAY.to_vec()), context);
+ fory.serialize_with_context(&Some(INT32_ARRAY.to_vec()), context);
+ fory.serialize_with_context(&Some(INT64_ARRAY.to_vec()), context);
+ fory.serialize_with_context(&Some(FLOAT32_ARRAY.to_vec()), context);
+ fory.serialize_with_context(&Some(FLOAT64_ARRAY.to_vec()), context);
+
+ fory.serialize_with_context(&Option::<bool>::None, context);
+ fory.serialize_with_context(&Option::<i8>::None, context);
+ fory.serialize_with_context(&Option::<i16>::None, context);
+ fory.serialize_with_context(&Option::<i32>::None, context);
+ fory.serialize_with_context(&Option::<i64>::None, context);
+ fory.serialize_with_context(&Option::<f32>::None, context);
+ fory.serialize_with_context(&Option::<f64>::None, context);
+ fory.serialize_with_context(&Option::<String>::None, context);
+ fory.serialize_with_context(&Option::<NaiveDate>::None, context);
+ fory.serialize_with_context(&Option::<NaiveDateTime>::None, context);
+
+ fory.serialize_with_context(&Option::<Vec<bool>>::None, context);
+ fory.serialize_with_context(&Option::<Vec<i8>>::None, context);
+ fory.serialize_with_context(&Option::<Vec<i16>>::None, context);
+ fory.serialize_with_context(&Option::<Vec<i32>>::None, context);
+ fory.serialize_with_context(&Option::<Vec<i64>>::None, context);
+ fory.serialize_with_context(&Option::<Vec<f32>>::None, context);
+ fory.serialize_with_context(&Option::<Vec<f64>>::None, context);
+}
+
+fn deserialize_non_null(fory: &Fory, context: &mut ReadContext, auto_conv: bool, to_end: bool) {
+ assert_eq!(
+ BOOL_VAL,
+ fory.deserialize_with_context::<bool>(context).unwrap()
+ );
+ assert_eq!(
+ I8_VAL,
+ fory.deserialize_with_context::<i8>(context).unwrap()
+ );
+ assert_eq!(
+ I16_VAL,
+ fory.deserialize_with_context::<i16>(context).unwrap()
+ );
+ assert_eq!(
+ I32_VAL,
+ fory.deserialize_with_context::<i32>(context).unwrap()
+ );
+ assert_eq!(
+ I64_VAL,
+ fory.deserialize_with_context::<i64>(context).unwrap()
+ );
+ assert_eq!(
+ F32_VAL,
+ fory.deserialize_with_context::<f32>(context).unwrap()
+ );
+ assert_eq!(
+ F64_VAL,
+ fory.deserialize_with_context::<f64>(context).unwrap()
+ );
+ assert_eq!(
+ STR_LATIN1_VAL.to_string(),
+ fory.deserialize_with_context::<String>(context).unwrap()
+ );
+ assert_eq!(
+ LOCAL_DATE_VAL,
+ fory.deserialize_with_context::<NaiveDate>(context).unwrap()
+ );
+ assert_eq!(
+ TIMESTAMP_VAL,
+ fory.deserialize_with_context::<NaiveDateTime>(context)
+ .unwrap()
+ );
+
+ assert_eq!(
+ BOOL_ARRAY.to_vec(),
+ fory.deserialize_with_context::<Vec<bool>>(context).unwrap()
+ );
+ assert_eq!(
+ INT8_ARRAY.to_vec(),
+ fory.deserialize_with_context::<Vec<i8>>(context).unwrap()
+ );
+ assert_eq!(
+ INT16_ARRAY.to_vec(),
+ fory.deserialize_with_context::<Vec<i16>>(context).unwrap()
+ );
+ assert_eq!(
+ INT32_ARRAY.to_vec(),
+ fory.deserialize_with_context::<Vec<i32>>(context).unwrap()
+ );
+ assert_eq!(
+ INT64_ARRAY.to_vec(),
+ fory.deserialize_with_context::<Vec<i64>>(context).unwrap()
+ );
+ assert_eq!(
+ FLOAT32_ARRAY.to_vec(),
+ fory.deserialize_with_context::<Vec<f32>>(context).unwrap()
+ );
+ assert_eq!(
+ FLOAT64_ARRAY.to_vec(),
+ fory.deserialize_with_context::<Vec<f64>>(context).unwrap()
+ );
+ if auto_conv {
+ assert_eq!(
+ bool::default(),
+ fory.deserialize_with_context::<bool>(context).unwrap()
+ );
+ assert_eq!(
+ i8::default(),
+ fory.deserialize_with_context::<i8>(context).unwrap()
+ );
+ assert_eq!(
+ i16::default(),
+ fory.deserialize_with_context::<i16>(context).unwrap()
+ );
+ assert_eq!(
+ i32::default(),
+ fory.deserialize_with_context::<i32>(context).unwrap()
+ );
+ assert_eq!(
+ i64::default(),
+ fory.deserialize_with_context::<i64>(context).unwrap()
+ );
+ assert_eq!(
+ f32::default(),
+ fory.deserialize_with_context::<f32>(context).unwrap()
+ );
+ assert_eq!(
+ f64::default(),
+ fory.deserialize_with_context::<f64>(context).unwrap()
+ );
+ assert_eq!(
+ String::default(),
+ fory.deserialize_with_context::<String>(context).unwrap()
+ );
+ assert_eq!(
+ NaiveDate::default(),
+ fory.deserialize_with_context::<NaiveDate>(context).unwrap()
+ );
+ assert_eq!(
+ NaiveDateTime::default(),
+ fory.deserialize_with_context::<NaiveDateTime>(context)
+ .unwrap()
+ );
+
+ assert_eq!(
+ Vec::<bool>::default(),
+ fory.deserialize_with_context::<Vec<bool>>(context).unwrap()
+ );
+ assert_eq!(
+ Vec::<i8>::default(),
+ fory.deserialize_with_context::<Vec<i8>>(context).unwrap()
+ );
+ assert_eq!(
+ Vec::<i16>::default(),
+ fory.deserialize_with_context::<Vec<i16>>(context).unwrap()
+ );
+ assert_eq!(
+ Vec::<i32>::default(),
+ fory.deserialize_with_context::<Vec<i32>>(context).unwrap()
+ );
+ assert_eq!(
+ Vec::<i64>::default(),
+ fory.deserialize_with_context::<Vec<i64>>(context).unwrap()
+ );
+ assert_eq!(
+ Vec::<f32>::default(),
+ fory.deserialize_with_context::<Vec<f32>>(context).unwrap()
+ );
+ assert_eq!(
+ Vec::<f64>::default(),
+ fory.deserialize_with_context::<Vec<f64>>(context).unwrap()
+ );
+ }
+ if to_end {
+ assert_eq!(context.reader.slice_after_cursor().len(), 0);
+ }
+}
+
+fn deserialize_nullable(fory: &Fory, context: &mut ReadContext, auto_conv: bool, to_end: bool) {
+ assert_eq!(
+ Some(BOOL_VAL),
+ fory.deserialize_with_context::<Option<bool>>(context)
+ .unwrap()
+ );
+ assert_eq!(
+ Some(I8_VAL),
+ fory.deserialize_with_context::<Option<i8>>(context)
+ .unwrap()
+ );
+ assert_eq!(
+ Some(I16_VAL),
+ fory.deserialize_with_context::<Option<i16>>(context)
+ .unwrap()
+ );
+ assert_eq!(
+ Some(I32_VAL),
+ fory.deserialize_with_context::<Option<i32>>(context)
+ .unwrap()
+ );
+ assert_eq!(
+ Some(I64_VAL),
+ fory.deserialize_with_context::<Option<i64>>(context)
+ .unwrap()
+ );
+ assert_eq!(
+ Some(F32_VAL),
+ fory.deserialize_with_context::<Option<f32>>(context)
+ .unwrap()
+ );
+ assert_eq!(
+ Some(F64_VAL),
+ fory.deserialize_with_context::<Option<f64>>(context)
+ .unwrap()
+ );
+ assert_eq!(
+ Some(STR_LATIN1_VAL.to_string()),
+ fory.deserialize_with_context::<Option<String>>(context)
+ .unwrap()
+ );
+ assert_eq!(
+ Some(LOCAL_DATE_VAL),
+ fory.deserialize_with_context::<Option<NaiveDate>>(context)
+ .unwrap()
+ );
+ assert_eq!(
+ Some(TIMESTAMP_VAL),
+ fory.deserialize_with_context::<Option<NaiveDateTime>>(context)
+ .unwrap()
+ );
+
+ assert_eq!(
+ Some(BOOL_ARRAY.to_vec()),
+ fory.deserialize_with_context::<Option<Vec<bool>>>(context)
+ .unwrap()
+ );
+ assert_eq!(
+ Some(INT8_ARRAY.to_vec()),
+ fory.deserialize_with_context::<Option<Vec<i8>>>(context)
+ .unwrap()
+ );
+ assert_eq!(
+ Some(INT16_ARRAY.to_vec()),
+ fory.deserialize_with_context::<Option<Vec<i16>>>(context)
+ .unwrap()
+ );
+ assert_eq!(
+ Some(INT32_ARRAY.to_vec()),
+ fory.deserialize_with_context::<Option<Vec<i32>>>(context)
+ .unwrap()
+ );
+ assert_eq!(
+ Some(INT64_ARRAY.to_vec()),
+ fory.deserialize_with_context::<Option<Vec<i64>>>(context)
+ .unwrap()
+ );
+ assert_eq!(
+ Some(FLOAT32_ARRAY.to_vec()),
+ fory.deserialize_with_context::<Option<Vec<f32>>>(context)
+ .unwrap()
+ );
+ assert_eq!(
+ Some(FLOAT64_ARRAY.to_vec()),
+ fory.deserialize_with_context::<Option<Vec<f64>>>(context)
+ .unwrap()
+ );
+ if !auto_conv {
+ assert_eq!(
+ None,
+ fory.deserialize_with_context::<Option<bool>>(context)
+ .unwrap()
+ );
+ assert_eq!(
+ None,
+ fory.deserialize_with_context::<Option<i8>>(context)
+ .unwrap()
+ );
+ assert_eq!(
+ None,
+ fory.deserialize_with_context::<Option<i16>>(context)
+ .unwrap()
+ );
+ assert_eq!(
+ None,
+ fory.deserialize_with_context::<Option<i32>>(context)
+ .unwrap()
+ );
+ assert_eq!(
+ None,
+ fory.deserialize_with_context::<Option<i64>>(context)
+ .unwrap()
+ );
+ assert_eq!(
+ None,
+ fory.deserialize_with_context::<Option<f32>>(context)
+ .unwrap()
+ );
+ assert_eq!(
+ None,
+ fory.deserialize_with_context::<Option<f64>>(context)
+ .unwrap()
+ );
+ assert_eq!(
+ None,
+ fory.deserialize_with_context::<Option<String>>(context)
+ .unwrap()
+ );
+ assert_eq!(
+ None,
+ fory.deserialize_with_context::<Option<NaiveDate>>(context)
+ .unwrap()
+ );
+ assert_eq!(
+ None,
+ fory.deserialize_with_context::<Option<NaiveDateTime>>(context)
+ .unwrap()
+ );
+
+ assert_eq!(
+ None,
+ fory.deserialize_with_context::<Option<Vec<bool>>>(context)
+ .unwrap()
+ );
+ assert_eq!(
+ None,
+ fory.deserialize_with_context::<Option<Vec<i8>>>(context)
+ .unwrap()
+ );
+ assert_eq!(
+ None,
+ fory.deserialize_with_context::<Option<Vec<i16>>>(context)
+ .unwrap()
+ );
+ assert_eq!(
+ None,
+ fory.deserialize_with_context::<Option<Vec<i32>>>(context)
+ .unwrap()
+ );
+ assert_eq!(
+ None,
+ fory.deserialize_with_context::<Option<Vec<i64>>>(context)
+ .unwrap()
+ );
+ assert_eq!(
+ None,
+ fory.deserialize_with_context::<Option<Vec<f32>>>(context)
+ .unwrap()
+ );
+ assert_eq!(
+ None,
+ fory.deserialize_with_context::<Option<Vec<f64>>>(context)
+ .unwrap()
+ );
+ }
+ if to_end {
+ assert_eq!(context.reader.slice_after_cursor().len(), 0);
+ }
+}
+
+// non-null <-> non-null
+#[test]
+fn basic() {
+ let fory = Fory::default().mode(Compatible);
+ // serialize
+ let mut writer = Writer::default();
+ let mut write_context = WriteContext::new(&fory, &mut writer);
+ serialize_non_null(&fory, &mut write_context);
+ // deserialize
+ let bytes = write_context.writer.dump();
+ let reader = Reader::new(bytes.as_slice());
+ let mut read_context = ReadContext::new(&fory, reader);
+ deserialize_non_null(&fory, &mut read_context, false, true);
+}
+
+// nullable <-> nullable
+#[test]
+fn basic_nullable() {
+ let fory = Fory::default().mode(Compatible);
+ // serialize
+ let mut writer = Writer::default();
+ let mut write_context = WriteContext::new(&fory, &mut writer);
+ serialize_nullable(&fory, &mut write_context);
+ // deserialize
+ let bytes = write_context.writer.dump();
+ let reader = Reader::new(bytes.as_slice());
+ let mut read_context = ReadContext::new(&fory, reader);
+ deserialize_nullable(&fory, &mut read_context, false, true);
+}
+
+// non-null -> nullable -> non-null
+#[test]
+fn auto_conv() {
+ let fory = Fory::default().mode(Compatible);
+ // serialize_non-null
+ let mut writer = Writer::default();
+ let mut write_context = WriteContext::new(&fory, &mut writer);
+ serialize_non_null(&fory, &mut write_context);
+ // deserialize_nullable
+ let bytes = write_context.writer.dump();
+ let reader = Reader::new(bytes.as_slice());
+ let mut read_context: ReadContext<'_, '_> = ReadContext::new(&fory, reader);
+ deserialize_nullable(&fory, &mut read_context, true, true);
+ // serialize_nullable
+ let mut writer = Writer::default();
+ let mut write_context = WriteContext::new(&fory, &mut writer);
+ serialize_nullable(&fory, &mut write_context);
+ // deserialize_non-null
+ let bytes = write_context.writer.dump();
+ let reader = Reader::new(bytes.as_slice());
+ let mut read_context = ReadContext::new(&fory, reader);
+ deserialize_non_null(&fory, &mut read_context, true, true);
+}
diff --git a/rust/tests/tests/compatible/test_container.rs b/rust/tests/tests/compatible/test_container.rs
new file mode 100644
index 000000000..e0227b76a
--- /dev/null
+++ b/rust/tests/tests/compatible/test_container.rs
@@ -0,0 +1,565 @@
+// 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 std::collections::{HashMap, HashSet};
+
+use fory_core::buffer::{Reader, Writer};
+use fory_core::fory::Fory;
+use fory_core::resolver::context::{ReadContext, WriteContext};
+use fory_core::types::Mode::Compatible;
+use fory_derive::ForyObject;
+
+#[derive(ForyObject, PartialEq, Eq, Hash, Debug)]
+struct Item {
+ id: i32,
+}
+
+fn basic_list() -> Vec<String> {
+ vec![
+ "42".to_string(),
+ "".to_string(),
+ "43".to_string(),
+ "".to_string(),
+ "44".to_string(),
+ ]
+}
+
+fn basic_set() -> HashSet<String> {
+ HashSet::from([
+ "45".to_string(),
+ "46".to_string(),
+ "".to_string(),
+ "47".to_string(),
+ ])
+}
+
+fn basic_map() -> HashMap<String, String> {
+ HashMap::from([
+ ("48".to_string(), "49".to_string()),
+ ("".to_string(), "50".to_string()),
+ ("51".to_string(), "".to_string()),
+ ])
+}
+
+fn nullable_basic_list(deserialize_auto_conv: bool) -> Vec<Option<String>> {
+ if deserialize_auto_conv {
+ vec![
+ Some("42".to_string()),
+ Some("".to_string()),
+ Some("43".to_string()),
+ Some("".to_string()),
+ Some("44".to_string()),
+ ]
+ } else {
+ vec![
+ Some("42".to_string()),
+ Some("".to_string()),
+ Some("43".to_string()),
+ None,
+ Some("44".to_string()),
+ ]
+ }
+}
+
+fn nullable_basic_set(deserialize_auto_conv: bool) -> HashSet<Option<String>> {
+ if deserialize_auto_conv {
+ HashSet::from([
+ Some("45".to_string()),
+ Some("46".to_string()),
+ Some("47".to_string()),
+ Some("".to_string()),
+ ])
+ } else {
+ HashSet::from([
+ Some("45".to_string()),
+ Some("46".to_string()),
+ None,
+ Some("47".to_string()),
+ Some("".to_string()),
+ ])
+ }
+}
+
+fn nullable_basic_map(deserialize_auto_conv: bool) -> HashMap<Option<String>, Option<String>> {
+ if deserialize_auto_conv {
+ HashMap::from([
+ (Some("48".to_string()), Some("49".to_string())),
+ (Some("".to_string()), Some("50".to_string())),
+ (Some("51".to_string()), Some("".to_string())),
+ ])
+ } else {
+ HashMap::from([
+ (Some("48".to_string()), Some("49".to_string())),
+ (None, Some("50".to_string())),
+ (Some("51".to_string()), None),
+ ])
+ }
+}
+
+fn item_list() -> Vec<Item> {
+ vec![
+ Item { id: 42 },
+ Item { id: 0 },
+ Item { id: 43 },
+ Item { id: 0 },
+ Item { id: 44 },
+ ]
+}
+
+fn item_set() -> HashSet<Item> {
+ HashSet::from([
+ Item { id: 45 },
+ Item { id: 0 },
+ Item { id: 46 },
+ Item { id: 47 },
+ ])
+}
+
+fn item_map() -> HashMap<Item, Item> {
+ HashMap::from([
+ (Item { id: 48 }, Item { id: 49 }),
+ (Item { id: 0 }, Item { id: 50 }),
+ (Item { id: 51 }, Item { id: 0 }),
+ ])
+}
+
+fn nullable_item_list(deserialize_auto_conv: bool) -> Vec<Option<Item>> {
+ if deserialize_auto_conv {
+ vec![
+ Some(Item { id: 42 }),
+ Some(Item { id: 0 }),
+ Some(Item { id: 43 }),
+ Some(Item { id: 0 }),
+ Some(Item { id: 44 }),
+ ]
+ } else {
+ vec![
+ Some(Item { id: 42 }),
+ Some(Item { id: 0 }),
+ Some(Item { id: 43 }),
+ None,
+ Some(Item { id: 44 }),
+ ]
+ }
+}
+
+fn nullable_item_set(deserialize_auto_conv: bool) -> HashSet<Option<Item>> {
+ if deserialize_auto_conv {
+ HashSet::from([
+ Some(Item { id: 45 }),
+ Some(Item { id: 46 }),
+ Some(Item { id: 47 }),
+ Some(Item { id: 0 }),
+ ])
+ } else {
+ HashSet::from([
+ Some(Item { id: 45 }),
+ Some(Item { id: 46 }),
+ None,
+ Some(Item { id: 47 }),
+ Some(Item { id: 0 }),
+ ])
+ }
+}
+
+fn nullable_item_map(deserialize_auto_conv: bool) -> HashMap<Option<Item>, Option<Item>> {
+ if deserialize_auto_conv {
+ HashMap::from([
+ (Some(Item { id: 48 }), Some(Item { id: 49 })),
+ (Some(Item { id: 0 }), Some(Item { id: 50 })),
+ (Some(Item { id: 51 }), Some(Item { id: 0 })),
+ ])
+ } else {
+ HashMap::from([
+ (Some(Item { id: 48 }), Some(Item { id: 49 })),
+ (None, Some(Item { id: 50 })),
+ (Some(Item { id: 51 }), None),
+ ])
+ }
+}
+
+fn nested_collection() -> Vec<HashSet<Item>> {
+ vec![
+ HashSet::from([Item { id: 42 }, Item { id: 0 }, Item { id: 43 }]),
+ HashSet::from([Item { id: 44 }]),
+ ]
+}
+
+fn complex_container1() -> Vec<HashMap<Item, Item>> {
+ vec![
+ HashMap::from([(Item { id: 42 }, Item { id: 43 })]),
+ HashMap::from([(Item { id: 44 }, Item { id: 45 })]),
+ ]
+}
+
+fn complex_container2() -> Vec<HashMap<Vec<Item>, Vec<Item>>> {
+ vec![
+ HashMap::from([(
+ vec![Item { id: 42 }, Item { id: 43 }],
+ vec![Item { id: 44 }, Item { id: 45 }],
+ )]),
+ HashMap::from([(
+ vec![Item { id: 46 }, Item { id: 47 }],
+ vec![Item { id: 48 }, Item { id: 49 }],
+ )]),
+ ]
+}
+
+#[test]
+fn container_outer_auto_conv() {
+ let fory = Fory::default().mode(Compatible);
+ // serialize_outer_non-null
+ let mut writer = Writer::default();
+ let mut write_context = WriteContext::new(&fory, &mut writer);
+ fory.serialize_with_context(&basic_list(), &mut write_context);
+ fory.serialize_with_context(&basic_set(), &mut write_context);
+ fory.serialize_with_context(&basic_map(), &mut write_context);
+ // deserialize_outer_nullable
+ let bytes = write_context.writer.dump();
+ let reader = Reader::new(bytes.as_slice());
+ let mut read_context = ReadContext::new(&fory, reader);
+ assert_eq!(
+ Some(basic_list()),
+ fory.deserialize_with_context::<Option<Vec<String>>>(&mut read_context)
+ .unwrap()
+ );
+ assert_eq!(
+ Some(basic_set()),
+ fory.deserialize_with_context::<Option<HashSet<String>>>(&mut read_context)
+ .unwrap()
+ );
+ assert_eq!(
+ Some(basic_map()),
+ fory.deserialize_with_context::<Option<HashMap<String, String>>>(&mut read_context)
+ .unwrap()
+ );
+ assert_eq!(read_context.reader.slice_after_cursor().len(), 0);
+ // serialize_outer_nullable
+ let mut writer = Writer::default();
+ let mut write_context = WriteContext::new(&fory, &mut writer);
+ fory.serialize_with_context(&Some(basic_list()), &mut write_context);
+ fory.serialize_with_context(&Some(basic_set()), &mut write_context);
+ fory.serialize_with_context(&Some(basic_map()), &mut write_context);
+ fory.serialize_with_context(&Option::<Vec<String>>::None, &mut write_context);
+ fory.serialize_with_context(&Option::<HashSet<String>>::None, &mut write_context);
+ fory.serialize_with_context(&Option::<HashMap<String, String>>::None, &mut write_context);
+ // deserialize_outer_non-null
+ let bytes = write_context.writer.dump();
+ let reader = Reader::new(bytes.as_slice());
+ let mut read_context = ReadContext::new(&fory, reader);
+ assert_eq!(
+ basic_list(),
+ fory.deserialize_with_context::<Vec<String>>(&mut read_context)
+ .unwrap()
+ );
+ assert_eq!(
+ basic_set(),
+ fory.deserialize_with_context::<HashSet<String>>(&mut read_context)
+ .unwrap()
+ );
+ assert_eq!(
+ basic_map(),
+ fory.deserialize_with_context::<HashMap<String, String>>(&mut read_context)
+ .unwrap()
+ );
+ assert_eq!(
+ Vec::<String>::default(),
+ fory.deserialize_with_context::<Vec<String>>(&mut read_context)
+ .unwrap()
+ );
+ assert_eq!(
+ HashSet::default(),
+ fory.deserialize_with_context::<HashSet<String>>(&mut read_context)
+ .unwrap()
+ );
+ assert_eq!(
+ HashMap::default(),
+ fory.deserialize_with_context::<HashMap<String, String>>(&mut read_context)
+ .unwrap()
+ );
+ assert_eq!(read_context.reader.slice_after_cursor().len(), 0);
+}
+
+#[test]
+fn collection_inner() {
+ let mut fory1 = Fory::default().mode(Compatible);
+ fory1.register::<Item>(101);
+ let mut fory2 = Fory::default().mode(Compatible);
+ fory2.register_by_name::<Item>("item");
+ for fory in [fory1, fory2] {
+ // serialize
+ let mut writer = Writer::default();
+ let mut write_context = WriteContext::new(&fory, &mut writer);
+ fory.serialize_with_context(&basic_list(), &mut write_context);
+ fory.serialize_with_context(&item_list(), &mut write_context);
+ fory.serialize_with_context(&basic_set(), &mut write_context);
+ fory.serialize_with_context(&item_set(), &mut write_context);
+ fory.serialize_with_context(&nullable_basic_list(false), &mut write_context);
+ fory.serialize_with_context(&nullable_item_list(false), &mut write_context);
+ fory.serialize_with_context(&nullable_basic_set(false), &mut write_context);
+ fory.serialize_with_context(&nullable_item_set(false), &mut write_context);
+ // deserialize
+ let bytes = write_context.writer.dump();
+ let reader = Reader::new(bytes.as_slice());
+ let mut read_context = ReadContext::new(&fory, reader);
+ assert_eq!(
+ basic_list(),
+ fory.deserialize_with_context::<Vec<String>>(&mut read_context)
+ .unwrap()
+ );
+ assert_eq!(
+ item_list(),
+ fory.deserialize_with_context::<Vec<Item>>(&mut read_context)
+ .unwrap()
+ );
+ assert_eq!(
+ basic_set(),
+ fory.deserialize_with_context::<HashSet<String>>(&mut read_context)
+ .unwrap()
+ );
+ assert_eq!(
+ item_set(),
+ fory.deserialize_with_context::<HashSet<Item>>(&mut read_context)
+ .unwrap()
+ );
+ assert_eq!(
+ nullable_basic_list(false),
+ fory.deserialize_with_context::<Vec<Option<String>>>(&mut read_context)
+ .unwrap()
+ );
+ assert_eq!(
+ nullable_item_list(false),
+ fory.deserialize_with_context::<Vec<Option<Item>>>(&mut read_context)
+ .unwrap()
+ );
+ assert_eq!(
+ nullable_basic_set(false),
+ fory.deserialize_with_context::<HashSet<Option<String>>>(&mut read_context)
+ .unwrap()
+ );
+ assert_eq!(
+ nullable_item_set(false),
+ fory.deserialize_with_context::<HashSet<Option<Item>>>(&mut read_context)
+ .unwrap()
+ );
+ assert_eq!(read_context.reader.slice_after_cursor().len(), 0);
+ }
+}
+
+#[test]
+fn collection_inner_auto_conv() {
+ let mut fory1 = Fory::default().mode(Compatible);
+ fory1.register::<Item>(101);
+ let mut fory2 = Fory::default().mode(Compatible);
+ fory2.register_by_name::<Item>("item");
+ for fory in [fory1, fory2] {
+ // serialize_non-null
+ let mut writer = Writer::default();
+ let mut write_context = WriteContext::new(&fory, &mut writer);
+ fory.serialize_with_context(&basic_list(), &mut write_context);
+ fory.serialize_with_context(&item_list(), &mut write_context);
+ fory.serialize_with_context(&basic_set(), &mut write_context);
+ fory.serialize_with_context(&item_set(), &mut write_context);
+ // deserialize_nullable
+ let bytes = write_context.writer.dump();
+ let reader = Reader::new(bytes.as_slice());
+ let mut read_context = ReadContext::new(&fory, reader);
+ assert_eq!(
+ nullable_basic_list(true),
+ fory.deserialize_with_context::<Vec<Option<String>>>(&mut read_context)
+ .unwrap()
+ );
+ assert_eq!(
+ nullable_item_list(true),
+ fory.deserialize_with_context::<Vec<Option<Item>>>(&mut read_context)
+ .unwrap()
+ );
+ assert_eq!(
+ nullable_basic_set(true),
+ fory.deserialize_with_context::<HashSet<Option<String>>>(&mut read_context)
+ .unwrap()
+ );
+ assert_eq!(
+ nullable_item_set(true),
+ fory.deserialize_with_context::<HashSet<Option<Item>>>(&mut read_context)
+ .unwrap()
+ );
+ assert_eq!(read_context.reader.slice_after_cursor().len(), 0);
+ // serialize_nullable
+ let mut writer = Writer::default();
+ let mut write_context = WriteContext::new(&fory, &mut writer);
+ fory.serialize_with_context(&nullable_basic_list(false), &mut write_context);
+ fory.serialize_with_context(&nullable_item_list(false), &mut write_context);
+ fory.serialize_with_context(&nullable_basic_set(false), &mut write_context);
+ fory.serialize_with_context(&nullable_item_set(false), &mut write_context);
+ // deserialize_non-null
+ let bytes = write_context.writer.dump();
+ let reader = Reader::new(bytes.as_slice());
+ let mut read_context = ReadContext::new(&fory, reader);
+ assert_eq!(
+ basic_list(),
+ fory.deserialize_with_context::<Vec<String>>(&mut read_context)
+ .unwrap()
+ );
+ assert_eq!(
+ item_list(),
+ fory.deserialize_with_context::<Vec<Item>>(&mut read_context)
+ .unwrap()
+ );
+ assert_eq!(
+ basic_set(),
+ fory.deserialize_with_context::<HashSet<String>>(&mut read_context)
+ .unwrap()
+ );
+ assert_eq!(
+ item_set(),
+ fory.deserialize_with_context::<HashSet<Item>>(&mut read_context)
+ .unwrap()
+ );
+ assert_eq!(read_context.reader.slice_after_cursor().len(), 0);
+ }
+}
+
+#[test]
+fn map_inner() {
+ let mut fory1 = Fory::default().mode(Compatible);
+ fory1.register::<Item>(101);
+ let mut fory2 = Fory::default().mode(Compatible);
+ fory2.register_by_name::<Item>("item");
+ for fory in [fory1, fory2] {
+ // serialize
+ let mut writer = Writer::default();
+ let mut write_context = WriteContext::new(&fory, &mut writer);
+ fory.serialize_with_context(&basic_map(), &mut write_context);
+ fory.serialize_with_context(&item_map(), &mut write_context);
+ fory.serialize_with_context(&nullable_basic_map(false), &mut write_context);
+ fory.serialize_with_context(&nullable_item_map(false), &mut write_context);
+ // deserialize
+ let bytes = write_context.writer.dump();
+ let reader = Reader::new(bytes.as_slice());
+ let mut read_context = ReadContext::new(&fory, reader);
+ assert_eq!(
+ basic_map(),
+ fory.deserialize_with_context::<HashMap<String, String>>(&mut read_context)
+ .unwrap()
+ );
+ assert_eq!(
+ item_map(),
+ fory.deserialize_with_context::<HashMap<Item, Item>>(&mut read_context)
+ .unwrap()
+ );
+ assert_eq!(
+ nullable_basic_map(false),
+ fory.deserialize_with_context::<HashMap<Option<String>, Option<String>>>(
+ &mut read_context
+ )
+ .unwrap()
+ );
+ assert_eq!(
+ nullable_item_map(false),
+ fory.deserialize_with_context::<HashMap<Option<Item>, Option<Item>>>(&mut read_context)
+ .unwrap()
+ );
+ assert_eq!(read_context.reader.slice_after_cursor().len(), 0);
+ }
+}
+
+#[test]
+fn map_inner_auto_conv() {
+ let mut fory1 = Fory::default().mode(Compatible);
+ fory1.register::<Item>(101);
+ let mut fory2 = Fory::default().mode(Compatible);
+ fory2.register_by_name::<Item>("item");
+ for fory in [fory1, fory2] {
+ // serialize_non-null
+ let mut writer = Writer::default();
+ let mut write_context = WriteContext::new(&fory, &mut writer);
+ fory.serialize_with_context(&basic_map(), &mut write_context);
+ fory.serialize_with_context(&item_map(), &mut write_context);
+ // deserialize_nullable
+ let bytes = write_context.writer.dump();
+ let reader = Reader::new(bytes.as_slice());
+ let mut read_context = ReadContext::new(&fory, reader);
+ assert_eq!(
+ nullable_basic_map(true),
+ fory.deserialize_with_context::<HashMap<Option<String>, Option<String>>>(
+ &mut read_context
+ )
+ .unwrap()
+ );
+ assert_eq!(
+ nullable_item_map(true),
+ fory.deserialize_with_context::<HashMap<Option<Item>, Option<Item>>>(&mut read_context)
+ .unwrap()
+ );
+ assert_eq!(read_context.reader.slice_after_cursor().len(), 0);
+ // serialize_nullable
+ let mut writer = Writer::default();
+ let mut write_context = WriteContext::new(&fory, &mut writer);
+ fory.serialize_with_context(&nullable_basic_map(false), &mut write_context);
+ fory.serialize_with_context(&nullable_item_map(false), &mut write_context);
+ // deserialize_non-null
+ let bytes = write_context.writer.dump();
+ let reader = Reader::new(bytes.as_slice());
+ let mut read_context = ReadContext::new(&fory, reader);
+ assert_eq!(
+ basic_map(),
+ fory.deserialize_with_context::<HashMap<String, String>>(&mut read_context)
+ .unwrap()
+ );
+ assert_eq!(
+ item_map(),
+ fory.deserialize_with_context::<HashMap<Item, Item>>(&mut read_context)
+ .unwrap()
+ );
+ assert_eq!(read_context.reader.slice_after_cursor().len(), 0);
+ }
+}
+
+#[test]
+fn complex() {
+ let mut fory1 = Fory::default().mode(Compatible);
+ fory1.register::<Item>(101);
+ let mut fory2 = Fory::default().mode(Compatible);
+ fory2.register_by_name::<Item>("item");
+ for fory in [fory1, fory2] {
+ let mut writer = Writer::default();
+ let mut write_context = WriteContext::new(&fory, &mut writer);
+ fory.serialize_with_context(&nested_collection(), &mut write_context);
+ fory.serialize_with_context(&complex_container1(), &mut write_context);
+ fory.serialize_with_context(&complex_container2(), &mut write_context);
+ let bytes = write_context.writer.dump();
+ let reader = Reader::new(bytes.as_slice());
+ let mut read_context = ReadContext::new(&fory, reader);
+ assert_eq!(
+ nested_collection(),
+ fory.deserialize_with_context::<Vec<HashSet<Item>>>(&mut read_context)
+ .unwrap()
+ );
+ assert_eq!(
+ complex_container1(),
+ fory.deserialize_with_context::<Vec<HashMap<Item, Item>>>(&mut read_context)
+ .unwrap()
+ );
+ assert_eq!(
+ complex_container2(),
+ fory.deserialize_with_context::<Vec<HashMap<Vec<Item>, Vec<Item>>>>(&mut read_context)
+ .unwrap()
+ );
+ assert_eq!(read_context.reader.slice_after_cursor().len(), 0);
+ }
+}
diff --git a/rust/tests/tests/test_compatible.rs b/rust/tests/tests/compatible/test_struct.rs
similarity index 99%
rename from rust/tests/tests/test_compatible.rs
rename to rust/tests/tests/compatible/test_struct.rs
index 0dc3dbd10..23fd99f2b 100644
--- a/rust/tests/tests/test_compatible.rs
+++ b/rust/tests/tests/compatible/test_struct.rs
@@ -20,7 +20,7 @@ use fory_core::types::Mode::Compatible;
use fory_derive::ForyObject;
use std::collections::{HashMap, HashSet};
-// RUSTFLAGS="-Awarnings" cargo expand -p fory-tests --test test_compatible
+// RUSTFLAGS="-Awarnings" cargo expand -p fory-tests --test test_struct
#[test]
fn simple() {
#[derive(ForyObject, Debug)]
@@ -589,9 +589,3 @@ fn boxed() {
let item2_f6: Option<i32> = fory2.deserialize(&bytes).unwrap();
assert_eq!(item2.f6, item2_f6);
}
-
-#[test]
-#[ignore]
-fn skip_custom_type() {
- todo!()
-}
diff --git a/rust/tests/tests/compatible/test_struct_enum.rs b/rust/tests/tests/compatible/test_struct_enum.rs
new file mode 100644
index 000000000..a44095e94
--- /dev/null
+++ b/rust/tests/tests/compatible/test_struct_enum.rs
@@ -0,0 +1,560 @@
+// 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 chrono::{NaiveDate, NaiveDateTime};
+use fory_core::buffer::{Reader, Writer};
+use fory_core::error::Error;
+use fory_core::fory::{read_data, write_data, Fory};
+use fory_core::resolver::context::{ReadContext, WriteContext};
+use fory_core::serializer::{ForyDefault, Serializer};
+use fory_core::types::Mode::Compatible;
+use fory_derive::ForyObject;
+use std::collections::{HashMap, HashSet};
+
+#[derive(ForyObject, Debug, PartialEq, Eq, Hash)]
+struct Item {
+ id: i32,
+}
+
+#[derive(ForyObject, Default, Debug, PartialEq, Eq, Hash)]
+enum Color {
+ #[default]
+ Green,
+ Red,
+ Blue,
+ White,
+}
+
+#[derive(ForyObject, Debug, PartialEq)]
+struct Person {
+ // primitive
+ f1: bool,
+ f2: i8,
+ f3: i16,
+ f4: i32,
+ f5: i64,
+ f6: f32,
+ f7: f64,
+ // nullable_primitive
+ f8: Option<bool>,
+ f9: Option<i8>,
+ f10: Option<i16>,
+ f11: Option<i32>,
+ f12: Option<i64>,
+ f13: Option<f32>,
+ f14: Option<f64>,
+ // final (string/enum/time/primitive_list)
+ f15: String,
+ f16: Color,
+ f17: NaiveDate,
+ f18: NaiveDateTime,
+ f19: Item,
+ f20: Vec<bool>,
+ f21: Vec<i8>,
+ f22: Vec<i16>,
+ f23: Vec<i32>,
+ f24: Vec<i64>,
+ f25: Vec<f32>,
+ f26: Vec<f64>,
+ // collection
+ f27: Vec<String>,
+ f28: HashSet<String>,
+ // map
+ f29: HashMap<String, i32>,
+}
+
+#[derive(ForyObject, Debug, PartialEq)]
+struct Empty {}
+
+#[test]
+fn basic() {
+ let mut fory1 = Fory::default().mode(Compatible);
+ fory1.register::<Color>(101);
+ fory1.register::<Item>(102);
+ fory1.register::<Person>(103);
+ let mut fory2 = Fory::default().mode(Compatible);
+ fory2.register_by_name::<Color>("color");
+ fory2.register_by_name::<Item>("item");
+ fory2.register_by_name::<Person>("person");
+ for fory in [fory1, fory2] {
+ let mut writer = Writer::default();
+ let mut write_context = WriteContext::new(&fory, &mut writer);
+ let person = Person::default();
+ fory.serialize_with_context(&person, &mut write_context);
+ fory.serialize_with_context(&person, &mut write_context);
+ let bytes = write_context.writer.dump();
+ let reader = Reader::new(bytes.as_slice());
+ let mut read_context = ReadContext::new(&fory, reader);
+ assert_eq!(
+ person,
+ fory.deserialize_with_context::<Person>(&mut read_context)
+ .unwrap()
+ );
+ assert_eq!(
+ person,
+ fory.deserialize_with_context::<Person>(&mut read_context)
+ .unwrap()
+ );
+ assert_eq!(read_context.reader.slice_after_cursor().len(), 0);
+ }
+}
+
+#[test]
+fn outer_nullable() {
+ let mut fory1 = Fory::default().mode(Compatible);
+ fory1.register::<Color>(101);
+ fory1.register::<Item>(102);
+ fory1.register::<Person>(103);
+ let mut fory2 = Fory::default().mode(Compatible);
+ fory2.register_by_name::<Color>("color");
+ fory2.register_by_name::<Item>("item");
+ fory2.register_by_name::<Person>("person");
+ for fory in [fory1, fory2] {
+ let null_person: Option<Person> = None;
+ let bytes = fory.serialize(&null_person);
+ assert_eq!(
+ fory.deserialize::<Person>(&bytes).unwrap(),
+ Person::default()
+ );
+ }
+}
+
+#[test]
+fn skip_basic() {
+ let person_default = Person::default();
+ let person2_default = Empty::default();
+
+ let mut id_fory1 = Fory::default().mode(Compatible);
+ id_fory1.register::<Color>(101);
+ id_fory1.register::<Item>(102);
+ id_fory1.register::<Person>(103);
+ let mut id_fory2 = Fory::default().mode(Compatible);
+ id_fory2.register::<Empty>(103);
+
+ let mut name_fory1 = Fory::default().mode(Compatible);
+ name_fory1.register_by_name::<Color>("color");
+ name_fory1.register_by_name::<Item>("item");
+ name_fory1.register_by_name::<Person>("person");
+ let mut name_fory2 = Fory::default().mode(Compatible);
+ name_fory2.register_by_name::<Empty>("person");
+
+ for (fory1, fory2) in [(id_fory1, id_fory2), (name_fory1, name_fory2)] {
+ let bytes = fory1.serialize(&person_default);
+ assert_eq!(fory2.deserialize::<Empty>(&bytes).unwrap(), person2_default);
+ let bytes = fory2.serialize(&person2_default);
+ assert_eq!(fory1.deserialize::<Person>(&bytes).unwrap(), person_default);
+ }
+}
+
+#[test]
+fn nested() {
+ #[derive(ForyObject, Debug, PartialEq)]
+ struct Element {
+ f1: Vec<Item>,
+ f2: HashSet<Item>,
+ f3: HashMap<Item, Item>,
+ f4: Vec<Color>,
+ f5: HashSet<Color>,
+ f6: HashMap<Color, Color>,
+ }
+ #[derive(ForyObject, Debug, PartialEq)]
+ struct Nested {
+ f1: Vec<Item>,
+ f2: HashSet<Item>,
+ f3: HashMap<Item, Item>,
+ f4: Vec<Color>,
+ f5: HashSet<Color>,
+ f6: HashMap<Color, Color>,
+ f7: Element,
+ }
+ let mut id_fory1 = Fory::default().mode(Compatible);
+ id_fory1.register::<Item>(101);
+ id_fory1.register::<Color>(102);
+ id_fory1.register::<Element>(103);
+ id_fory1.register::<Nested>(104);
+ let mut id_fory2 = Fory::default().mode(Compatible);
+ id_fory2.register::<Empty>(104);
+
+ let mut name_fory1 = Fory::default().mode(Compatible);
+ name_fory1.register_by_name::<Item>("item");
+ name_fory1.register_by_name::<Color>("color");
+ name_fory1.register_by_name::<Element>("element");
+ name_fory1.register_by_name::<Nested>("nested");
+ let mut name_fory2 = Fory::default().mode(Compatible);
+ name_fory2.register_by_name::<Empty>("nested");
+
+ for (fory1, fory2) in [(id_fory1, id_fory2), (name_fory1, name_fory2)] {
+ let bytes = fory1.serialize(&Nested::default());
+ assert_eq!(
+ fory2.deserialize::<Empty>(&bytes).unwrap(),
+ Empty::default()
+ );
+ let bytes = fory2.serialize(&Empty::default());
+ assert_eq!(
+ fory1.deserialize::<Nested>(&bytes).unwrap(),
+ Nested::default()
+ );
+ }
+}
+
+#[test]
+fn compatible_nullable() {
+ #[derive(ForyObject, Debug, PartialEq)]
+ struct Nonnull {
+ f1: bool,
+ f2: i8,
+ f3: i16,
+ f4: i32,
+ f5: i64,
+ f6: f32,
+ f7: f64,
+ f15: String,
+ f16: Color,
+ f17: NaiveDate,
+ f18: NaiveDateTime,
+ f19: Item,
+ f20: Vec<bool>,
+ f21: Vec<i8>,
+ f22: Vec<i16>,
+ f23: Vec<i32>,
+ f24: Vec<i64>,
+ f25: Vec<f32>,
+ f26: Vec<f64>,
+ f27: Vec<String>,
+ f28: HashSet<String>,
+ f29: HashMap<String, i32>,
+ }
+ #[derive(ForyObject, Debug, PartialEq)]
+ struct Nullable {
+ f1: Option<bool>,
+ f2: Option<i8>,
+ f3: Option<i16>,
+ f4: Option<i32>,
+ f5: Option<i64>,
+ f6: Option<f32>,
+ f7: Option<f64>,
+ f15: Option<String>,
+ f16: Option<Color>,
+ f17: Option<NaiveDate>,
+ f18: Option<NaiveDateTime>,
+ f19: Option<Item>,
+ f20: Option<Vec<bool>>,
+ f21: Option<Vec<i8>>,
+ f22: Option<Vec<i16>>,
+ f23: Option<Vec<i32>>,
+ f24: Option<Vec<i64>>,
+ f25: Option<Vec<f32>>,
+ f26: Option<Vec<f64>>,
+ f27: Option<Vec<String>>,
+ f28: Option<HashSet<String>>,
+ f29: Option<HashMap<String, i32>>,
+ }
+ let nullable_obj = Nullable {
+ f1: Some(bool::default()),
+ f2: Some(i8::default()),
+ f3: Some(i16::default()),
+ f4: Some(i32::default()),
+ f5: Some(i64::default()),
+ f6: Some(f32::default()),
+ f7: Some(f64::default()),
+ f15: Some(String::default()),
+ f16: Some(Color::default()),
+ f17: Some(NaiveDate::from_ymd_opt(1970, 1, 1).unwrap()),
+ #[allow(deprecated)]
+ f18: Some(NaiveDateTime::from_timestamp_opt(0, 0).unwrap()),
+ f19: Some(Item::default()),
+ f20: Some(Vec::<bool>::default()),
+ f21: Some(Vec::<i8>::default()),
+ f22: Some(Vec::<i16>::default()),
+ f23: Some(Vec::<i32>::default()),
+ f24: Some(Vec::<i64>::default()),
+ f25: Some(Vec::<f32>::default()),
+ f26: Some(Vec::<f64>::default()),
+ f27: Some(Vec::<String>::default()),
+ f28: Some(HashSet::<String>::default()),
+ f29: Some(HashMap::<String, i32>::default()),
+ };
+ let mut id_fory1 = Fory::default().mode(Compatible);
+ id_fory1.register::<Color>(101);
+ id_fory1.register::<Item>(102);
+ id_fory1.register::<Nonnull>(103);
+ let mut id_fory2 = Fory::default().mode(Compatible);
+ id_fory2.register::<Color>(101);
+ id_fory2.register::<Item>(102);
+ id_fory2.register::<Nullable>(103);
+
+ let mut name_fory1 = Fory::default().mode(Compatible);
+ name_fory1.register_by_name::<Color>("color");
+ name_fory1.register_by_name::<Item>("item");
+ name_fory1.register_by_name::<Nonnull>("obj");
+ let mut name_fory2 = Fory::default().mode(Compatible);
+ name_fory2.register_by_name::<Color>("color");
+ name_fory2.register_by_name::<Item>("item");
+ name_fory2.register_by_name::<Nullable>("obj");
+
+ for (fory1, fory2) in [(id_fory1, id_fory2), (name_fory1, name_fory2)] {
+ let bytes = fory1.serialize(&Nonnull::default());
+ assert_eq!(fory2.deserialize::<Nullable>(&bytes).unwrap(), nullable_obj);
+ let bytes = fory2.serialize(&Nullable::default());
+ assert_eq!(
+ fory1.deserialize::<Nonnull>(&bytes).unwrap(),
+ Nonnull::default()
+ );
+ }
+}
+
+#[test]
+fn name_mismatch() {
+ #[derive(ForyObject, Debug, PartialEq)]
+ struct MismatchPerson {
+ f2: bool,
+ f3: i8,
+ f4: i16,
+ f5: i32,
+ f6: i64,
+ f7: f32,
+ f8: f64,
+ f9: Option<bool>,
+ f10: Option<i8>,
+ f11: Option<i16>,
+ f12: Option<i32>,
+ f13: Option<i64>,
+ f14: Option<f32>,
+ f15: Option<f64>,
+ f16: String,
+ f17: Color,
+ f18: NaiveDate,
+ f19: NaiveDateTime,
+ f20: Item,
+ f21: Vec<bool>,
+ f22: Vec<i8>,
+ f23: Vec<i16>,
+ f24: Vec<i32>,
+ f25: Vec<i64>,
+ f26: Vec<f32>,
+ f27: Vec<f64>,
+ f28: Vec<String>,
+ f29: HashSet<String>,
+ f30: HashMap<String, i32>,
+ }
+ let mut id_fory1 = Fory::default().mode(Compatible);
+ id_fory1.register::<Color>(101);
+ id_fory1.register::<Item>(102);
+ id_fory1.register::<Person>(103);
+ let mut id_fory2 = Fory::default().mode(Compatible);
+ id_fory2.register::<Color>(101);
+ id_fory2.register::<Item>(102);
+ id_fory2.register::<MismatchPerson>(103);
+
+ let mut name_fory1 = Fory::default().mode(Compatible);
+ name_fory1.register_by_name::<Color>("color");
+ name_fory1.register_by_name::<Item>("item");
+ name_fory1.register_by_name::<Person>("person");
+ let mut name_fory2 = Fory::default().mode(Compatible);
+ name_fory2.register_by_name::<Color>("color");
+ name_fory2.register_by_name::<Item>("item");
+ name_fory2.register_by_name::<MismatchPerson>("person");
+
+ for (fory1, fory2) in [(id_fory1, id_fory2), (name_fory1, name_fory2)] {
+ let bytes = fory1.serialize(&Person::default());
+ assert_eq!(
+ fory2.deserialize::<MismatchPerson>(&bytes).unwrap(),
+ MismatchPerson::default()
+ );
+ let bytes = fory2.serialize(&MismatchPerson::default());
+ assert_eq!(
+ fory1.deserialize::<Person>(&bytes).unwrap(),
+ Person::default()
+ );
+ }
+}
+
+#[test]
+fn ext() {
+ #[derive(Debug, PartialEq, Default)]
+ struct ExtItem {
+ id: i32,
+ }
+ impl ForyDefault for ExtItem {
+ fn fory_default() -> Self {
+ Self::default()
+ }
+ }
+ impl Serializer for ExtItem {
+ fn fory_write_data(&self, context: &mut WriteContext, is_field: bool) {
+ write_data(&self.id, context, is_field);
+ }
+ fn fory_read_data(context: &mut ReadContext, is_field: bool) -> Result<Self, Error> {
+ Ok(Self {
+ id: read_data(context, is_field)?,
+ })
+ }
+
+ fn fory_type_id_dyn(&self, fory: &Fory) -> u32 {
+ Self::fory_get_type_id(fory)
+ }
+
+ fn as_any(&self) -> &dyn std::any::Any {
+ self
+ }
+ }
+ #[derive(ForyObject, Debug, PartialEq)]
+ struct ExtWrapper {
+ f1: ExtItem,
+ }
+
+ let mut id_fory = Fory::default().mode(Compatible).xlang(true);
+ id_fory.register_serializer::<ExtItem>(100);
+ id_fory.register::<ExtWrapper>(101);
+
+ let mut name_fory = Fory::default().mode(Compatible).xlang(true);
+ name_fory.register_serializer_by_name::<ExtItem>("ext_item");
+ name_fory.register::<ExtWrapper>(101);
+
+ for fory in [id_fory, name_fory] {
+ let wrapper = ExtWrapper {
+ f1: ExtItem { id: 1 },
+ };
+ let bytes = fory.serialize(&wrapper);
+ assert_eq!(fory.deserialize::<ExtWrapper>(&bytes).unwrap(), wrapper);
+ }
+}
+
+#[test]
+fn skip_ext() {
+ #[derive(Debug, PartialEq, Default)]
+ struct ExtItem {
+ id: i32,
+ }
+ impl Serializer for ExtItem {
+ fn fory_write_data(&self, context: &mut WriteContext, is_field: bool) {
+ write_data(&self.id, context, is_field);
+ }
+ fn fory_read_data(context: &mut ReadContext, is_field: bool) -> Result<Self, Error> {
+ Ok(Self {
+ id: read_data(context, is_field)?,
+ })
+ }
+
+ fn fory_type_id_dyn(&self, fory: &Fory) -> u32 {
+ Self::fory_get_type_id(fory)
+ }
+
+ fn as_any(&self) -> &dyn std::any::Any {
+ self
+ }
+ }
+ impl ForyDefault for ExtItem {
+ fn fory_default() -> Self {
+ Self::default()
+ }
+ }
+ #[derive(ForyObject, Debug, PartialEq)]
+ struct ExtWrapper {
+ f1: ExtItem,
+ }
+ let mut id_fory1 = Fory::default().mode(Compatible).xlang(true);
+ id_fory1.register_serializer::<ExtItem>(100);
+ id_fory1.register::<ExtWrapper>(101);
+ let mut id_fory2 = Fory::default().mode(Compatible).xlang(true);
+ id_fory2.register_serializer::<ExtItem>(100);
+ id_fory2.register::<Empty>(101);
+
+ let mut name_fory1 = Fory::default().mode(Compatible).xlang(true);
+ name_fory1.register_serializer_by_name::<ExtItem>("ext_item");
+ name_fory1.register::<ExtWrapper>(101);
+ let mut name_fory2 = Fory::default().mode(Compatible).xlang(true);
+ name_fory2.register_serializer_by_name::<ExtItem>("ext_item");
+ name_fory2.register::<Empty>(101);
+
+ for (fory1, fory2) in [(id_fory1, id_fory2), (name_fory1, name_fory2)] {
+ let wrapper = ExtWrapper {
+ f1: ExtItem { id: 1 },
+ };
+ let bytes = fory1.serialize(&wrapper);
+ assert_eq!(
+ fory2.deserialize::<Empty>(&bytes).unwrap(),
+ Empty::default()
+ );
+ }
+}
+
+#[test]
+fn compatible_ext() {
+ #[derive(Debug, PartialEq, Default)]
+ struct ExtItem {
+ id: i32,
+ }
+ impl Serializer for ExtItem {
+ fn fory_write_data(&self, context: &mut WriteContext, is_field: bool) {
+ write_data(&self.id, context, is_field);
+ }
+ fn fory_read_data(context: &mut ReadContext, is_field: bool) -> Result<Self, Error> {
+ Ok(Self {
+ id: read_data(context, is_field)?,
+ })
+ }
+ fn fory_type_id_dyn(&self, fory: &Fory) -> u32 {
+ Self::fory_get_type_id(fory)
+ }
+
+ fn as_any(&self) -> &dyn std::any::Any {
+ self
+ }
+ }
+ impl ForyDefault for ExtItem {
+ fn fory_default() -> Self {
+ Self::default()
+ }
+ }
+ #[derive(ForyObject, Debug, PartialEq)]
+ struct ExtWrapper1 {
+ f1: ExtItem,
+ }
+ #[derive(ForyObject, Debug, PartialEq)]
+ struct ExtWrapper2 {
+ f1: Option<ExtItem>,
+ }
+ let mut id_fory1 = Fory::default().mode(Compatible).xlang(true);
+ id_fory1.register_serializer::<ExtItem>(100);
+ id_fory1.register::<ExtWrapper1>(101);
+ let mut id_fory2 = Fory::default().mode(Compatible).xlang(true);
+ id_fory2.register_serializer::<ExtItem>(100);
+ id_fory2.register::<ExtWrapper2>(101);
+
+ let mut name_fory1 = Fory::default().mode(Compatible).xlang(true);
+ name_fory1.register_serializer_by_name::<ExtItem>("ext_item");
+ name_fory1.register::<ExtWrapper1>(101);
+ let mut name_fory2 = Fory::default().mode(Compatible).xlang(true);
+ name_fory2.register_serializer_by_name::<ExtItem>("ext_item");
+ name_fory2.register::<ExtWrapper2>(101);
+
+ for (fory1, fory2) in [(id_fory1, id_fory2), (name_fory1, name_fory2)] {
+ let wrapper = ExtWrapper1 {
+ f1: ExtItem { id: 1 },
+ };
+ let bytes = fory1.serialize(&wrapper);
+ assert_eq!(
+ fory2
+ .deserialize::<ExtWrapper2>(&bytes)
+ .unwrap()
+ .f1
+ .unwrap(),
+ wrapper.f1
+ );
+ }
+}
diff --git a/rust/fory-core/src/meta/mod.rs b/rust/tests/tests/mod.rs
similarity index 61%
copy from rust/fory-core/src/meta/mod.rs
copy to rust/tests/tests/mod.rs
index 7ec3239aa..a86a16572 100644
--- a/rust/fory-core/src/meta/mod.rs
+++ b/rust/tests/tests/mod.rs
@@ -15,17 +15,4 @@
// specific language governing permissions and limitations
// under the License.
-mod meta_string;
-mod string_util;
-mod type_meta;
-
-pub use meta_string::{
- Encoding, MetaString, MetaStringBytes, MetaStringDecoder, MetaStringEncoder,
- FIELD_NAME_DECODER, FIELD_NAME_ENCODER, NAMESPACE_DECODER, NAMESPACE_ENCODER,
- TYPE_NAME_DECODER, TYPE_NAME_ENCODER,
-};
-pub use string_util::{buffer_rw_string, get_latin1_length, is_latin, murmurhash3_x64_128};
-pub use type_meta::{
- FieldInfo, FieldType, NullableFieldType, TypeMeta, TypeMetaLayer, NAMESPACE_ENCODINGS,
- TYPE_NAME_ENCODINGS,
-};
+mod compatible;
diff --git a/rust/tests/tests/test_complex_struct.rs b/rust/tests/tests/test_complex_struct.rs
index 58158c845..86d9e1425 100644
--- a/rust/tests/tests/test_complex_struct.rs
+++ b/rust/tests/tests/test_complex_struct.rs
@@ -114,6 +114,12 @@ fn complex_struct() {
let bin: Vec<u8> = fory.serialize(&person);
let obj: Person = fory.deserialize(&bin).expect("should success");
assert_eq!(person, obj);
+ let mut fory = Fory::default();
+ fory.register_by_name::<Animal>("animal");
+ fory.register_by_name::<Person>("person");
+ let bin: Vec<u8> = fory.serialize(&person);
+ let obj: Person = fory.deserialize(&bin).expect("should success");
+ assert_eq!(person, obj);
}
#[test]
diff --git a/rust/tests/tests/test_cross_language.rs b/rust/tests/tests/test_cross_language.rs
index 27bfe7995..87290e93f 100644
--- a/rust/tests/tests/test_cross_language.rs
+++ b/rust/tests/tests/test_cross_language.rs
@@ -17,20 +17,24 @@
use chrono::{NaiveDate, NaiveDateTime};
use fory_core::buffer::{Reader, Writer};
-use fory_core::fory::Fory;
+use fory_core::error::Error;
+use fory_core::fory::{read_data, write_data, Fory};
use fory_core::meta::murmurhash3_x64_128;
use fory_core::resolver::context::{ReadContext, WriteContext};
-use fory_core::serializer::Serializer;
-use fory_core::types::Mode::Compatible;
+use fory_core::serializer::{ForyDefault, Serializer};
+use fory_core::types::Mode::{Compatible, SchemaConsistent};
use fory_derive::ForyObject;
use std::collections::{HashMap, HashSet};
-use std::fs;
+use std::{fs, vec};
// RUSTFLAGS="-Awarnings" cargo expand -p fory-tests --test test_cross_language
fn get_data_file() -> String {
std::env::var("DATA_FILE").expect("DATA_FILE not set")
}
+#[derive(ForyObject, Debug, PartialEq)]
+struct Empty {}
+
#[derive(ForyObject, Debug, PartialEq, Default)]
enum Color {
#[default]
@@ -417,6 +421,7 @@ fn test_list() {
let mut fory = Fory::default().mode(Compatible);
fory.register::<Item>(102);
let reader = Reader::new(bytes.as_slice());
+ let mut context = ReadContext::new(&fory, reader);
let str_list = vec![Some("a".to_string()), Some("b".to_string())];
let str_list2 = vec![None, Some("b".to_string())];
@@ -432,42 +437,24 @@ fn test_list() {
let item_list = vec![Some(item), Some(item2)];
let item_list2 = vec![None, Some(item3)];
- let bytes = reader.get_slice();
- let remote_str_list: Vec<Option<String>> = fory.deserialize(bytes).unwrap();
+ let remote_str_list: Vec<Option<String>> = fory.deserialize_with_context(&mut context).unwrap();
assert_eq!(remote_str_list, str_list);
- let data_bytes1 = fory.serialize(&remote_str_list);
- let new_local_str_list: Vec<Option<String>> = fory.deserialize(&data_bytes1).unwrap();
- assert_eq!(new_local_str_list, str_list);
-
- let bytes = &bytes[data_bytes1.len()..];
- let remote_str_list2: Vec<Option<String>> = fory.deserialize(bytes).unwrap();
+ let remote_str_list2: Vec<Option<String>> =
+ fory.deserialize_with_context(&mut context).unwrap();
assert_eq!(remote_str_list2, str_list2);
- let data_bytes2 = fory.serialize(&remote_str_list2);
- let new_local_str_list2: Vec<Option<String>> = fory.deserialize(&data_bytes2).unwrap();
- assert_eq!(new_local_str_list2, str_list2);
-
- let bytes = &bytes[data_bytes2.len()..];
- let remote_item_list: Vec<Option<Item>> = fory.deserialize(bytes).unwrap();
+ let remote_item_list: Vec<Option<Item>> = fory.deserialize_with_context(&mut context).unwrap();
assert_eq!(remote_item_list, item_list);
- let data_bytes3 = fory.serialize(&remote_item_list);
- let new_local_item_list: Vec<Option<Item>> = fory.deserialize(&data_bytes3).unwrap();
- assert_eq!(new_local_item_list, item_list);
-
- let bytes = &bytes[data_bytes3.len()..];
- let remote_item_list2: Vec<Option<Item>> = fory.deserialize(bytes).unwrap();
+ let remote_item_list2: Vec<Option<Item>> = fory.deserialize_with_context(&mut context).unwrap();
assert_eq!(remote_item_list2, item_list2);
- let data_bytes4 = fory.serialize(&remote_item_list2);
- let new_local_item_list2: Vec<Option<Item>> = fory.deserialize(&data_bytes4).unwrap();
- assert_eq!(new_local_item_list2, item_list2);
-
- let all_bytes = [
- data_bytes1.as_slice(),
- data_bytes2.as_slice(),
- data_bytes3.as_slice(),
- data_bytes4.as_slice(),
- ]
- .concat();
- fs::write(&data_file_path, all_bytes).unwrap();
+
+ let mut writer = Writer::default();
+ let mut context = WriteContext::new(&fory, &mut writer);
+ fory.serialize_with_context(&remote_str_list, &mut context);
+ fory.serialize_with_context(&remote_str_list2, &mut context);
+ fory.serialize_with_context(&remote_item_list, &mut context);
+ fory.serialize_with_context(&remote_item_list2, &mut context);
+
+ fs::write(&data_file_path, context.writer.dump()).unwrap();
}
#[test]
@@ -591,3 +578,169 @@ fn test_integer() {
fory.serialize_with_context(&remote_f6, &mut context);
fs::write(&data_file_path, context.writer.dump()).unwrap();
}
+
+#[derive(ForyObject, Debug, PartialEq)]
+struct MyStruct {
+ id: i32,
+}
+#[derive(Debug, PartialEq, Default)]
+struct MyExt {
+ id: i32,
+}
+impl Serializer for MyExt {
+ fn fory_write_data(&self, context: &mut WriteContext, _is_field: bool) {
+ // set is_field=false to write type_id like in java
+ write_data(&self.id, context, false);
+ }
+
+ fn fory_read_data(context: &mut ReadContext, _is_field: bool) -> Result<Self, Error> {
+ Ok(Self {
+ // set is_field=false to write type_id like in java
+ id: read_data(context, false)?,
+ })
+ }
+
+ fn fory_type_id_dyn(&self, fory: &Fory) -> u32 {
+ Self::fory_get_type_id(fory)
+ }
+
+ fn as_any(&self) -> &dyn std::any::Any {
+ self
+ }
+}
+impl ForyDefault for MyExt {
+ fn fory_default() -> Self {
+ Self::default()
+ }
+}
+#[derive(ForyObject, Debug, PartialEq)]
+struct MyWrapper {
+ color: Color,
+ my_struct: MyStruct,
+ my_ext: MyExt,
+}
+
+fn _test_skip_custom(fory1: &Fory, fory2: &Fory) {
+ let data_file_path = get_data_file();
+ let bytes = fs::read(&data_file_path).unwrap();
+ assert_eq!(
+ fory1.deserialize::<Empty>(&bytes).unwrap(),
+ Empty::default()
+ );
+ let wrapper = MyWrapper {
+ color: Color::White,
+ my_struct: MyStruct { id: 42 },
+ my_ext: MyExt { id: 43 },
+ };
+ let bytes = fory2.serialize(&wrapper);
+ fs::write(&data_file_path, bytes).unwrap();
+}
+
+#[test]
+fn test_kankankan() {
+ let mut fory1 = Fory::default().mode(Compatible);
+ fory1.register_serializer::<MyExt>(103);
+ fory1.register::<Empty>(104);
+ let mut fory2 = Fory::default().mode(Compatible);
+ fory2.register::<Color>(101);
+ fory2.register::<MyStruct>(102);
+ fory2.register_serializer::<MyExt>(103);
+ fory2.register::<MyWrapper>(104);
+ let wrapper = MyWrapper {
+ color: Color::White,
+ my_struct: MyStruct { id: 42 },
+ my_ext: MyExt { id: 43 },
+ };
+ let bytes = fory2.serialize(&wrapper);
+ fory1.deserialize::<Empty>(&bytes).unwrap();
+}
+
+#[test]
+#[ignore]
+fn test_skip_id_custom() {
+ let mut fory1 = Fory::default().mode(Compatible);
+ fory1.register_serializer::<MyExt>(103);
+ fory1.register::<Empty>(104);
+ let mut fory2 = Fory::default().mode(Compatible);
+ fory2.register::<Color>(101);
+ fory2.register::<MyStruct>(102);
+ fory2.register_serializer::<MyExt>(103);
+ fory2.register::<MyWrapper>(104);
+ _test_skip_custom(&fory1, &fory2);
+}
+
+#[test]
+#[ignore]
+fn test_skip_name_custom() {
+ let mut fory1 = Fory::default().mode(Compatible);
+ fory1.register_serializer_by_name::<MyExt>("my_ext");
+ fory1.register_by_name::<Empty>("my_wrapper");
+ let mut fory2 = Fory::default().mode(Compatible);
+ fory2.register_by_name::<Color>("color");
+ fory2.register_by_name::<MyStruct>("my_struct");
+ fory2.register_serializer_by_name::<MyExt>("my_ext");
+ fory2.register_by_name::<MyWrapper>("my_wrapper");
+ _test_skip_custom(&fory1, &fory2);
+}
+
+#[test]
+#[ignore]
+fn test_consistent_named() {
+ let mut fory = Fory::default().mode(SchemaConsistent);
+ fory.register_by_name::<Color>("color");
+ fory.register_by_name::<MyStruct>("my_struct");
+ fory.register_serializer_by_name::<MyExt>("my_ext");
+
+ let color = Color::White;
+ let _my_struct = MyStruct { id: 42 };
+ let my_ext = MyExt { id: 43 };
+
+ let data_file_path = get_data_file();
+ let bytes = fs::read(&data_file_path).unwrap();
+ let reader = Reader::new(bytes.as_slice());
+ let mut context = ReadContext::new(&fory, reader);
+
+ assert_eq!(
+ fory.deserialize_with_context::<Color>(&mut context)
+ .unwrap(),
+ color
+ );
+ assert_eq!(
+ fory.deserialize_with_context::<Color>(&mut context)
+ .unwrap(),
+ color
+ );
+ assert_eq!(
+ fory.deserialize_with_context::<Color>(&mut context)
+ .unwrap(),
+ color
+ );
+ // assert_eq!(fory.deserialize_with_context::<MyStruct>(&mut context).unwrap(), my_struct);
+ assert_eq!(
+ fory.deserialize_with_context::<MyExt>(&mut context)
+ .unwrap(),
+ my_ext
+ );
+ assert_eq!(
+ fory.deserialize_with_context::<MyExt>(&mut context)
+ .unwrap(),
+ my_ext
+ );
+ assert_eq!(
+ fory.deserialize_with_context::<MyExt>(&mut context)
+ .unwrap(),
+ my_ext
+ );
+
+ let mut writer = Writer::default();
+ let mut context = WriteContext::new(&fory, &mut writer);
+ fory.serialize_with_context(&color, &mut context);
+ fory.serialize_with_context(&color, &mut context);
+ fory.serialize_with_context(&color, &mut context);
+ // todo: checkVersion
+ // fory.serialize_with_context(&my_struct, &mut context);
+ fory.serialize_with_context(&my_ext, &mut context);
+ fory.serialize_with_context(&my_ext, &mut context);
+ fory.serialize_with_context(&my_ext, &mut context);
+ fs::write(&data_file_path, context.writer.dump()).unwrap();
+}
diff --git a/rust/tests/tests/test_ext.rs b/rust/tests/tests/test_ext.rs
index fe68cfd4f..4db19daff 100644
--- a/rust/tests/tests/test_ext.rs
+++ b/rust/tests/tests/test_ext.rs
@@ -46,7 +46,7 @@ fn test_duplicate_impl() {
#[test]
fn test_use() {
- use fory_core::fory::{read, write};
+ use fory_core::fory::{read_data, write_data};
#[derive(Debug, PartialEq)]
struct Item {
f1: i32,
@@ -61,12 +61,12 @@ fn test_use() {
impl Serializer for Item {
fn fory_write_data(&self, context: &mut WriteContext, is_field: bool) {
- write(&self.f1, context, is_field);
+ write_data(&self.f1, context, is_field);
}
fn fory_read_data(context: &mut ReadContext, is_field: bool) -> Result<Self, Error> {
Ok(Self {
- f1: read(context, is_field)?,
+ f1: read_data(context, is_field)?,
f2: 0,
})
}
diff --git a/rust/tests/tests/test_rc_arc_trait_object.rs b/rust/tests/tests/test_rc_arc_trait_object.rs
index 92bfe0a66..1dc62e828 100644
--- a/rust/tests/tests/test_rc_arc_trait_object.rs
+++ b/rust/tests/tests/test_rc_arc_trait_object.rs
@@ -315,6 +315,7 @@ struct AnimalShelter {
}
#[test]
+#[ignore]
fn test_collections_of_wrappers() {
let mut fory = fory_compatible();
fory.register::<Dog>(8001);
---------------------------------------------------------------------
To unsubscribe, e-mail: commits-unsubscribe@fory.apache.org
For additional commands, e-mail: commits-help@fory.apache.org