1
use std::borrow::Cow;
2

            
3
use arc_bytes::serde::{Bytes, CowBytes};
4
use serde::{Deserialize, Serialize};
5

            
6
use crate::schema::{Collection, SerializedCollection};
7

            
8
mod collection;
9
mod header;
10
mod id;
11
mod revision;
12
pub use self::{
13
    collection::{CollectionDocument, OwnedDocuments},
14
    header::{AnyHeader, CollectionHeader, Emit, HasHeader, Header},
15
    id::{AnyDocumentId, DocumentId, InvalidHexadecimal},
16
    revision::Revision,
17
};
18
/// Contains a serialized document in the database.
19
4092856
#[derive(Clone, Debug, Serialize, Deserialize)]
20
pub struct BorrowedDocument<'a> {
21
    /// The header of the document, which contains the id and `Revision`.
22
    pub header: Header,
23

            
24
    /// The serialized bytes of the stored item.
25
    #[serde(borrow)]
26
    pub contents: CowBytes<'a>,
27
}
28

            
29
/// Contains a serialized document in the database.
30
22496
#[derive(Clone, Debug, Serialize, Deserialize)]
31
pub struct OwnedDocument {
32
    /// The header of the document, which contains the id and `Revision`.
33
    pub header: Header,
34

            
35
    /// The serialized bytes of the stored item.
36
    pub contents: Bytes,
37
}
38

            
39
/// Common interface of a document in BonsaiDb.
40
pub trait Document<C>: Sized
41
where
42
    C: Collection,
43
{
44
    /// The bytes type used in the interface.
45
    type Bytes;
46

            
47
    /// Returns the unique key for this document.
48
    fn key(&self) -> AnyDocumentId<C::PrimaryKey>;
49
    /// Returns the header of this document.
50
    fn header(&self) -> AnyHeader<C::PrimaryKey>;
51
    /// Sets the header to the new header.
52
    fn set_header(&mut self, header: Header) -> Result<(), crate::Error>;
53
    /// Sets the header to the new collection header.
54
    fn set_collection_header(
55
        &mut self,
56
        header: CollectionHeader<C::PrimaryKey>,
57
    ) -> Result<(), crate::Error> {
58
5
        self.set_header(Header::try_from(header)?)
59
5
    }
60
    /// Returns the contents of this document, serialized.
61
    fn bytes(&self) -> Result<Vec<u8>, crate::Error>;
62
    /// Retrieves `contents` through deserialization into the type `D`.
63
    fn contents(&self) -> Result<C::Contents, crate::Error>
64
    where
65
        C: SerializedCollection;
66
    /// Stores `contents` into this document.
67
    fn set_contents(&mut self, contents: C::Contents) -> Result<(), crate::Error>
68
    where
69
        C: SerializedCollection;
70
}
71

            
72
impl<'a> AsRef<[u8]> for BorrowedDocument<'a> {
73
    fn as_ref(&self) -> &[u8] {
74
        &self.contents
75
    }
76
}
77

            
78
impl<'a, C> Document<C> for BorrowedDocument<'a>
79
where
80
    C: Collection,
81
{
82
    type Bytes = CowBytes<'a>;
83

            
84
3591
    fn contents(&self) -> Result<C::Contents, crate::Error>
85
3591
    where
86
3591
        C: SerializedCollection,
87
3591
    {
88
3591
        <C as SerializedCollection>::deserialize(&self.contents)
89
3591
    }
90

            
91
    fn set_contents(&mut self, contents: C::Contents) -> Result<(), crate::Error>
92
    where
93
        C: SerializedCollection,
94
    {
95
        self.contents = CowBytes::from(<C as SerializedCollection>::serialize(&contents)?);
96
        Ok(())
97
    }
98

            
99
5
    fn header(&self) -> AnyHeader<C::PrimaryKey> {
100
5
        AnyHeader::Serialized(self.header.clone())
101
5
    }
102

            
103
    fn set_header(&mut self, header: Header) -> Result<(), crate::Error> {
104
        self.header = header;
105
        Ok(())
106
    }
107

            
108
5
    fn bytes(&self) -> Result<Vec<u8>, crate::Error> {
109
5
        Ok(self.contents.to_vec())
110
5
    }
111

            
112
    fn key(&self) -> AnyDocumentId<C::PrimaryKey> {
113
        AnyDocumentId::Serialized(self.header.id)
114
    }
115
}
116

            
117
impl<'a, C> Document<C> for OwnedDocument
118
where
119
    C: Collection,
