Skip to main content

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