Skip to main content

fory_core/serializer/
core.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
18use crate::context::{ReadContext, WriteContext};
19use crate::error::Error;
20use crate::meta::FieldInfo;
21use crate::resolver::{RefFlag, RefMode, TypeInfo, TypeResolver};
22use crate::serializer::struct_;
23use crate::type_id::{self, TypeId};
24use std::any::Any;
25use std::rc::Rc;
26use std::sync::Arc;
27
28#[cold]
29#[inline(never)]
30fn default_unavailable<S: Serializer>() -> Result<S::Target, Error> {
31    Err(Error::type_error(format!(
32        "serializer {} has no default for target {}",
33        std::any::type_name::<S>(),
34        std::any::type_name::<S::Target>(),
35    )))
36}
37
38/// Static serialization behavior for one runtime [`Serializer::Target`].
39///
40/// Implementations define type-level serialization behavior and are never
41/// instantiated by Fory. Ordinary local types use `Target = Self`.
42pub trait Serializer: Sized + 'static {
43    type Target: Sized + 'static;
44
45    /// Write the target body only.
46    fn write_data(value: &Self::Target, context: &mut WriteContext) -> Result<(), Error>;
47
48    /// Read the target body only.
49    fn read_data(context: &mut ReadContext) -> Result<Self::Target, Error>;
50
51    /// Construct a target for a null or missing local value.
52    #[inline(always)]
53    fn default_value(context: &mut ReadContext) -> Result<Self::Target, Error> {
54        let _ = context;
55        default_unavailable::<Self>()
56    }
57
58    /// Write a complete value, including the requested reference and type
59    /// information envelopes, then write its body.
60    #[doc(hidden)]
61    #[inline(always)]
62    fn write(
63        value: &Self::Target,
64        context: &mut WriteContext,
65        ref_mode: RefMode,
66        write_type_info: bool,
67    ) -> Result<(), Error> {
68        if ref_mode != RefMode::None {
69            context.writer.write_i8(RefFlag::NotNullValue as i8);
70        }
71        if write_type_info {
72            Self::write_type_info(context)?;
73        }
74        Self::write_data(value, context)
75    }
76
77    /// Resolve and emit metadata for one dynamically selected concrete target.
78    ///
79    /// Homogeneous collection and map owners retain the returned [`TypeInfo`]
80    /// and pass it to every body in that wire chunk.
81    #[doc(hidden)]
82    #[inline(always)]
83    fn write_type_info_value(
84        context: &mut WriteContext,
85        target_type_id: std::any::TypeId,
86    ) -> Result<Rc<TypeInfo>, Error> {
87        context.write_target_type_info(Self::static_type_id() as u32, target_type_id)
88    }
89
90    /// Write a value using concrete type metadata already emitted by its
91    /// containing collection or map owner.
92    #[doc(hidden)]
93    #[inline(always)]
94    fn write_with_type_info(
95        value: &Self::Target,
96        context: &mut WriteContext,
97        ref_mode: RefMode,
98        type_info: &Rc<TypeInfo>,
99    ) -> Result<(), Error> {
100        let _ = type_info;
101        Self::write(value, context, ref_mode, false)
102    }
103
104    /// Read a complete value, including the requested reference and type
105    /// information envelopes, then read its body.
106    #[doc(hidden)]
107    #[inline(always)]
108    fn read(
109        context: &mut ReadContext,
110        ref_mode: RefMode,
111        read_type_info: bool,
112    ) -> Result<Self::Target, Error> {
113        if ref_mode != RefMode::None {
114            let flag = context.reader.read_i8()?;
115            if flag == RefFlag::Null as i8 {
116                return Self::default_value(context);
117            }
118        }
119        if read_type_info {
120            Self::read_type_info(context)?;
121        }
122        Self::read_data(context)
123    }
124
125    #[doc(hidden)]
126    #[inline(always)]
127    fn read_with_type_info(
128        context: &mut ReadContext,
129        ref_mode: RefMode,
130        type_info: &Rc<TypeInfo>,
131    ) -> Result<Self::Target, Error> {
132        let _ = type_info;
133        Self::read(context, ref_mode, false)
134    }
135
136    #[doc(hidden)]
137    #[inline(always)]
138    fn write_type_info(context: &mut WriteContext) -> Result<(), Error> {
139        context.write_provider_type_info(
140            Self::static_type_id() as u32,
141            std::any::TypeId::of::<Self>(),
142        )?;
143        Ok(())
144    }
145
146    #[doc(hidden)]
147    #[inline(always)]
148    fn read_type_info(context: &mut ReadContext) -> Result<(), Error> {
149        context.read_any_type_info()?;
150        Ok(())
151    }
152
153    /// Read directly into the final owner for sync dynamic carriers.
154    #[cold]
155    #[inline(never)]
156    fn read_arc_any(context: &mut ReadContext) -> Result<Arc<dyn Any + Send + Sync>, Error> {
157        let _ = context;
158        Err(Error::type_error(format!(
159            "target {} cannot be represented as Arc<dyn Any + Send + Sync>",
160            std::any::type_name::<Self::Target>(),
161        )))
162    }
163
164    #[doc(hidden)]
165    #[inline(always)]
166    fn static_type_id() -> TypeId {
167        TypeId::EXT
168    }
169
170    #[doc(hidden)]
171    #[inline(always)]
172    fn reserved_space() -> usize {
173        std::mem::size_of::<Self::Target>()
174    }
175
176    #[doc(hidden)]
177    const IS_OPTIONAL: bool = false;
178
179    #[doc(hidden)]
180    const IS_POLYMORPHIC: bool = false;
181
182    #[doc(hidden)]
183    const IS_SHARED_REF: bool = false;
184
185    #[doc(hidden)]
186    const IS_WRAPPER: bool = Self::IS_SHARED_REF;
187
188    #[doc(hidden)]
189    const REQUIRES_SCOPED_ACCESS: bool = false;
190
191    #[doc(hidden)]
192    #[inline(always)]
193    fn is_none(value: &Self::Target) -> bool {
194        let _ = value;
195        false
196    }
197
198    /// Return the concrete target selected by a polymorphic value.
199    ///
200    /// `None` means that the value is absent and has no concrete target.
201    #[doc(hidden)]
202    #[inline(always)]
203    fn dynamic_type_id(value: &Self::Target) -> Result<Option<std::any::TypeId>, Error> {
204        let _ = value;
205        Ok(Some(std::any::TypeId::of::<Self::Target>()))
206    }
207}
208
209#[inline(always)]
210pub(super) fn read_value_type_info<S: Serializer>(
211    context: &mut ReadContext,
212) -> Result<Option<Rc<TypeInfo>>, Error> {
213    // Static built-in carrier headers are compact type IDs, not registered
214    // serializers. Compatible TypeInfo exists only for metadata-bearing IDs.
215    if context.is_compatible() && !type_id::is_internal_type(S::static_type_id() as u32) {
216        return context.read_any_type_info().map(Some);
217    }
218    S::read_type_info(context)?;
219    Ok(None)
220}
221
222/// Schema metadata and compatible reads for derive-generated serializers.
223pub trait StructSerializer: Serializer {
224    fn type_index() -> u32;
225
226    #[cold]
227    #[inline(never)]
228    fn actual_type_id(
229        type_id: u32,
230        register_by_name: bool,
231        compatible: bool,
232        xlang: bool,
233    ) -> Result<u32, Error> {
234        let _ = xlang;
235        Ok(struct_::actual_type_id(
236            type_id,
237            register_by_name,
238            compatible,
239        ))
240    }
241
242    fn fields_info(type_resolver: &TypeResolver) -> Result<Vec<FieldInfo>, Error>;
243
244    fn variants_fields_info(
245        type_resolver: &TypeResolver,
246    ) -> Result<Vec<(String, std::any::TypeId, Vec<FieldInfo>)>, Error>;
247
248    fn sorted_field_names() -> &'static [&'static str];
249
250    fn read_compatible(
251        context: &mut ReadContext,
252        type_info: &Rc<TypeInfo>,
253    ) -> Result<Self::Target, Error>;
254
255    #[cold]
256    #[inline(never)]
257    fn read_compatible_arc_any(
258        context: &mut ReadContext,
259        type_info: &Rc<TypeInfo>,
260    ) -> Result<Arc<dyn Any + Send + Sync>, Error> {
261        let _ = context;
262        let _ = type_info;
263        Err(Error::type_error(format!(
264            "target {} cannot be represented as Arc<dyn Any + Send + Sync>",
265            std::any::type_name::<Self::Target>(),
266        )))
267    }
268}
269
270#[inline(always)]
271pub fn write_data<S: Serializer>(
272    value: &S::Target,
273    context: &mut WriteContext,
274) -> Result<(), Error> {
275    S::write_data(value, context)
276}
277
278#[inline(always)]
279pub fn read_data<S: Serializer>(context: &mut ReadContext) -> Result<S::Target, Error> {
280    S::read_data(context)
281}