1use crate::{
3 commit::{CommitHash, CommitProof},
4 events::{AccountEvent, DeviceEvent, EventRecord, WriteEvent},
5 Result,
6};
7use binary_stream::futures::{Decodable, Encodable};
8use std::marker::PhantomData;
9
10#[cfg(feature = "files")]
11use crate::events::FileEvent;
12
13pub type AccountPatch = Patch<AccountEvent>;
15
16pub type FolderPatch = Patch<WriteEvent>;
18
19pub type DevicePatch = Patch<DeviceEvent>;
21
22#[cfg(feature = "files")]
24pub type FilePatch = Patch<FileEvent>;
25
26#[derive(Clone, Debug, Default, Eq, PartialEq)]
28pub struct Patch<T>(Vec<EventRecord>, PhantomData<T>);
29
30impl<T> Patch<T> {
31 pub fn new(records: Vec<EventRecord>) -> Self {
33 Self(records, PhantomData)
34 }
35
36 pub fn len(&self) -> usize {
38 self.0.len()
39 }
40
41 pub fn is_empty(&self) -> bool {
43 self.0.is_empty()
44 }
45
46 pub fn iter(&self) -> impl Iterator<Item = &EventRecord> {
48 self.0.iter()
49 }
50
51 pub fn records(&self) -> &[EventRecord] {
53 self.0.as_slice()
54 }
55
56 pub async fn into_events<E: Default + Decodable + Encodable>(
58 &self,
59 ) -> Result<Vec<E>> {
60 let mut events = Vec::with_capacity(self.0.len());
61 for record in &self.0 {
62 events.push(record.decode_event::<E>().await?);
63 }
64 Ok(events)
65 }
66}
67
68impl<T> From<Patch<T>> for Vec<EventRecord> {
69 fn from(value: Patch<T>) -> Self {
70 value.0
71 }
72}
73
74#[derive(Debug, Clone, PartialEq, Eq)]
76pub enum CheckedPatch {
77 Success(CommitProof),
79 Conflict {
81 head: CommitProof,
83 contains: Option<CommitProof>,
86 },
87}
88
89#[derive(Default, Debug, Clone, PartialEq, Eq)]
91pub struct Diff<T> {
92 pub patch: Patch<T>,
94 pub checkpoint: CommitProof,
103 pub last_commit: Option<CommitHash>,
112}
113
114impl<T> Diff<T> {
115 pub fn new(
117 patch: Patch<T>,
118 checkpoint: CommitProof,
119 last_commit: Option<CommitHash>,
120 ) -> Self {
121 Self {
122 patch,
123 checkpoint,
124 last_commit,
125 }
126 }
127}
128
129pub type AccountDiff = Diff<AccountEvent>;
131
132pub type DeviceDiff = Diff<DeviceEvent>;
134
135#[cfg(feature = "files")]
137pub type FileDiff = Diff<FileEvent>;
138
139pub type FolderDiff = Diff<WriteEvent>;