Skip to main content

decl_lang/semantics/
shared_text.rs

1//! Thin immutable text handles with explicit sharing across path boundaries.
2
3use std::borrow::Borrow;
4use std::fmt;
5use std::ops::Deref;
6use std::rc::Rc;
7
8/// Shared UTF-8 text held through a thin descriptor.
9///
10/// Value clones share the descriptor. Paths can retain the inner `Rc<str>`
11/// without copying characters; its strong count does not count each descriptor
12/// clone separately. Equality, ordering and hashing compare text, not owners.
13#[derive(Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
14pub struct SharedText(Rc<Rc<str>>);
15
16impl SharedText {
17    /// Retain an existing character allocation in a new shared descriptor.
18    pub fn from_rc(text: Rc<str>) -> Self {
19        Self(Rc::new(text))
20    }
21
22    /// Borrow the character owner without changing either reference count.
23    pub fn as_rc(&self) -> &Rc<str> {
24        &self.0
25    }
26
27    /// Retain the character allocation independently of this descriptor.
28    pub fn to_rc(&self) -> Rc<str> {
29        self.as_rc().clone()
30    }
31
32    /// Move out a unique descriptor's character owner, or retain a shared one.
33    pub fn into_rc(self) -> Rc<str> {
34        Rc::unwrap_or_clone(self.0)
35    }
36
37    /// Mutate text without changing retained descriptors or exported owners.
38    /// Both sharing levels use copy-on-write, including weak-only dissociation.
39    pub fn make_mut(&mut self) -> &mut str {
40        Rc::make_mut(Rc::make_mut(&mut self.0))
41    }
42}
43
44impl From<Rc<str>> for SharedText {
45    fn from(text: Rc<str>) -> Self {
46        Self::from_rc(text)
47    }
48}
49
50impl From<&str> for SharedText {
51    fn from(text: &str) -> Self {
52        Self::from_rc(Rc::from(text))
53    }
54}
55
56impl From<String> for SharedText {
57    fn from(text: String) -> Self {
58        Self::from_rc(Rc::from(text))
59    }
60}
61
62impl Deref for SharedText {
63    type Target = str;
64
65    fn deref(&self) -> &str {
66        self.as_rc()
67    }
68}
69
70impl AsRef<str> for SharedText {
71    fn as_ref(&self) -> &str {
72        self
73    }
74}
75
76impl Borrow<str> for SharedText {
77    fn borrow(&self) -> &str {
78        self
79    }
80}
81
82impl fmt::Display for SharedText {
83    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
84        fmt::Display::fmt(self.as_ref(), f)
85    }
86}
87
88impl fmt::Debug for SharedText {
89    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
90        fmt::Debug::fmt(self.as_ref(), f)
91    }
92}