1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
use std::fmt;
use std::ops::Deref;

use arc_swap::{ArcSwapAny, Guard};
use triomphe::Arc;

/// A thread-safe atomically reference-counting string.
pub struct AtomicStr(ArcSwapAny<Arc<String>>);

/// A thread-safe view the string that was stored when `AtomicStr::as_str()` was called.
struct GuardedStr(Guard<Arc<String>>);

impl Deref for GuardedStr {
    type Target = str;

    fn deref(&self) -> &Self::Target {
        self.0.as_str()
    }
}

impl AtomicStr {
    /// Create a new `AtomicStr` with the given value.
    pub fn new(value: &str) -> Self {
        let arced = Arc::new(value.into());
        Self(ArcSwapAny::new(arced))
    }

    /// Get the string slice.
    pub fn as_str(&self) -> impl Deref<Target = str> {
        GuardedStr(self.0.load())
    }

    /// Replaces the value at self with src.
    pub fn replace(&self, src: impl Into<String>) {
        let arced = Arc::new(src.into());
        self.0.store(arced);
    }
}

impl From<&str> for AtomicStr {
    fn from(value: &str) -> Self {
        Self::new(value)
    }
}

impl fmt::Display for AtomicStr {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.write_str(&self.as_str())
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    fn test_str(s: &str) {
        assert_eq!(s, "hello");
    }

    #[test]
    fn test_atomic_str() {
        let s = AtomicStr::from("hello");
        test_str(&s.as_str());
    }
}