wasmer_journal/concrete/
aligned_cow_str.rs1use std::{borrow::Cow, ops::Deref};
2
3use rkyv::{
4 rancor::Fallible,
5 ser::{Allocator, WriterExt},
6 vec::{ArchivedVec, VecResolver},
7 Archive, Archived,
8};
9
10#[derive(Clone)]
11pub struct AlignedCowStr<'a> {
12 inner: Cow<'a, str>,
13}
14
15impl<'a> AlignedCowStr<'a> {
16 pub const ALIGNMENT: usize = 16;
17
18 pub fn into_inner(self) -> Cow<'a, str> {
19 self.inner
20 }
21
22 #[inline]
23 pub fn as_slice(&self) -> &str {
24 self.inner.as_ref()
25 }
26
27 pub fn len(&self) -> usize {
28 self.inner.len()
29 }
30
31 pub fn is_empty(&self) -> bool {
32 self.inner.is_empty()
33 }
34}
35
36impl<'a> Default for AlignedCowStr<'a> {
37 fn default() -> Self {
38 Self {
39 inner: String::new().into(),
40 }
41 }
42}
43
44impl<'a> std::fmt::Debug for AlignedCowStr<'a> {
45 #[inline]
46 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
47 self.inner.fmt(f)
48 }
49}
50
51impl<'a> From<String> for AlignedCowStr<'a> {
52 fn from(value: String) -> Self {
53 Self {
54 inner: value.into(),
55 }
56 }
57}
58
59#[allow(clippy::from_over_into)]
60impl<'a> Into<String> for AlignedCowStr<'a> {
61 fn into(self) -> String {
62 self.inner.into_owned()
63 }
64}
65
66impl<'a> From<Cow<'a, str>> for AlignedCowStr<'a> {
67 fn from(value: Cow<'a, str>) -> Self {
68 Self { inner: value }
69 }
70}
71
72#[allow(clippy::from_over_into)]
73impl<'a> Into<Cow<'a, str>> for AlignedCowStr<'a> {
74 fn into(self) -> Cow<'a, str> {
75 self.inner
76 }
77}
78
79impl<'a> Deref for AlignedCowStr<'a> {
80 type Target = str;
81
82 fn deref(&self) -> &Self::Target {
83 self.inner.deref()
84 }
85}
86
87impl<'a> AsRef<str> for AlignedCowStr<'a> {
88 #[inline]
89 fn as_ref(&self) -> &str {
90 self.inner.as_ref()
91 }
92}
93
94impl<'a> Archive for AlignedCowStr<'a> {
95 type Archived = ArchivedVec<u8>;
96 type Resolver = VecResolver;
97
98 #[inline]
99 fn resolve(&self, resolver: Self::Resolver, out: rkyv::Place<Self::Archived>) {
100 ArchivedVec::resolve_from_len(self.inner.as_bytes().len(), resolver, out);
101 }
102}
103
104impl<'a, S> rkyv::Serialize<S> for AlignedCowStr<'a>
105where
106 S: Fallible + WriterExt<S::Error> + Allocator + ?Sized,
107 S::Error: rkyv::rancor::Source,
108{
109 #[inline]
110 fn serialize(&self, serializer: &mut S) -> Result<Self::Resolver, S::Error> {
111 serializer.align(Self::ALIGNMENT)?;
112 ArchivedVec::<Archived<u8>>::serialize_from_slice(self.inner.as_bytes(), serializer)
113 }
114}