120
{
121
    type Bytes = Vec<u8>;
122

            
123
1030
    fn contents(&self) -> Result<C::Contents, crate::Error>
124
1030
    where
125
1030
        C: SerializedCollection,
126
1030
    {
127
1030
        <C as SerializedCollection>::deserialize(&self.contents)
128
1030
    }
129

            
130
521
    fn set_contents(&mut self, contents: C::Contents) -> Result<(), crate::Error>
131
521
    where
132
521
        C: SerializedCollection,
133
521
    {
134
521
        self.contents = Bytes::from(<C as SerializedCollection>::serialize(&contents)?);
135
521
        Ok(())
136
521
    }
137

            
138
5
    fn key(&self) -> AnyDocumentId<C::PrimaryKey> {
139
5
        AnyDocumentId::Serialized(self.header.id)
140
5
    }
141

            
142
4923
    fn header(&self) -> AnyHeader<C::PrimaryKey> {
143
4923
        AnyHeader::Serialized(self.header.clone())
144
4923
    }
145

            
146
4913
    fn set_header(&mut self, header: Header) -> Result<(), crate::Error> {
147
4913
        self.header = header;
148
4913
        Ok(())
149
4913
    }
150

            
151
4928
    fn bytes(&self) -> Result<Vec<u8>, crate::Error> {
152
4928
        Ok(self.contents.to_vec())
153
4928
    }
154
}
155

            
156
impl AsRef<Header> for OwnedDocument {
157
    fn as_ref(&self) -> &Header {
158
        &self.header
159
    }
160
}
161

            
162
impl AsMut<Header> for OwnedDocument {
163
    fn as_mut(&mut self) -> &mut Header {
164
        &mut self.header
165
    }
166
}
167

            
168
impl AsRef<[u8]> for OwnedDocument {
169
    fn as_ref(&self) -> &[u8] {
170
        &self.contents
171
    }
172
}
173

            
174
impl<'a> BorrowedDocument<'a> {
175
    /// Returns a new instance with the id and content bytes.
176
422464
    pub fn new<Contents: Into<CowBytes<'a>>>(id: DocumentId, contents: Contents) -> Self {
177
422464
        let contents = contents.into();
178
422464
        let revision = Revision::new(&contents);
179
422464
        Self {
180
422464
            header: Header { id, revision },
181
422464
            contents,
182
422464
        }
183
422464
    }
184

            
185
    /// Returns a new instance with `contents`, after serializing.
186
513
    pub fn with_contents<C>(id: C::PrimaryKey, contents: &C::Contents) -> Result<Self, crate::Error>
187
513
    where
188
513
        C: SerializedCollection,
189
513
    {
190
513
        let contents = <C as SerializedCollection>::serialize(contents)?;
191
513
        Ok(Self::new(DocumentId::new(id)?, contents))
192
513
    }
193

            
194
    /// Converts this document to an owned document.
195
    #[must_use]
196
550810
    pub fn into_owned(self) -> OwnedDocument {
197
550810
        OwnedDocument {
198
550810
            header: self.header,
199
550810
            contents: Bytes::from(self.contents),
200
550810
        }
201
550810
    }
202
}
203

            
204
impl<'a> AsRef<Header> for BorrowedDocument<'a> {
205
    fn as_ref(&self) -> &Header {
206
        &self.header
207
    }
208
}
209

            
210
impl<'a> AsMut<Header> for BorrowedDocument<'a> {
211
    fn as_mut(&mut self) -> &mut Header {
212
        &mut self.header
213
    }
214
}
215

            
216
/// The ID of an encryption key.
217
674158
#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq)]
218
pub enum KeyId {
219
    /// A key with no id.
220
    None,
221
    /// The master key of the vault.
222
    Master,
223
    /// A specific named key in the vault.
224
    Id(Cow<'static, str>),
225
}