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
use std::ops::{Deref, DerefMut};
use zeroize::Zeroize;
use crate::{CryptoError, CryptoResult};
mod read_locker;
pub use read_locker::ReadLocker;
mod write_locker;
pub use write_locker::WriteLocker;
mod buffer_vec_u8;
pub trait Buffer: Send + std::fmt::Debug + Deref<Target = [u8]> + DerefMut<Target = [u8]> {
fn box_clone(&self) -> Box<dyn Buffer>;
fn as_buffer(&self) -> &dyn Buffer;
fn as_buffer_mut(&mut self) -> &mut dyn Buffer;
fn len(&self) -> usize;
fn is_empty(&self) -> bool;
fn set_no_access(&self);
fn set_readable(&self);
fn set_writable(&self);
fn read_lock(&self) -> ReadLocker {
ReadLocker::new(self.as_buffer())
}
fn write_lock(&mut self) -> WriteLocker {
WriteLocker::new(self.as_buffer_mut())
}
fn zero(&mut self) {
self.write_lock().zeroize();
}
fn write(&mut self, offset: usize, data: &[u8]) -> CryptoResult<()> {
if offset + data.len() > self.len() {
return Err(CryptoError::WriteOverflow);
}
unsafe {
let mut b = self.write_lock();
std::ptr::copy(data.as_ptr(), (*b).as_mut_ptr().add(offset), data.len());
}
Ok(())
}
#[allow(clippy::borrowed_box)]
fn compare(&self, b: &Box<dyn Buffer>) -> i32 {
let a = self.read_lock();
let b = b.read_lock();
let al = self.len();
let bl = b.len();
for i in (0..al).rev() {
let av = a[i];
let bv = if i >= bl { 0 } else { b[i] };
if av > bv {
return 1;
} else if av < bv {
return -1;
};
}
return 0;
}
}
#[derive(Debug, Clone, PartialEq)]
pub enum ProtectState {
NoAccess,
ReadOnly,
ReadWrite,
}