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
use crate::{utils::wrap_err, TinkError};
use std::io::{Read, Write};
pub struct BinaryReader<T: Read> {
r: T,
}
impl<T: Read> BinaryReader<T> {
pub fn new(r: T) -> Self {
BinaryReader { r }
}
}
impl<T: Read> super::Reader for BinaryReader<T> {
fn read(&mut self) -> Result<tink_proto::Keyset, TinkError> {
read::<tink_proto::Keyset>(&mut self.r)
}
fn read_encrypted(&mut self) -> Result<tink_proto::EncryptedKeyset, TinkError> {
read::<tink_proto::EncryptedKeyset>(&mut self.r)
}
}
fn read<T>(r: &mut dyn Read) -> Result<T, TinkError>
where
T: prost::Message + std::default::Default,
{
let mut data = vec![];
r.read_to_end(&mut data)
.map_err(|e| wrap_err("read failed", e))?;
match T::decode(data.as_ref()) {
Ok(msg) => Ok(msg),
Err(e) => Err(wrap_err("decode failed", e)),
}
}
pub struct BinaryWriter<T: Write> {
w: T,
}
impl<T: Write> BinaryWriter<T> {
pub fn new(w: T) -> Self {
BinaryWriter { w }
}
}
impl<T: Write> super::Writer for BinaryWriter<T> {
fn write(&mut self, keyset: &tink_proto::Keyset) -> Result<(), TinkError> {
write(&mut self.w, keyset)
}
fn write_encrypted(&mut self, keyset: &tink_proto::EncryptedKeyset) -> Result<(), TinkError> {
write(&mut self.w, keyset)
}
}
fn write<T>(w: &mut dyn Write, msg: &T) -> Result<(), TinkError>
where
T: prost::Message,
{
let mut data = vec![];
match msg.encode(&mut data) {
Ok(()) => Ok(()),
Err(e) => Err(wrap_err("encode failed", e)),
}?;
match w.write(&data) {
Ok(_size) => Ok(()),
Err(e) => Err(wrap_err("write failed", e)),
}
}