Skip to main content

fory_core/serializer/
rc.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 super::codec::{
19    codec_read_type_info, codec_read_type_info_static, codec_ref_mode, codec_write_type_info,
20    field_ref_mode, Codec,
21};
22use super::pointee::{PointeeCodec, PointeeSerializer};
23use crate::context::{ReadContext, WriteContext};
24use crate::error::Error;
25use crate::meta::FieldType;
26use crate::resolver::{RefFlag, RefMode, TypeInfo, TypeResolver};
27use crate::serializer::Serializer;
28use crate::type_id::TypeId;
29use std::marker::PhantomData;
30use std::rc::Rc;
31
32pub struct RcCodec<T: ?Sized, C, const NULLABLE: bool, const TRACK_REF: bool>(
33    PhantomData<(*const T, C)>,
34);
35
36#[cold]
37#[inline(never)]
38fn shared_rc_child() -> Error {
39    Error::not_allowed("Rc<T> where T is a shared ref type is not allowed")
40}
41
42#[cold]
43#[inline(never)]
44fn missing_rc_ref(ref_id: u32) -> Error {
45    Error::invalid_ref(format!("Rc reference {ref_id} not found"))
46}
47
48#[inline(always)]
49fn check_child<T: ?Sized + 'static, C: PointeeSerializer<T>>() -> Result<(), Error> {
50    // Nested shared owners would compete for reference framing and identity
51    // while both wrappers remain transparent on the wire.
52    if C::IS_SHARED_REF {
53        Err(shared_rc_child())
54    } else {
55        Ok(())
56    }
57}
58
59#[inline(always)]
60fn reserve_rc<T: ?Sized, C: PointeeSerializer<T>>(context: &mut ReadContext) -> Result<(), Error> {
61    let bytes = C::POINTEE_SIZE;
62    if bytes != 0 {
63        context.reserve_graph_memory(bytes)?;
64    }
65    Ok(())
66}
67
68#[inline(always)]
69fn write_inner<T: ?Sized + 'static, C: PointeeSerializer<T>>(
70    value: &T,
71    context: &mut WriteContext,
72    write_type_info: bool,
73) -> Result<(), Error> {
74    check_child::<T, C>()?;
75    C::write_pointee(value, context, RefMode::None, write_type_info)
76}
77
78#[inline(always)]
79fn write_inner_with_type_info<T: ?Sized + 'static, C: PointeeSerializer<T>>(
80    value: &T,
81    context: &mut WriteContext,
82    type_info: &Rc<TypeInfo>,
83) -> Result<(), Error> {
84    check_child::<T, C>()?;
85    C::write_pointee_with_type_info(value, context, RefMode::None, type_info)
86}
87
88#[inline(always)]
89fn write_inner_field<T: ?Sized + 'static, V: 'static, C: PointeeCodec<T, V>>(
90    value: &T,
91    context: &mut WriteContext,
92    write_type_info: bool,
93    has_generics: bool,
94) -> Result<(), Error> {
95    check_child::<T, C>()?;
96    C::write_pointee_with_mode(value, context, RefMode::None, write_type_info, has_generics)
97}
98
99#[inline(always)]
100fn write_inner_field_with_type_info<T: ?Sized + 'static, V: 'static, C: PointeeCodec<T, V>>(
101    value: &T,
102    context: &mut WriteContext,
103    type_info: &Rc<TypeInfo>,
104    has_generics: bool,
105) -> Result<(), Error> {
106    check_child::<T, C>()?;
107    C::write_pointee_field_with_type_info(value, context, RefMode::None, type_info, has_generics)
108}
109
110#[inline(always)]
111fn write_ref<T: ?Sized>(value: &Rc<T>, context: &mut WriteContext, ref_mode: RefMode) -> bool {
112    match ref_mode {
113        RefMode::None => true,
114        RefMode::NullOnly => {
115            context.writer.write_i8(RefFlag::NotNullValue as i8);
116            true
117        }
118        RefMode::Tracking => !context
119            .ref_writer
120            .try_write_rc_ref(&mut context.writer, value),
121    }
122}
123
124#[inline(always)]
125fn read_inner<T: ?Sized + 'static, C: PointeeSerializer<T>>(
126    context: &mut ReadContext,
127    read_type_info: bool,
128    type_info: Option<&Rc<TypeInfo>>,
129) -> Result<C::Target, Error> {
130    check_child::<T, C>()?;
131    reserve_rc::<T, C>(context)?;
132    if let Some(type_info) = type_info {
133        return C::read_with_type_info(context, RefMode::None, type_info);
134    }
135    if read_type_info {
136        C::read_type_info(context)?;
137    }
138    C::read_data(context)
139}
140
141#[inline(always)]
142fn read_inner_with_type<T: ?Sized + 'static, V: 'static, C: PointeeCodec<T, V>>(
143    context: &mut ReadContext,
144    remote_field_type: &FieldType,
145) -> Result<C::Target, Error> {
146    check_child::<T, C>()?;
147    reserve_rc::<T, C>(context)?;
148    // The Rc envelope owns only reference framing. A compatible
149    // metadata-bearing child still owns its inline TypeInfo before its body,
150    // while declared carrier children consume the remote schema directly.
151    if codec_read_type_info::<C::Target, C>(context, remote_field_type) {
152        return C::read(context, RefMode::None, true);
153    }
154    C::read_data_with_type(context, remote_field_type)
155}
156
157impl<T, C, const NULLABLE: bool, const TRACK_REF: bool> Serializer
158    for RcCodec<T, C, NULLABLE, TRACK_REF>
159where
160    T: ?Sized + 'static,
161    C: PointeeSerializer<T>,
162    Rc<T>: From<C::Target>,
163{
164    type Target = Rc<T>;
165
166    #[inline(always)]
167    fn reserved_space() -> usize {
168        4
169    }
170
171    #[inline(always)]
172    fn write_data(value: &Rc<T>, context: &mut WriteContext) -> Result<(), Error> {
173        write_inner::<T, C>(value, context, false)
174    }
175
176    #[inline(always)]
177    fn read_data(context: &mut ReadContext) -> Result<Rc<T>, Error> {
178        Ok(Rc::from(read_inner::<T, C>(context, false, None)?))
179    }
180
181    #[inline(always)]
182    fn write(
183        value: &Rc<T>,
184        context: &mut WriteContext,
185        ref_mode: RefMode,
186        write_type_info: bool,
187    ) -> Result<(), Error> {
188        if !write_ref(value, context, ref_mode) {
189            return Ok(());
190        }
191        write_inner::<T, C>(value, context, write_type_info)
192    }
193
194    #[inline(always)]
195    fn write_type_info_value(
196        context: &mut WriteContext,
197        target_type_id: std::any::TypeId,
198    ) -> Result<Rc<TypeInfo>, Error> {
199        C::write_type_info_value(context, target_type_id)
200    }
201
202    #[inline(always)]
203    fn write_with_type_info(
204        value: &Rc<T>,
205        context: &mut WriteContext,
206        ref_mode: RefMode,
207        type_info: &Rc<TypeInfo>,
208    ) -> Result<(), Error> {
209        if !write_ref(value, context, ref_mode) {
210            return Ok(());
211        }
212        write_inner_with_type_info::<T, C>(value, context, type_info)
213    }
214
215    #[inline(always)]
216    fn read(
217        context: &mut ReadContext,
218        ref_mode: RefMode,
219        read_type_info: bool,
220    ) -> Result<Rc<T>, Error> {
221        read_rc::<T, C>(context, ref_mode, read_type_info, None)
222    }
223
224    #[inline(always)]
225    fn read_with_type_info(
226        context: &mut ReadContext,
227        ref_mode: RefMode,
228        type_info: &Rc<TypeInfo>,
229    ) -> Result<Rc<T>, Error> {
230        read_rc::<T, C>(context, ref_mode, false, Some(type_info))
231    }
232
233    #[inline(always)]
234    fn default_value(context: &mut ReadContext) -> Result<Rc<T>, Error> {
235        check_child::<T, C>()?;
236        reserve_rc::<T, C>(context)?;
237        Ok(Rc::from(C::default_value(context)?))
238    }
239
240    #[inline(always)]
241    fn write_type_info(context: &mut WriteContext) -> Result<(), Error> {
242        C::write_type_info(context)
243    }
244
245    #[inline(always)]
246    fn read_type_info(context: &mut ReadContext) -> Result<(), Error> {
247        C::read_type_info(context)
248    }
249
250    #[inline(always)]
251    fn static_type_id() -> TypeId {
252        C::static_type_id()
253    }
254
255    #[inline(always)]
256    fn metadata_target_type_id() -> std::any::TypeId {
257        C::metadata_target_type_id()
258    }
259
260    const IS_POLYMORPHIC: bool = C::IS_POLYMORPHIC;
261
262    const IS_SHARED_REF: bool = true;
263
264    const IS_WRAPPER: bool = true;
265
266    const REQUIRES_SCOPED_ACCESS: bool = C::REQUIRES_SCOPED_ACCESS;
267
268    #[inline(always)]
269    fn dynamic_type_id(value: &Rc<T>) -> Result<Option<std::any::TypeId>, Error> {
270        C::pointee_dynamic_type_id(value)
271    }
272}
273
274impl<T, V, C, const NULLABLE: bool, const TRACK_REF: bool> Codec<Rc<T>>
275    for RcCodec<T, C, NULLABLE, TRACK_REF>
276where
277    T: ?Sized + 'static,
278    V: 'static,
279    C: Serializer<Target = V> + PointeeCodec<T, V>,
280    Rc<T>: From<C::Target>,
281{
282    #[inline(always)]
283    fn field_type(type_resolver: &TypeResolver) -> Result<FieldType, Error> {
284        let mut field_type = C::field_type(type_resolver)?;
285        field_type.nullable = NULLABLE;
286        field_type.track_ref = TRACK_REF;
287        Ok(field_type)
288    }
289
290    #[inline(always)]
291    fn write_field(value: &Rc<T>, context: &mut WriteContext) -> Result<(), Error> {
292        Self::write_with_mode(
293            value,
294            context,
295            codec_ref_mode::<C::Target, C, NULLABLE, TRACK_REF>(),
296            codec_write_type_info::<C::Target, C>(context),
297            true,
298        )
299    }
300
301    #[inline(always)]
302    fn read_field(context: &mut ReadContext) -> Result<Rc<T>, Error> {
303        <Self as Serializer>::read(
304            context,
305            codec_ref_mode::<C::Target, C, NULLABLE, TRACK_REF>(),
306            codec_read_type_info_static::<C::Target, C>(context),
307        )
308    }
309
310    #[inline(always)]
311    fn read_data_with_type(
312        context: &mut ReadContext,
313        remote_data_type: &FieldType,
314    ) -> Result<Rc<T>, Error> {
315        check_child::<T, C>()?;
316        reserve_rc::<T, C>(context)?;
317        Ok(Rc::from(C::read_data_with_type(context, remote_data_type)?))
318    }
319
320    #[inline(always)]
321    fn read_field_with_type(
322        context: &mut ReadContext,
323        remote_field_type: &FieldType,
324    ) -> Result<Rc<T>, Error> {
325        read_rc_with_type::<T, V, C>(
326            context,
327            field_ref_mode(remote_field_type),
328            remote_field_type,
329        )
330    }
331
332    #[inline(always)]
333    fn write_with_mode(
334        value: &Rc<T>,
335        context: &mut WriteContext,
336        ref_mode: RefMode,
337        write_type_info: bool,
338        has_generics: bool,
339    ) -> Result<(), Error> {
340        if !write_ref(value, context, ref_mode) {
341            return Ok(());
342        }
343        write_inner_field::<T, V, C>(value, context, write_type_info, has_generics)
344    }
345
346    #[inline(always)]
347    fn write_with_type_info(
348        value: &Rc<T>,
349        context: &mut WriteContext,
350        ref_mode: RefMode,
351        type_info: &Rc<TypeInfo>,
352        has_generics: bool,
353    ) -> Result<(), Error> {
354        if !write_ref(value, context, ref_mode) {
355            return Ok(());
356        }
357        write_inner_field_with_type_info::<T, V, C>(value, context, type_info, has_generics)
358    }
359
360    #[inline(always)]
361    fn read_type_info_value(
362        context: &mut ReadContext,
363    ) -> Result<super::codec::CodecReadType, Error> {
364        C::read_type_info_value(context)
365    }
366}
367
368macro_rules! read_rc_owner {
369    ($context:ident, $ref_mode:expr, $read_inner:expr, $default:expr) => {
370        match $ref_mode {
371            RefMode::None => Ok(Rc::from($read_inner?)),
372            RefMode::NullOnly => {
373                if $context.reader.read_i8()? == RefFlag::Null as i8 {
374                    return $default;
375                }
376                Ok(Rc::from($read_inner?))
377            }
378            RefMode::Tracking => match $context.ref_reader.read_ref_flag(&mut $context.reader)? {
379                RefFlag::Null => $default,
380                RefFlag::Ref => {
381                    let ref_id = $context.ref_reader.read_ref_id(&mut $context.reader)?;
382                    $context
383                        .ref_reader
384                        .get_rc_ref::<T>(ref_id)
385                        .ok_or_else(|| missing_rc_ref(ref_id))
386                }
387                RefFlag::NotNullValue => Ok(Rc::from($read_inner?)),
388                RefFlag::RefValue => {
389                    let ref_id = $context.ref_reader.reserve_ref_id();
390                    let value = Rc::from($read_inner?);
391                    $context.ref_reader.store_rc_ref_at(ref_id, value.clone());
392                    Ok(value)
393                }
394            },
395        }
396    };
397}
398
399#[inline(always)]
400fn read_rc<T: ?Sized + 'static, C: PointeeSerializer<T>>(
401    context: &mut ReadContext,
402    ref_mode: RefMode,
403    read_type_info: bool,
404    type_info: Option<&Rc<TypeInfo>>,
405) -> Result<Rc<T>, Error>
406where
407    Rc<T>: From<C::Target>,
408{
409    read_rc_owner!(
410        context,
411        ref_mode,
412        read_inner::<T, C>(context, read_type_info, type_info),
413        <RcCodec<T, C, false, false> as Serializer>::default_value(context)
414    )
415}
416
417#[inline(always)]
418fn read_rc_with_type<T: ?Sized + 'static, V: 'static, C: PointeeCodec<T, V>>(
419    context: &mut ReadContext,
420    ref_mode: RefMode,
421    remote_field_type: &FieldType,
422) -> Result<Rc<T>, Error>
423where
424    Rc<T>: From<C::Target>,
425{
426    read_rc_owner!(
427        context,
428        ref_mode,
429        read_inner_with_type::<T, V, C>(context, remote_field_type),
430        <RcCodec<T, C, false, false> as Serializer>::default_value(context)
431    )
432}
433
434impl_unsized_carrier_serializer!(Rc, RcCodec);
435
436impl_single_carrier_serializer!(RcSerializer, Rc, RcCodec, wrapper = true);