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
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
use std::{borrow::Cow, ops::Deref};

use rkyv::{
    rancor::Fallible,
    ser::{Allocator, WriterExt},
    vec::{ArchivedVec, VecResolver},
    Archive, Archived,
};

#[derive(Clone)]
pub struct AlignedCowStr<'a> {
    inner: Cow<'a, str>,
}

impl<'a> AlignedCowStr<'a> {
    pub const ALIGNMENT: usize = 16;

    pub fn into_inner(self) -> Cow<'a, str> {
        self.inner
    }

    #[inline]
    pub fn as_slice(&self) -> &str {
        self.inner.as_ref()
    }

    pub fn len(&self) -> usize {
        self.inner.len()
    }

    pub fn is_empty(&self) -> bool {
        self.inner.is_empty()
    }
}

impl<'a> Default for AlignedCowStr<'a> {
    fn default() -> Self {
        Self {
            inner: String::new().into(),
        }
    }
}

impl<'a> std::fmt::Debug for AlignedCowStr<'a> {
    #[inline]
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        self.inner.fmt(f)
    }
}

impl<'a> From<String> for AlignedCowStr<'a> {
    fn from(value: String) -> Self {
        Self {
            inner: value.into(),
        }
    }
}

#[allow(clippy::from_over_into)]
impl<'a> Into<String> for AlignedCowStr<'a> {
    fn into(self) -> String {
        self.inner.into_owned()
    }
}

impl<'a> From<Cow<'a, str>> for AlignedCowStr<'a> {
    fn from(value: Cow<'a, str>) -> Self {
        Self { inner: value }
    }
}

#[allow(clippy::from_over_into)]
impl<'a> Into<Cow<'a, str>> for AlignedCowStr<'a> {
    fn into(self) -> Cow<'a, str> {
        self.inner
    }
}

impl<'a> Deref for AlignedCowStr<'a> {
    type Target = str;

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

impl<'a> AsRef<str> for AlignedCowStr<'a> {
    #[inline]
    fn as_ref(&self) -> &str {
        self.inner.as_ref()
    }
}

impl<'a> Archive for AlignedCowStr<'a> {
    type Archived = ArchivedVec<u8>;
    type Resolver = VecResolver;

    #[inline]
    fn resolve(&self, resolver: Self::Resolver, out: rkyv::Place<Self::Archived>) {
        ArchivedVec::resolve_from_len(self.inner.as_bytes().len(), resolver, out);
    }
}

impl<'a, S> rkyv::Serialize<S> for AlignedCowStr<'a>
where
    S: Fallible + WriterExt<S::Error> + Allocator + ?Sized,
    S::Error: rkyv::rancor::Source,
{
    #[inline]
    fn serialize(&self, serializer: &mut S) -> Result<Self::Resolver, S::Error> {
        serializer.align(Self::ALIGNMENT)?;
        ArchivedVec::<Archived<u8>>::serialize_from_slice(self.inner.as_bytes(), serializer)
    }
}