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
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
//! Batch operation types.
use crate::{CollectionName, Key, Namespace, StoredValue};
/// A single batch operation.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum BatchOperation {
/// Set a stored value.
Set {
/// Target namespace.
namespace: Namespace,
/// Target collection.
collection: CollectionName,
/// Target key.
key: Key,
/// Value to store.
value: StoredValue,
},
/// Delete a stored value.
Delete {
/// Target namespace.
namespace: Namespace,
/// Target collection.
collection: CollectionName,
/// Target key.
key: Key,
},
}
impl BatchOperation {
/// Creates a set operation.
#[must_use]
pub fn set(
namespace: Namespace,
collection: CollectionName,
key: Key,
value: StoredValue,
) -> Self {
Self::Set {
namespace,
collection,
key,
value,
}
}
/// Creates a delete operation.
#[must_use]
pub fn delete(namespace: Namespace, collection: CollectionName, key: Key) -> Self {
Self::Delete {
namespace,
collection,
key,
}
}
}
/// Ordered batch of write operations.
#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub struct Batch {
operations: Vec<BatchOperation>,
}
impl Batch {
/// Creates an empty batch.
#[must_use]
pub fn new() -> Self {
Self::default()
}
/// Adds an operation to the batch.
pub fn push(&mut self, operation: BatchOperation) {
self.operations.push(operation);
}
/// Adds an operation and returns the batch for chaining.
#[must_use]
pub fn with_operation(mut self, operation: BatchOperation) -> Self {
self.push(operation);
self
}
/// Returns all operations.
#[must_use]
pub fn operations(&self) -> &[BatchOperation] {
&self.operations
}
/// Consumes the batch and returns the operations.
#[must_use]
pub fn into_operations(self) -> Vec<BatchOperation> {
self.operations
}
/// Returns true when the batch has no operations.
#[must_use]
pub fn is_empty(&self) -> bool {
self.operations.is_empty()
}
/// Returns the number of operations.
#[must_use]
pub fn len(&self) -> usize {
self.operations.len()
}
}
/// Summary returned after a batch write.
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
pub struct BatchResult {
/// Number of set operations applied.
pub set_count: usize,
/// Number of delete operations applied.
pub delete_count: usize,
}
impl BatchResult {
/// Creates a batch result.
#[must_use]
pub const fn new(set_count: usize, delete_count: usize) -> Self {
Self {
set_count,
delete_count,
}
}
/// Returns the total number of affected operations.
#[must_use]
pub const fn total_count(self) -> usize {
self.set_count + self.delete_count
}
}