rkyv/impls/alloc/
string.rs

1use core::cmp::Ordering;
2
3use rancor::{Fallible, Source};
4
5use crate::{
6    alloc::string::{String, ToString},
7    string::{ArchivedString, StringResolver},
8    Archive, Deserialize, DeserializeUnsized, Place, Serialize,
9    SerializeUnsized,
10};
11
12impl Archive for String {
13    type Archived = ArchivedString;
14    type Resolver = StringResolver;
15
16    #[inline]
17    fn resolve(&self, resolver: Self::Resolver, out: Place<Self::Archived>) {
18        ArchivedString::resolve_from_str(self.as_str(), resolver, out);
19    }
20}
21
22impl<S: Fallible + ?Sized> Serialize<S> for String
23where
24    S::Error: Source,
25    str: SerializeUnsized<S>,
26{
27    fn serialize(
28        &self,
29        serializer: &mut S,
30    ) -> Result<Self::Resolver, S::Error> {
31        ArchivedString::serialize_from_str(self.as_str(), serializer)
32    }
33}
34
35impl<D: Fallible + ?Sized> Deserialize<String, D> for ArchivedString
36where
37    str: DeserializeUnsized<str, D>,
38{
39    fn deserialize(&self, _: &mut D) -> Result<String, D::Error> {
40        Ok(self.as_str().to_string())
41    }
42}
43
44impl PartialEq<String> for ArchivedString {
45    #[inline]
46    fn eq(&self, other: &String) -> bool {
47        PartialEq::eq(self.as_str(), other.as_str())
48    }
49}
50
51impl PartialEq<ArchivedString> for String {
52    #[inline]
53    fn eq(&self, other: &ArchivedString) -> bool {
54        PartialEq::eq(other.as_str(), self.as_str())
55    }
56}
57
58impl PartialOrd<String> for ArchivedString {
59    #[inline]
60    fn partial_cmp(&self, other: &String) -> Option<Ordering> {
61        self.as_str().partial_cmp(other.as_str())
62    }
63}
64
65impl PartialOrd<ArchivedString> for String {
66    #[inline]
67    fn partial_cmp(&self, other: &ArchivedString) -> Option<Ordering> {
68        self.as_str().partial_cmp(other.as_str())
69    }
70}
71
72#[cfg(test)]
73mod tests {
74    use crate::{alloc::string::ToString, api::test::roundtrip};
75
76    #[test]
77    fn roundtrip_string() {
78        roundtrip(&"".to_string());
79        roundtrip(&"hello world".to_string());
80    }
81
82    #[test]
83    fn roundtrip_option_string() {
84        roundtrip(&Some("".to_string()));
85        roundtrip(&Some("hello world".to_string()));
86    }
87
88    #[test]
89    fn roundtrip_result_string() {
90        roundtrip(&Ok::<_, ()>("".to_string()));
91        roundtrip(&Ok::<_, ()>("hello world".to_string()));
92
93        roundtrip(&Err::<(), _>("".to_string()));
94        roundtrip(&Err::<(), _>("hello world".to_string()));
95    }
96}