Skip to main content

valence_core/
reference.rs

1//! Reference placeholders for batch entity creation.
2
3use std::sync::{Arc, Mutex};
4
5use crate::RecordId;
6use uuid::Uuid;
7
8#[derive(Clone, Debug)]
9pub struct Reference<T> {
10    id: String,
11    resolved: Arc<Mutex<Option<RecordId>>>,
12    _phantom: std::marker::PhantomData<T>,
13}
14
15impl<T> Reference<T> {
16    pub fn new() -> Self {
17        Self {
18            id: format!("ref_{}", Uuid::new_v4()),
19            resolved: Arc::new(Mutex::new(None)),
20            _phantom: std::marker::PhantomData,
21        }
22    }
23
24    pub fn id(&self) -> &str {
25        &self.id
26    }
27
28    pub fn resolve(&self) -> Option<RecordId> {
29        self.resolved.lock().unwrap().clone()
30    }
31
32    /// Store the resolved record id for this placeholder reference.
33    pub fn resolve_to(&self, id: RecordId) {
34        *self.resolved.lock().unwrap() = Some(id);
35    }
36
37    pub fn is_resolved(&self) -> bool {
38        self.resolved.lock().unwrap().is_some()
39    }
40}
41
42impl<T> Default for Reference<T> {
43    fn default() -> Self {
44        Self::new()
45    }
46}
47
48pub trait WithReference: Sized {
49    fn with_reference(self, reference: Reference<Self>) -> ReferencedEntity<Self> {
50        ReferencedEntity {
51            reference,
52            entity: self,
53        }
54    }
55}
56
57pub struct ReferencedEntity<T> {
58    pub(crate) reference: Reference<T>,
59    pub(crate) entity: T,
60}
61
62impl<T> ReferencedEntity<T> {
63    pub fn new(reference: Reference<T>, entity: T) -> Self {
64        Self { reference, entity }
65    }
66
67    pub fn reference(&self) -> &Reference<T> {
68        &self.reference
69    }
70
71    pub fn entity(&self) -> &T {
72        &self.entity
73    }
74
75    pub fn into_entity(self) -> T {
76        self.entity
77    }
78}