Skip to main content

serde_saphyr/
anchors.rs

1//! Support for YAML anchors and aliases using smart pointers.
2//!
3//! This module provides wrappers around [`Rc`] and [`Arc`] (and their weak counterparts)
4//! to enable the serialization and deserialization of shared or recursive structures
5//! in YAML.
6//!
7//! ## Anchor Types
8//!
9//! There are two main categories of anchor types provided:
10//!
11//! 1. **Standard Anchors** ([`RcAnchor`], [`ArcAnchor`], [`RcWeakAnchor`], [`ArcWeakAnchor`]):
12//!    - Designed for **Directed Acyclic Graphs (DAGs)** where multiple fields share ownership
13//!      of the same object.
14//!    - During deserialization, the strong anchor must be fully parsed before any of its aliases
15//!      (weak anchors) are encountered.
16//!    - These types are simpler to use because they implement [`Deref`] directly to the inner type `T`.
17//!
18//! 2. **Recursive Anchors** ([`RcRecursive`], [`ArcRecursive`], [`RcRecursion`], [`ArcRecursion`]):
19//!    - Specifically designed for **circular or recursive graphs** (e.g., an object that
20//!      contains a reference to itself).
21//!    - They allow an object to be referenced via an alias *before* it has been fully deserialized.
22//!
23//! ## Recursive Anchors Are More Complex
24//!
25//! Recursive anchors require a more complex internal structure because they must handle late
26//! initialization. When the deserializer encounters a recursive anchor, it creates a placeholder
27//! and registers it. Once the object's data is fully parsed, the placeholder is updated with the
28//! actual value. This requires interior mutability to fill in the value after the container has
29//! already been shared, and optionality ([`Option`]) to represent the uninitialized state.
30//!
31//! Because of this, you cannot [`Deref`] directly to `T`. Instead, you must use methods like
32//! [`.borrow()`](RcRecursive::borrow) or [`.lock()`](ArcRecursive::lock) to access the underlying data.
33//!
34//! For a complete working example of recursive anchors, see `examples/recursive_yaml.rs`.
35
36use std::borrow::Borrow;
37use std::cell::RefCell;
38use std::fmt;
39use std::marker::PhantomData;
40use std::ops::Deref;
41use std::rc::{Rc, Weak as RcWeak};
42use std::sync::{Arc, Mutex, Weak as ArcWeak};
43
44use serde::de::{Error as _, Visitor};
45
46use crate::anchor_store;
47
48/// A wrapper around [`Rc<T>`] that opt-ins a field for **anchor emission** (e.g. serialization by reference).
49///
50/// This type behaves like a normal [`Rc<T>`] but signals that the value
51/// should be treated as an *anchorable* reference — for instance,
52/// when serializing graphs or shared structures where pointer identity matters.
53///
54/// # Examples
55///
56/// ```
57/// use std::rc::Rc;
58/// use serde_saphyr::RcAnchor;
59///
60/// // Create from an existing Rc
61/// let rc = Rc::new(String::from("Hello"));
62/// let anchor1 = RcAnchor::from(rc.clone());
63///
64/// // Or directly from a value (Rc::new is called internally)
65/// let anchor2: RcAnchor<String> = RcAnchor::from(Rc::new(String::from("World")));
66///
67/// assert_eq!(*anchor1.0, "Hello");
68/// assert_eq!(*anchor2.0, "World");
69/// ```
70#[repr(transparent)]
71#[derive(Clone)]
72pub struct RcAnchor<T>(pub Rc<T>);
73
74/// A wrapper around [`Arc<T>`] that opt-ins a field for **anchor emission** (e.g. serialization by reference).
75///
76/// It behaves exactly like an [`Arc<T>`] but explicitly marks shared ownership
77/// as an *anchor* for reference tracking or cross-object linking.
78///
79/// # Examples
80///
81/// ```
82/// use std::sync::Arc;
83/// use serde_saphyr::ArcAnchor;
84///
85/// // Create from an existing Arc
86/// let arc = Arc::new(String::from("Shared"));
87/// let anchor1 = ArcAnchor::from(arc.clone());
88///
89/// // Or create directly from a value
90/// let anchor2: ArcAnchor<String> = ArcAnchor::from(Arc::new(String::from("Data")));
91///
92/// assert_eq!(*anchor1.0, "Shared");
93/// assert_eq!(*anchor2.0, "Data");
94/// ```
95#[repr(transparent)]
96#[derive(Clone)]
97pub struct ArcAnchor<T>(pub Arc<T>);
98
99/// A wrapper around [`Weak<T>`] (from [`std::rc`]) that opt-ins for **anchor emission**.
100///
101/// When serialized, if the weak reference is **dangling** (i.e., the value was dropped),
102/// it emits `null` to indicate that the target no longer exists.
103/// Provides convenience methods like [`upgrade`](Self::upgrade) and [`is_dangling`](Self::is_dangling).
104///
105/// > **Note on deserialization:** `null` deserializes back into a dangling weak (`Weak::new()`).
106/// > Non-`null` cannot be safely reconstructed into a `Weak` without a shared registry; we reject it.
107/// > Ask if you want an ID/registry-based scheme to restore sharing.
108///
109/// # Examples
110///
111/// ```
112/// use std::rc::Rc;
113/// use serde_saphyr::{RcAnchor, RcWeakAnchor};
114///
115/// let rc_anchor = RcAnchor::from(Rc::new(String::from("Persistent")));
116///
117/// // Create a weak anchor from a strong reference
118/// let weak_anchor = RcWeakAnchor::from(&rc_anchor.0);
119///
120/// assert!(weak_anchor.upgrade().is_some());
121/// drop(rc_anchor);
122/// assert!(weak_anchor.upgrade().is_none());
123/// ```
124#[repr(transparent)]
125#[derive(Clone)]
126pub struct RcWeakAnchor<T>(pub RcWeak<T>);
127
128/// A wrapper around [`Weak<T>`] (from [`std::sync`]) that opt-ins for **anchor emission**.
129///
130/// This variant is thread-safe and uses [`Arc`] / [`Weak`] instead of [`Rc`].
131/// If the weak reference is **dangling**, it serializes as `null`.
132///
133/// > **Deserialization note:** `null` → dangling weak. Non-`null` is rejected unless a registry is used.
134///
135/// # Examples
136///
137/// ```
138/// use std::sync::Arc;
139/// use serde_saphyr::{ArcAnchor, ArcWeakAnchor};
140///
141/// let arc_anchor = ArcAnchor::from(Arc::new(String::from("Thread-safe")));
142///
143/// // Create a weak anchor from the strong reference
144/// let weak_anchor = ArcWeakAnchor::from(&arc_anchor.0);
145///
146/// assert!(weak_anchor.upgrade().is_some());
147/// drop(arc_anchor);
148/// assert!(weak_anchor.upgrade().is_none());
149/// ```
150#[repr(transparent)]
151#[derive(Clone)]
152pub struct ArcWeakAnchor<T>(pub ArcWeak<T>);
153
154/// The parent (origin) anchor definition that may have recursive references to it.
155/// This type provides the value for the references and must be placed where the original value is defined.
156/// Fields that reference this value (possibly recursively) must be wrapped in [`RcRecursion`].
157/// ```rust
158/// use std::cell::Ref;
159/// use serde::{Deserialize, Serialize};
160/// use serde_saphyr::{RcRecursion, RcRecursive};
161/// #[derive(Deserialize, Serialize)]
162/// struct King {
163///     name: String,
164///     coronator: RcRecursion<King>, // who crowned this king
165/// }
166///
167/// #[derive(Deserialize, Serialize)]
168/// struct Kingdom {
169///     king: RcRecursive<King>,
170/// }
171///     let yaml = r#"
172/// king: &root
173///   name: "Aurelian I"
174///   coronator: *root # this king crowned himself
175/// "#;
176///
177/// let kingdom_data: Kingdom = serde_saphyr::from_str(yaml).unwrap();
178///     let king: Ref<King> = kingdom_data.king.borrow();
179///     let coronator = king
180///         .coronator
181///         .upgrade().expect("coronator always exists");
182///     let coronator_name = &coronator.borrow().name;
183///     assert_eq!(coronator_name, "Aurelian I");
184/// ```
185#[repr(transparent)]
186#[derive(Clone)]
187pub struct RcRecursive<T>(pub Rc<RefCell<Option<T>>>);
188
189/// The parent (origin) anchor definition that may have recursive references to it.
190/// This type provides the value for the references and must be placed where the original value is defined.
191/// Fields that reference this value (possibly recursively) must be wrapped in [`ArcRecursion`].
192/// ```rust
193/// use serde::{Deserialize, Serialize};
194/// use serde_saphyr::{ArcRecursion, ArcRecursive};
195///
196/// #[derive(Deserialize, Serialize)]
197/// struct King {
198///     name: String,
199///     coronator: ArcRecursion<King>, // who crowned this king
200/// }
201///
202/// #[derive(Deserialize, Serialize)]
203/// struct Kingdom {
204///     king: ArcRecursive<King>,
205/// }
206///
207///     let yaml = r#"
208/// king: &root
209///   name: "Aurelian I"
210///   coronator: *root # this king crowned himself
211/// "#;
212///
213///     let kingdom_data: Kingdom = serde_saphyr::from_str(yaml).unwrap();
214///     let coronator = {
215///         let king_guard = kingdom_data.king.lock().unwrap();
216///         let king = king_guard.as_ref().expect("king should be initialized");
217///         king.coronator
218///             .upgrade()
219///             .expect("coronator should be alive")
220///     };
221///
222///     let coronator_guard = coronator.lock().unwrap();
223///     let coronator_ref = coronator_guard
224///         .as_ref()
225///         .expect("coronator should be initialized");
226///     assert_eq!(coronator_ref.name, "Aurelian I");
227/// ```
228#[repr(transparent)]
229#[derive(Clone)]
230pub struct ArcRecursive<T>(pub Arc<Mutex<Option<T>>>);
231
232/// The possibly recursive reference to the parent anchor that must be [`RcRecursive`].
233/// See [`RcRecursive`] for code example.
234#[repr(transparent)]
235#[derive(Clone)]
236pub struct RcRecursion<T>(pub RcWeak<RefCell<Option<T>>>);
237
238/// The possibly recursive reference to the parent anchor that must be [`ArcRecursive`], thread safe
239/// It is more complex to use than [`RcRecursive`] (you need to lock it before accessing the value)
240/// See [`ArcRecursive`] for code example.
241#[repr(transparent)]
242#[derive(Clone)]
243pub struct ArcRecursion<T>(pub ArcWeak<Mutex<Option<T>>>);
244
245// ===== From conversions (strong -> anchor) =====
246
247impl<T> From<Rc<T>> for RcAnchor<T> {
248    fn from(rc: Rc<T>) -> Self {
249        RcAnchor(rc)
250    }
251}
252
253impl<T> RcAnchor<T> {
254    /// Create inner Rc (takes arbitrary value Rc can take)
255    pub fn wrapping(x: T) -> Self {
256        RcAnchor(Rc::new(x))
257    }
258}
259
260impl<T> ArcAnchor<T> {
261    /// Create inner Arc (takes arbitrary value Arc can take)
262    pub fn wrapping(x: T) -> Self {
263        ArcAnchor(Arc::new(x))
264    }
265}
266
267impl<T> From<Arc<T>> for ArcAnchor<T> {
268    #[inline]
269    fn from(arc: Arc<T>) -> Self {
270        ArcAnchor(arc)
271    }
272}
273
274// ===== From conversions (strong -> weak anchor) =====
275
276impl<T> From<&Rc<T>> for RcWeakAnchor<T> {
277    #[inline]
278    fn from(rc: &Rc<T>) -> Self {
279        RcWeakAnchor(Rc::downgrade(rc))
280    }
281}
282impl<T> From<Rc<T>> for RcWeakAnchor<T> {
283    #[inline]
284    fn from(rc: Rc<T>) -> Self {
285        RcWeakAnchor(Rc::downgrade(&rc))
286    }
287}
288impl<T> From<&RcAnchor<T>> for RcWeakAnchor<T> {
289    #[inline]
290    fn from(rca: &RcAnchor<T>) -> Self {
291        RcWeakAnchor(Rc::downgrade(&rca.0))
292    }
293}
294impl<T> From<&Arc<T>> for ArcWeakAnchor<T> {
295    #[inline]
296    fn from(arc: &Arc<T>) -> Self {
297        ArcWeakAnchor(Arc::downgrade(arc))
298    }
299}
300impl<T> From<Arc<T>> for ArcWeakAnchor<T> {
301    #[inline]
302    fn from(arc: Arc<T>) -> Self {
303        ArcWeakAnchor(Arc::downgrade(&arc))
304    }
305}
306impl<T> From<&ArcAnchor<T>> for ArcWeakAnchor<T> {
307    #[inline]
308    fn from(ara: &ArcAnchor<T>) -> Self {
309        ArcWeakAnchor(Arc::downgrade(&ara.0))
310    }
311}
312
313// ===== From conversions (recursive strong -> weak) =====
314
315impl<T> From<&RcRecursive<T>> for RcRecursion<T> {
316    #[inline]
317    fn from(rca: &RcRecursive<T>) -> Self {
318        RcRecursion(Rc::downgrade(&rca.0))
319    }
320}
321
322impl<T> From<&ArcRecursive<T>> for ArcRecursion<T> {
323    #[inline]
324    fn from(ara: &ArcRecursive<T>) -> Self {
325        ArcRecursion(Arc::downgrade(&ara.0))
326    }
327}
328
329// ===== Ergonomics: Deref / AsRef / Borrow / Into =====
330
331impl<T> Deref for RcAnchor<T> {
332    type Target = Rc<T>;
333    #[inline]
334    fn deref(&self) -> &Self::Target {
335        &self.0
336    }
337}
338impl<T> Deref for ArcAnchor<T> {
339    type Target = Arc<T>;
340    #[inline]
341    fn deref(&self) -> &Self::Target {
342        &self.0
343    }
344}
345impl<T> Deref for RcRecursive<T> {
346    type Target = Rc<RefCell<Option<T>>>;
347    #[inline]
348    fn deref(&self) -> &Self::Target {
349        &self.0
350    }
351}
352impl<T> Deref for ArcRecursive<T> {
353    type Target = Arc<Mutex<Option<T>>>;
354    #[inline]
355    fn deref(&self) -> &Self::Target {
356        &self.0
357    }
358}
359impl<T> AsRef<Rc<T>> for RcAnchor<T> {
360    #[inline]
361    fn as_ref(&self) -> &Rc<T> {
362        &self.0
363    }
364}
365impl<T> AsRef<Arc<T>> for ArcAnchor<T> {
366    #[inline]
367    fn as_ref(&self) -> &Arc<T> {
368        &self.0
369    }
370}
371impl<T> Borrow<Rc<T>> for RcAnchor<T> {
372    #[inline]
373    fn borrow(&self) -> &Rc<T> {
374        &self.0
375    }
376}
377impl<T> Borrow<Arc<T>> for ArcAnchor<T> {
378    #[inline]
379    fn borrow(&self) -> &Arc<T> {
380        &self.0
381    }
382}
383impl<T> From<RcAnchor<T>> for Rc<T> {
384    #[inline]
385    fn from(a: RcAnchor<T>) -> Rc<T> {
386        a.0
387    }
388}
389impl<T> From<ArcAnchor<T>> for Arc<T> {
390    #[inline]
391    fn from(a: ArcAnchor<T>) -> Arc<T> {
392        a.0
393    }
394}
395
396impl<T> RcRecursive<T> {
397    /// Create a new recursive anchor with an initialized value.
398    pub fn wrapping(x: T) -> Self {
399        RcRecursive(Rc::new(RefCell::new(Some(x))))
400    }
401
402    /// Borrow the inner value
403    pub fn borrow(&self) -> std::cell::Ref<'_, T> {
404        let borrowed = self.0.as_ref().borrow();
405        std::cell::Ref::map(borrowed, |opt: &Option<T>| {
406            opt.as_ref().expect("recursive Rc anchor not initialized")
407        })
408    }
409}
410
411impl<T> ArcRecursive<T> {
412    /// Create a new recursive anchor with an initialized value.
413    pub fn wrapping(x: T) -> Self {
414        ArcRecursive(Arc::new(Mutex::new(Some(x))))
415    }
416
417    /// Lock the recursive anchor value so that it can be accessed safely.
418    pub fn lock(&self) -> std::sync::LockResult<std::sync::MutexGuard<'_, Option<T>>> {
419        self.0.lock()
420    }
421}
422
423// ===== Weak helpers =====
424
425impl<T> RcWeakAnchor<T> {
426    /// Try to upgrade the weak reference to [`Rc<T>`].
427    /// Returns [`None`] if the value has been dropped.
428    #[inline]
429    pub fn upgrade(&self) -> Option<Rc<T>> {
430        self.0.upgrade()
431    }
432
433    /// Returns `true` if the underlying value has been dropped (no strong refs remain).
434    #[inline]
435    pub fn is_dangling(&self) -> bool {
436        self.0.strong_count() == 0
437    }
438}
439impl<T> RcRecursion<T> {
440    /// Try to upgrade the weak reference to [`RcRecursive<T>`].
441    #[inline]
442    pub fn upgrade(&self) -> Option<RcRecursive<T>> {
443        self.0.upgrade().map(RcRecursive)
444    }
445
446    /// Access the recursive value in one step, if it is still alive.
447    #[inline]
448    pub fn with<R>(&self, f: impl FnOnce(&T) -> R) -> Option<R> {
449        let upgraded = self.upgrade()?;
450        let borrowed = upgraded.borrow();
451        Some(f(&borrowed))
452    }
453
454    /// Returns `true` if the underlying value has been dropped (no strong refs remain).
455    #[inline]
456    pub fn is_dangling(&self) -> bool {
457        self.0.strong_count() == 0
458    }
459}
460impl<T> ArcRecursion<T> {
461    /// Try to upgrade the weak reference to [`ArcRecursive<T>`].
462    #[inline]
463    pub fn upgrade(&self) -> Option<ArcRecursive<T>> {
464        self.0.upgrade().map(ArcRecursive)
465    }
466
467    /// Access the recursive value in one step, if it is still alive.
468    #[inline]
469    pub fn with<R>(&self, f: impl FnOnce(&T) -> R) -> Option<R> {
470        let upgraded = self.upgrade()?;
471        let guard = upgraded.lock().ok()?;
472        let value = guard.as_ref()?;
473        Some(f(value))
474    }
475
476    /// Returns `true` if the underlying value has been dropped (no strong refs remain).
477    #[inline]
478    pub fn is_dangling(&self) -> bool {
479        self.0.strong_count() == 0
480    }
481}
482impl<T> ArcWeakAnchor<T> {
483    /// Try to upgrade the weak reference to [`Arc<T>`].
484    /// Returns [`None`] if the value has been dropped.
485    #[inline]
486    pub fn upgrade(&self) -> Option<Arc<T>> {
487        self.0.upgrade()
488    }
489
490    /// Returns `true` if the underlying value has been dropped (no strong refs remain).
491    #[inline]
492    pub fn is_dangling(&self) -> bool {
493        self.0.strong_count() == 0
494    }
495}
496
497// ===== Pointer-equality PartialEq/Eq =====
498
499impl<T> PartialEq for RcAnchor<T> {
500    #[inline]
501    fn eq(&self, other: &Self) -> bool {
502        Rc::ptr_eq(&self.0, &other.0)
503    }
504}
505impl<T> Eq for RcAnchor<T> {}
506
507impl<T> PartialEq for ArcAnchor<T> {
508    #[inline]
509    fn eq(&self, other: &Self) -> bool {
510        Arc::ptr_eq(&self.0, &other.0)
511    }
512}
513impl<T> Eq for ArcAnchor<T> {}
514
515impl<T> PartialEq for RcWeakAnchor<T> {
516    #[inline]
517    fn eq(&self, other: &Self) -> bool {
518        match (self.0.upgrade(), other.0.upgrade()) {
519            (Some(a), Some(b)) => Rc::ptr_eq(&a, &b),
520            (None, None) => true,
521            _ => false,
522        }
523    }
524}
525impl<T> Eq for RcWeakAnchor<T> {}
526
527impl<T> PartialEq for RcRecursion<T> {
528    #[inline]
529    fn eq(&self, other: &Self) -> bool {
530        match (self.0.upgrade(), other.0.upgrade()) {
531            (Some(a), Some(b)) => Rc::ptr_eq(&a, &b),
532            (None, None) => true,
533            _ => false,
534        }
535    }
536}
537impl<T> Eq for RcRecursion<T> {}
538
539impl<T> PartialEq for ArcWeakAnchor<T> {
540    #[inline]
541    fn eq(&self, other: &Self) -> bool {
542        match (self.0.upgrade(), other.0.upgrade()) {
543            (Some(a), Some(b)) => Arc::ptr_eq(&a, &b),
544            (None, None) => true,
545            _ => false,
546        }
547    }
548}
549impl<T> PartialEq for RcRecursive<T> {
550    #[inline]
551    fn eq(&self, other: &Self) -> bool {
552        Rc::ptr_eq(&self.0, &other.0)
553    }
554}
555impl<T> Eq for RcRecursive<T> {}
556
557impl<T> PartialEq for ArcRecursion<T> {
558    #[inline]
559    fn eq(&self, other: &Self) -> bool {
560        match (self.0.upgrade(), other.0.upgrade()) {
561            (Some(a), Some(b)) => Arc::ptr_eq(&a, &b),
562            (None, None) => true,
563            _ => false,
564        }
565    }
566}
567impl<T> Eq for ArcRecursion<T> {}
568
569impl<T> PartialEq for ArcRecursive<T> {
570    #[inline]
571    fn eq(&self, other: &Self) -> bool {
572        Arc::ptr_eq(&self.0, &other.0)
573    }
574}
575impl<T> Eq for ArcRecursive<T> {}
576impl<T> Eq for ArcWeakAnchor<T> {}
577
578// ===== Debug =====
579
580impl<T> fmt::Debug for RcAnchor<T> {
581    #[inline]
582    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
583        write!(f, "RcAnchor({:p})", Rc::as_ptr(&self.0))
584    }
585}
586impl<T> fmt::Debug for ArcAnchor<T> {
587    #[inline]
588    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
589        write!(f, "ArcAnchor({:p})", Arc::as_ptr(&self.0))
590    }
591}
592impl<T> fmt::Debug for RcWeakAnchor<T> {
593    #[inline]
594    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
595        if let Some(rc) = self.0.upgrade() {
596            write!(f, "RcWeakAnchor(upgrade={:p})", Rc::as_ptr(&rc))
597        } else {
598            write!(f, "RcWeakAnchor(dangling)")
599        }
600    }
601}
602impl<T> fmt::Debug for ArcWeakAnchor<T> {
603    #[inline]
604    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
605        if let Some(arc) = self.0.upgrade() {
606            write!(f, "ArcWeakAnchor(upgrade={:p})", Arc::as_ptr(&arc))
607        } else {
608            write!(f, "ArcWeakAnchor(dangling)")
609        }
610    }
611}
612impl<T> fmt::Debug for RcRecursive<T> {
613    #[inline]
614    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
615        write!(f, "RcRecursive({:p})", Rc::as_ptr(&self.0))
616    }
617}
618impl<T> fmt::Debug for ArcRecursive<T> {
619    #[inline]
620    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
621        write!(f, "ArcRecursive({:p})", Arc::as_ptr(&self.0))
622    }
623}
624impl<T> fmt::Debug for RcRecursion<T> {
625    #[inline]
626    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
627        if let Some(rc) = self.0.upgrade() {
628            write!(f, "RcRecursion(upgrade={:p})", Rc::as_ptr(&rc))
629        } else {
630            write!(f, "RcRecursion(dangling)")
631        }
632    }
633}
634impl<T> fmt::Debug for ArcRecursion<T> {
635    #[inline]
636    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
637        if let Some(arc) = self.0.upgrade() {
638            write!(f, "ArcRecursion(upgrade={:p})", Arc::as_ptr(&arc))
639        } else {
640            write!(f, "ArcRecursion(dangling)")
641        }
642    }
643}
644
645// ===== Default =====
646
647impl<T: Default> Default for RcAnchor<T> {
648    #[inline]
649    fn default() -> Self {
650        RcAnchor(Rc::new(T::default()))
651    }
652}
653impl<T: Default> Default for ArcAnchor<T> {
654    fn default() -> Self {
655        ArcAnchor(Arc::new(T::default()))
656    }
657}
658impl<T: Default> Default for RcRecursive<T> {
659    #[inline]
660    fn default() -> Self {
661        RcRecursive(Rc::new(RefCell::new(Some(T::default()))))
662    }
663}
664impl<T: Default> Default for ArcRecursive<T> {
665    fn default() -> Self {
666        ArcRecursive(Arc::new(Mutex::new(Some(T::default()))))
667    }
668}
669
670// -------------------------------
671// Deserialize impls
672// -------------------------------
673impl<'de, T> serde::de::Deserialize<'de> for RcAnchor<T>
674where
675    T: serde::de::Deserialize<'de> + 'static,
676{
677    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
678    where
679        D: serde::de::Deserializer<'de>,
680    {
681        struct RcAnchorVisitor<T>(PhantomData<T>);
682
683        impl<'de, T> Visitor<'de> for RcAnchorVisitor<T>
684        where
685            T: serde::de::Deserialize<'de> + 'static,
686        {
687            type Value = RcAnchor<T>;
688
689            fn expecting(&self, f: &mut fmt::Formatter) -> fmt::Result {
690                f.write_str("an RcAnchor newtype")
691            }
692
693            fn visit_newtype_struct<D>(self, deserializer: D) -> Result<Self::Value, D::Error>
694            where
695                D: serde::de::Deserializer<'de>,
696            {
697                let anchor_id = anchor_store::current_rc_anchor();
698                let existing = match anchor_id {
699                    Some(id) => {
700                        Some((id, anchor_store::get_rc::<T>(id).map_err(D::Error::custom)?))
701                    }
702                    None => None,
703                };
704                if let Some((id, None)) = existing
705                    && anchor_store::rc_anchor_reentrant(id)
706                {
707                    return Err(D::Error::custom(
708                        "Recursive references require weak anchors",
709                    ));
710                }
711
712                let value = T::deserialize(deserializer)?;
713                if let Some((_, Some(rc))) = existing {
714                    drop(value);
715                    return Ok(RcAnchor(rc));
716                }
717                if let Some((id, None)) = existing {
718                    let rc = Rc::new(value);
719                    anchor_store::store_rc(id, rc.clone());
720                    return Ok(RcAnchor(rc));
721                }
722                Ok(RcAnchor(Rc::new(value)))
723            }
724        }
725
726        deserializer.deserialize_newtype_struct("__yaml_rc_anchor", RcAnchorVisitor(PhantomData))
727    }
728}
729
730impl<'de, T> serde::de::Deserialize<'de> for ArcAnchor<T>
731where
732    T: serde::de::Deserialize<'de> + Send + Sync + 'static,
733{
734    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
735    where
736        D: serde::de::Deserializer<'de>,
737    {
738        struct ArcAnchorVisitor<T>(PhantomData<T>);
739
740        impl<'de, T> Visitor<'de> for ArcAnchorVisitor<T>
741        where
742            T: serde::de::Deserialize<'de> + Send + Sync + 'static,
743        {
744            type Value = ArcAnchor<T>;
745
746            fn expecting(&self, f: &mut fmt::Formatter) -> fmt::Result {
747                f.write_str("an ArcAnchor newtype")
748            }
749
750            fn visit_newtype_struct<D>(self, deserializer: D) -> Result<Self::Value, D::Error>
751            where
752                D: serde::de::Deserializer<'de>,
753            {
754                let anchor_id = anchor_store::current_arc_anchor();
755                let existing = match anchor_id {
756                    Some(id) => Some((
757                        id,
758                        anchor_store::get_arc::<T>(id).map_err(D::Error::custom)?,
759                    )),
760                    None => None,
761                };
762                if let Some((id, None)) = existing
763                    && anchor_store::arc_anchor_reentrant(id)
764                {
765                    return Err(D::Error::custom(
766                        "Recursive references require weak anchors",
767                    ));
768                }
769
770                let value = T::deserialize(deserializer)?;
771                if let Some((_, Some(arc))) = existing {
772                    drop(value);
773                    return Ok(ArcAnchor(arc));
774                }
775                if let Some((id, None)) = existing {
776                    let arc = Arc::new(value);
777                    anchor_store::store_arc(id, arc.clone());
778                    return Ok(ArcAnchor(arc));
779                }
780                Ok(ArcAnchor(Arc::new(value)))
781            }
782        }
783
784        deserializer.deserialize_newtype_struct("__yaml_arc_anchor", ArcAnchorVisitor(PhantomData))
785    }
786}
787
788impl<'de, T> serde::de::Deserialize<'de> for RcRecursive<T>
789where
790    T: serde::de::Deserialize<'de> + 'static,
791{
792    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
793    where
794        D: serde::de::Deserializer<'de>,
795    {
796        struct RcRecursiveVisitor<T>(PhantomData<T>);
797
798        impl<'de, T> Visitor<'de> for RcRecursiveVisitor<T>
799        where
800            T: serde::de::Deserialize<'de> + 'static,
801        {
802            type Value = RcRecursive<T>;
803
804            fn expecting(&self, f: &mut fmt::Formatter) -> fmt::Result {
805                f.write_str("an RcRecursive newtype")
806            }
807
808            fn visit_newtype_struct<D>(self, deserializer: D) -> Result<Self::Value, D::Error>
809            where
810                D: serde::de::Deserializer<'de>,
811            {
812                let anchor_id = anchor_store::current_rc_recursive_anchor();
813                let existing = match anchor_id {
814                    Some(id) => Some((
815                        id,
816                        anchor_store::get_rc_recursive::<RefCell<Option<T>>>(id)
817                            .map_err(D::Error::custom)?,
818                    )),
819                    None => None,
820                };
821                if let Some((id, None)) = existing
822                    && anchor_store::rc_recursive_reentrant(id)
823                {
824                    return Err(D::Error::custom(
825                        "recursive references require weak recursion types",
826                    ));
827                }
828
829                if let Some((_, Some(rc))) = existing {
830                    let value = T::deserialize(deserializer)?;
831                    drop(value);
832                    return Ok(RcRecursive(rc));
833                }
834
835                if let Some((id, None)) = existing {
836                    let rc = Rc::new(RefCell::new(None));
837                    anchor_store::store_rc_recursive(id, rc.clone());
838
839                    let value = T::deserialize(deserializer)?;
840                    *rc.borrow_mut() = Some(value);
841                    return Ok(RcRecursive(rc));
842                }
843
844                let value = T::deserialize(deserializer)?;
845                Ok(RcRecursive(Rc::new(RefCell::new(Some(value)))))
846            }
847        }
848
849        deserializer
850            .deserialize_newtype_struct("__yaml_rc_recursive", RcRecursiveVisitor(PhantomData))
851    }
852}
853
854impl<'de, T> serde::de::Deserialize<'de> for ArcRecursive<T>
855where
856    T: serde::de::Deserialize<'de> + Send + Sync + 'static,
857{
858    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
859    where
860        D: serde::de::Deserializer<'de>,
861    {
862        struct ArcRecursiveVisitor<T>(PhantomData<T>);
863
864        impl<'de, T> Visitor<'de> for ArcRecursiveVisitor<T>
865        where
866            T: serde::de::Deserialize<'de> + Send + Sync + 'static,
867        {
868            type Value = ArcRecursive<T>;
869
870            fn expecting(&self, f: &mut fmt::Formatter) -> fmt::Result {
871                f.write_str("an ArcRecursive newtype")
872            }
873
874            fn visit_newtype_struct<D>(self, deserializer: D) -> Result<Self::Value, D::Error>
875            where
876                D: serde::de::Deserializer<'de>,
877            {
878                let anchor_id = anchor_store::current_arc_recursive_anchor();
879                let existing = match anchor_id {
880                    Some(id) => Some((
881                        id,
882                        anchor_store::get_arc_recursive::<Mutex<Option<T>>>(id)
883                            .map_err(D::Error::custom)?,
884                    )),
885                    None => None,
886                };
887                if let Some((id, None)) = existing
888                    && anchor_store::arc_recursive_reentrant(id)
889                {
890                    return Err(D::Error::custom(
891                        "recursive references require weak recursion types",
892                    ));
893                }
894
895                if let Some((_, Some(arc))) = existing {
896                    let value = T::deserialize(deserializer)?;
897                    drop(value);
898                    return Ok(ArcRecursive(arc));
899                }
900
901                if let Some((id, None)) = existing {
902                    let arc = Arc::new(Mutex::new(None));
903                    anchor_store::store_arc_recursive(id, arc.clone());
904
905                    let value = T::deserialize(deserializer)?;
906                    *arc.lock()
907                        .map_err(|_| D::Error::custom("recursive Arc anchor mutex poisoned"))? =
908                        Some(value);
909                    return Ok(ArcRecursive(arc));
910                }
911
912                let value = T::deserialize(deserializer)?;
913                Ok(ArcRecursive(Arc::new(Mutex::new(Some(value)))))
914            }
915        }
916
917        deserializer
918            .deserialize_newtype_struct("__yaml_arc_recursive", ArcRecursiveVisitor(PhantomData))
919    }
920}
921
922// -------------------------------
923// Deserialize impls for WEAK anchors (RcWeakAnchor / ArcWeakAnchor)
924// -------------------------------
925impl<'de, T> serde::de::Deserialize<'de> for RcWeakAnchor<T>
926where
927    T: serde::de::Deserialize<'de> + 'static,
928{
929    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
930    where
931        D: serde::de::Deserializer<'de>,
932    {
933        struct RcWeakVisitor<T>(PhantomData<T>);
934        impl<'de, T> Visitor<'de> for RcWeakVisitor<T>
935        where
936            T: serde::de::Deserialize<'de> + 'static,
937        {
938            type Value = RcWeakAnchor<T>;
939            fn expecting(&self, f: &mut fmt::Formatter) -> fmt::Result {
940                f.write_str(
941                    "an RcWeakAnchor referring to a previously defined strong anchor (via alias)",
942                )
943            }
944            fn visit_newtype_struct<D>(self, deserializer: D) -> Result<Self::Value, D::Error>
945            where
946                D: serde::de::Deserializer<'de>,
947            {
948                // Anchor context is established by de.rs when the special name is used.
949                let id = anchor_store::current_rc_anchor().ok_or_else(|| {
950                    D::Error::custom(
951                        "weak Rc anchor must refer to an existing strong anchor via alias",
952                    )
953                })?;
954                // Consume and ignore the inner node to keep the stream in sync (alias replay injects the full target node).
955                let _ =
956                    <serde::de::IgnoredAny as serde::de::Deserialize>::deserialize(deserializer)?;
957                // Look up the strong reference by id and downgrade.
958                match anchor_store::get_rc::<T>(id).map_err(D::Error::custom)? {
959                    Some(rc) => Ok(RcWeakAnchor(Rc::downgrade(&rc))),
960                    None if anchor_store::rc_anchor_reentrant(id) => {
961                        Err(D::Error::custom("Recursive references require RcRecursion"))
962                    }
963                    None => Err(D::Error::custom(
964                        "weak Rc anchor refers to unknown anchor; strong anchor must be defined before weak",
965                    )),
966                }
967            }
968        }
969        deserializer.deserialize_newtype_struct("__yaml_rc_weak_anchor", RcWeakVisitor(PhantomData))
970    }
971}
972
973impl<'de, T> serde::de::Deserialize<'de> for ArcWeakAnchor<T>
974where
975    T: serde::de::Deserialize<'de> + Send + Sync + 'static,
976{
977    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
978    where
979        D: serde::de::Deserializer<'de>,
980    {
981        struct ArcWeakVisitor<T>(PhantomData<T>);
982        impl<'de, T> Visitor<'de> for ArcWeakVisitor<T>
983        where
984            T: serde::de::Deserialize<'de> + Send + Sync + 'static,
985        {
986            type Value = ArcWeakAnchor<T>;
987            fn expecting(&self, f: &mut fmt::Formatter) -> fmt::Result {
988                f.write_str(
989                    "an ArcWeakAnchor referring to a previously defined strong anchor (via alias)",
990                )
991            }
992            fn visit_newtype_struct<D>(self, deserializer: D) -> Result<Self::Value, D::Error>
993            where
994                D: serde::de::Deserializer<'de>,
995            {
996                let id = anchor_store::current_arc_anchor().ok_or_else(|| {
997                    D::Error::custom(
998                        "weak Arc anchor must refer to an existing strong anchor via alias",
999                    )
1000                })?;
1001                // Consume and ignore the inner node (alias replay injects the target node events).
1002                let _ =
1003                    <serde::de::IgnoredAny as serde::de::Deserialize>::deserialize(deserializer)?;
1004                match anchor_store::get_arc::<T>(id).map_err(D::Error::custom)? {
1005                    Some(arc) => Ok(ArcWeakAnchor(Arc::downgrade(&arc))),
1006                    None if anchor_store::arc_anchor_reentrant(id) => Err(D::Error::custom(
1007                        "Recursive references require ArcRecursion",
1008                    )),
1009                    None => Err(D::Error::custom(
1010                        "weak Arc anchor refers to unknown anchor; strong anchor must be defined before weak",
1011                    )),
1012                }
1013            }
1014        }
1015        deserializer
1016            .deserialize_newtype_struct("__yaml_arc_weak_anchor", ArcWeakVisitor(PhantomData))
1017    }
1018}
1019
1020impl<'de, T> serde::de::Deserialize<'de> for RcRecursion<T>
1021where
1022    T: serde::de::Deserialize<'de> + 'static,
1023{
1024    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
1025    where
1026        D: serde::de::Deserializer<'de>,
1027    {
1028        struct RcRecursionVisitor<T>(PhantomData<T>);
1029        impl<'de, T> Visitor<'de> for RcRecursionVisitor<T>
1030        where
1031            T: serde::de::Deserialize<'de> + 'static,
1032        {
1033            type Value = RcRecursion<T>;
1034            fn expecting(&self, f: &mut fmt::Formatter) -> fmt::Result {
1035                f.write_str(
1036                    "an RcRecursion referring to a previously defined recursive strong anchor (via alias)",
1037                )
1038            }
1039            fn visit_newtype_struct<D>(self, deserializer: D) -> Result<Self::Value, D::Error>
1040            where
1041                D: serde::de::Deserializer<'de>,
1042            {
1043                let id = anchor_store::current_rc_recursive_anchor().ok_or_else(|| {
1044                    D::Error::custom(
1045                        "RcRecursion must refer to an existing recursive strong anchor via alias",
1046                    )
1047                })?;
1048                let _ =
1049                    <serde::de::IgnoredAny as serde::de::Deserialize>::deserialize(deserializer)?;
1050                match anchor_store::get_rc_recursive::<RefCell<Option<T>>>(id)
1051                    .map_err(D::Error::custom)?
1052                {
1053                    Some(rc) => Ok(RcRecursion(Rc::downgrade(&rc))),
1054                    None => Err(D::Error::custom(
1055                        "RcRecursion refers to unknown recursive anchor id",
1056                    )),
1057                }
1058            }
1059        }
1060        deserializer
1061            .deserialize_newtype_struct("__yaml_rc_recursion", RcRecursionVisitor(PhantomData))
1062    }
1063}
1064
1065impl<'de, T> serde::de::Deserialize<'de> for ArcRecursion<T>
1066where
1067    T: serde::de::Deserialize<'de> + Send + Sync + 'static,
1068{
1069    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
1070    where
1071        D: serde::de::Deserializer<'de>,
1072    {
1073        struct ArcRecursionVisitor<T>(PhantomData<T>);
1074        impl<'de, T> Visitor<'de> for ArcRecursionVisitor<T>
1075        where
1076            T: serde::de::Deserialize<'de> + Send + Sync + 'static,
1077        {
1078            type Value = ArcRecursion<T>;
1079            fn expecting(&self, f: &mut fmt::Formatter) -> fmt::Result {
1080                f.write_str(
1081                    "an ArcRecursion referring to a previously defined recursive strong anchor (via alias)",
1082                )
1083            }
1084            fn visit_newtype_struct<D>(self, deserializer: D) -> Result<Self::Value, D::Error>
1085            where
1086                D: serde::de::Deserializer<'de>,
1087            {
1088                let id = anchor_store::current_arc_recursive_anchor().ok_or_else(|| {
1089                    D::Error::custom(
1090                        "ArcRecursion must refer to an existing recursive strong anchor via alias",
1091                    )
1092                })?;
1093                let _ =
1094                    <serde::de::IgnoredAny as serde::de::Deserialize>::deserialize(deserializer)?;
1095                match anchor_store::get_arc_recursive::<Mutex<Option<T>>>(id)
1096                    .map_err(D::Error::custom)?
1097                {
1098                    Some(arc) => Ok(ArcRecursion(Arc::downgrade(&arc))),
1099                    None => Err(D::Error::custom(
1100                        "ArcRecursion refers to unknown recursive anchor id",
1101                    )),
1102                }
1103            }
1104        }
1105        deserializer
1106            .deserialize_newtype_struct("__yaml_arc_recursion", ArcRecursionVisitor(PhantomData))
1107    }
1108}