Skip to main content

fory_core/
lib.rs

1// Licensed to the Apache Software Foundation (ASF) under one
2// or more contributor license agreements.  See the NOTICE file
3// distributed with this work for additional information
4// regarding copyright ownership.  The ASF licenses this file
5// to you under the Apache License, Version 2.0 (the
6// "License"); you may not use this file except in compliance
7// with the License.  You may obtain a copy of the License at
8//
9//   http://www.apache.org/licenses/LICENSE-2.0
10//
11// Unless required by applicable law or agreed to in writing,
12// software distributed under the License is distributed on an
13// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
14// KIND, either express or implied.  See the License for the
15// specific language governing permissions and limitations
16// under the License.
17
18//! # Fory Core
19//!
20//! This is the core implementation of the Fory serialization framework.
21//! It provides the fundamental building blocks for high-performance serialization
22//! and deserialization in Rust.
23//!
24//! ## Architecture
25//!
26//! The core library is organized into several key modules:
27//!
28//! - **`fory`**: Main serialization engine and public API
29//! - **`buffer`**: Efficient binary buffer management with Reader/Writer
30//! - **`row`**: Row-based serialization for zero-copy operations
31//! - **`serializer`**: Type-specific serialization implementations
32//! - **`resolver`**: Type resolution and metadata management
33//! - **`meta`**: Metadata handling for schema evolution
34//! - **`types`**: Core type definitions and constants
35//! - **`error`**: Error handling and result types
36//! - **`util`**: Utility functions and helpers
37//!
38//! ## Key Concepts
39//!
40//! ### Serialization Modes
41//!
42//! Fory supports two serialization modes:
43//!
44//! - **SchemaConsistent**: Requires exact type matching between peers
45//! - **Compatible**: Allows schema evolution with field additions/deletions
46//!
47//! ### Type System
48//!
49//! The framework uses a comprehensive type system that supports:
50//! - Primitive types (bool, integers, floats, strings)
51//! - Collections (Vec, HashMap, BTreeMap)
52//! - Optional types (`Option<T>`)
53//! - Date/time types (chrono integration)
54//! - Custom structs and enums
55//! - Trait objects (Box, Rc, Arc)
56//!
57//! ### Performance Optimizations
58//!
59//! - **Zero-copy deserialization** in row mode
60//! - **Buffer pre-allocation** to minimize allocations
61//! - **Variable-length encoding** for compact representation
62//! - **Little-endian byte order** for cross-platform compatibility
63//!
64//! ### Trait Object Serialization
65//!
66//! Fory supports polymorphic serialization through trait objects:
67//!
68//! #### Box-Based Trait Objects
69//!
70//! Define custom traits and register implementations:
71//!
72//! ```rust,ignore
73//! use fory_core::{Fory, register_trait_type, Serializer};
74//! use fory_derive::ForyObject;
75//!
76//! trait Animal: Serializer {
77//!     fn speak(&self) -> String;
78//! }
79//!
80//! #[derive(ForyObject, Debug)]
81//! struct Dog { name: String }
82//!
83//! #[derive(ForyObject, Debug)]
84//! struct Cat { name: String }
85//!
86//! impl Animal for Dog {
87//!     fn speak(&self) -> String { "Woof!".to_string() }
88//! }
89//!
90//! impl Animal for Cat {
91//!     fn speak(&self) -> String { "Meow!".to_string() }
92//! }
93//!
94//! register_trait_type!(Animal, Dog, Cat);
95//!
96//! #[derive(ForyObject)]
97//! struct Zoo {
98//!     star_animal: Box<dyn Animal>,
99//! }
100//!
101//! # fn main() {
102//! let mut fory = Fory::default().compatible(true);
103//! fory.register::<Dog>(100);
104//! fory.register::<Cat>(101);
105//! fory.register::<Zoo>(102);
106//!
107//! let zoo = Zoo {
108//!     star_animal: Box::new(Dog { name: "Buddy".to_string() }),
109//! };
110//!
111//! let bytes = fory.serialize(&zoo);
112//! let decoded: Zoo = fory.deserialize(&bytes).unwrap();
113//! assert_eq!(decoded.star_animal.speak(), "Woof!");
114//! # }
115//! ```
116//!
117//! #### Rc/Arc-Based Trait Objects
118//!
119//! For reference-counted trait objects, use them directly in struct fields:
120//!
121//! ```rust,ignore
122//! # use fory_core::Serializer;
123//! # use fory_derive::ForyObject;
124//! # use std::rc::Rc;
125//! # use std::sync::Arc;
126//! # trait Animal: Serializer { fn speak(&self) -> String; }
127//! #[derive(ForyObject)]
128//! struct Shelter {
129//!     animals_rc: Vec<Rc<dyn Animal>>,
130//!     animals_arc: Vec<Arc<dyn Animal>>,
131//! }
132//! ```
133//!
134//! For standalone serialization, use auto-generated wrapper types (e.g., `AnimalRc`, `AnimalArc`)
135//! created by `register_trait_type!` due to Rust's orphan rule limitations.
136//!
137//! ## Usage
138//!
139//! This crate is typically used through the higher-level `fory` crate,
140//! which provides derive macros and a more convenient API. However,
141//! you can use the core types directly for advanced use cases.
142//!
143//! ```rust
144//! use fory_core::fory::Fory;
145//! use fory_core::error::Error;
146//! use fory_core::row::{to_row, from_row};
147//! use std::collections::HashMap;
148//!
149//! // Create a Fory instance
150//! let mut fory = Fory::default().compatible(true);
151//!
152//! // Serialize String
153//! let text = String::from("Hello, Fory!");
154//! let serialized_str = fory.serialize(&text).unwrap();
155//! let deserialized_str: String = fory.deserialize(&serialized_str).unwrap();
156//! assert_eq!(text, deserialized_str);
157//!
158//! // Serialize Vec
159//! let vec_data = vec![1, 2, 3, 4, 5];
160//! let serialized_vec = fory.serialize(&vec_data).unwrap();
161//! let deserialized_vec: Vec<i32> = fory.deserialize(&serialized_vec).unwrap();
162//! assert_eq!(vec_data, deserialized_vec);
163//!
164//! // Serialize HashMap
165//! let mut map = HashMap::new();
166//! map.insert("key1".to_string(), 100);
167//! map.insert("key2".to_string(), 200);
168//! let serialized_map = fory.serialize(&map).unwrap();
169//! let deserialized_map: HashMap<String, i32> = fory.deserialize(&serialized_map).unwrap();
170//! assert_eq!(map, deserialized_map);
171//! // Register types for object serialization
172//! // fory.register::<MyStruct>(type_id);
173//!
174//! // Use row-based serialization for zero-copy operations
175//! // let row_data = to_row(&my_data);
176//! // let row = from_row::<MyStruct>(&row_data);
177//! ```
178
179pub mod buffer;
180pub mod config;
181pub mod error;
182pub mod fory;
183pub mod meta;
184pub mod resolver;
185pub mod row;
186pub mod serializer;
187pub mod types;
188pub mod util;
189
190// Re-export paste for use in macros
191pub use paste;
192
193pub use crate::buffer::{Reader, Writer};
194pub use crate::config::Config;
195pub use crate::error::Error;
196pub use crate::fory::Fory;
197pub use crate::resolver::context::{ReadContext, WriteContext};
198pub use crate::resolver::type_resolver::{TypeInfo, TypeResolver};
199pub use crate::serializer::weak::{ArcWeak, RcWeak};
200pub use crate::serializer::{read_data, write_data, ForyDefault, Serializer, StructSerializer};
201pub use crate::types::{RefFlag, RefMode, TypeId};