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
133
134
135
use std::{hash::Hash, io::{Cursor, Seek, SeekFrom, Read}};
use crate::{Contains, OverlayError, SolidPatch};
pub struct Patch {
offset: u64,
content: Vec<u8>,
}
impl Patch {
pub fn id(&self) -> u128 {
let offset = (self.offset as u128) << 64;
let len = TryInto::<u128>::try_into(self.content.len()).unwrap();
offset | len
}
pub fn begin(&self) -> u64 {
self.offset
}
pub fn end(&self) -> u64 {
self.offset + TryInto::<u64>::try_into(self.content.len()).unwrap()
}
pub fn first_byte_offset(&self) -> u64 {
self.offset
}
pub fn last_byte_offset(&self) -> u64 {
assert!(! self.content.is_empty());
self.offset + TryInto::<u64>::try_into(self.content.len() - 1).unwrap()
}
pub fn overlaps(&self, other: &Self) -> bool {
other.contains(self.first_byte_offset()) || self.contains(other.first_byte_offset())
}
pub fn read(&self, offset: u64, buf: &mut [u8]) -> std::io::Result<usize> {
let mut cursor = Cursor::new(&self.content);
cursor.seek(SeekFrom::Start(offset))?;
cursor.read(buf)
}
}
impl Hash for Patch {
fn hash<H: std::hash::Hasher>(&self, state: &mut H) {
self.id().hash(state);
}
}
impl PartialEq for Patch {
fn eq(&self, other: &Self) -> bool {
self.id() == other.id()
}
}
impl PartialOrd for Patch {
fn partial_cmp(&self, other: &Self) -> Option<std::cmp::Ordering> {
self.id().partial_cmp(&other.id())
}
}
impl Ord for Patch {
fn cmp(&self, other: &Self) -> std::cmp::Ordering {
self.id().cmp(&other.id())
}
}
impl Eq for Patch {}
impl Contains for Patch {
fn contains(&self, offset: u64) -> bool {
self.begin() <= offset && offset < self.end()
}
}
impl SolidPatch<&[u8]> for Patch {
fn new(offset: u64, content: &[u8]) -> Result<Self, OverlayError> {
if content.is_empty() {
Err(OverlayError::EmptyPatch)
} else {
Ok(Self {
offset,
content: Vec::from(content),
})
}
}
}
impl SolidPatch<Vec<u8>> for Patch {
fn new(offset: u64, content: Vec<u8>) -> Result<Self, OverlayError> {
if content.is_empty() {
Err(OverlayError::EmptyPatch)
} else {
Ok(Self { offset, content })
}
}
}