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
use cfg_if::cfg_if;
use core::fmt;
use crate::id::{Id, IdHash};
use crate::CanonError;
cfg_if! {
if #[cfg(target_arch = "wasm32")] {
mod bridge;
use bridge::BridgeStore as Inner;
} else {
mod host;
use host::HostStore as Inner;
}
}
pub struct Store;
impl Store {
pub fn put(bytes: &[u8]) -> IdHash {
Inner::put(bytes)
}
pub fn get(hash: &IdHash, write_to: &mut [u8]) -> Result<(), CanonError> {
Inner::get(hash, write_to)
}
pub fn hash(bytes: &[u8]) -> IdHash {
Inner::hash(bytes)
}
pub(crate) fn take_bytes(id: &Id) -> Result<Vec<u8>, CanonError> {
Inner::take_bytes(id)
}
}
pub struct Sink<'a> {
bytes: &'a mut [u8],
offset: usize,
}
impl<'a> fmt::Debug for Sink<'a> {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "Sink {:?}", &self.bytes[0..self.offset])
}
}
impl<'a> Sink<'a> {
pub fn new(bytes: &'a mut [u8]) -> Self {
Sink { bytes, offset: 0 }
}
pub fn copy_bytes(&mut self, bytes: &[u8]) {
let len = bytes.len();
self.bytes[self.offset..self.offset + len].copy_from_slice(bytes);
self.offset += len;
}
}
pub struct Source<'a> {
pub(crate) bytes: &'a [u8],
pub(crate) offset: usize,
}
impl<'a> Source<'a> {
pub fn new(bytes: &'a [u8]) -> Self {
Source { bytes, offset: 0 }
}
pub fn read_bytes(&mut self, n: usize) -> &[u8] {
let old_offset = self.offset;
self.offset += n;
&self.bytes[old_offset..old_offset + n]
}
}