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
136
137
138
use crate::storage::{
IntoInner,
PathGenerator,
PathGeneratorError,
StorageBackend,
};
#[derive(Debug, PartialEq)]
pub enum StorageState {
Open,
Closed,
}
#[derive(Debug, thiserror::Error)]
pub enum TarArchiveError {
#[error(transparent)]
IOError(#[from] std::io::Error),
#[error(transparent)]
PathGenerator(#[from] PathGeneratorError),
}
pub struct TarArchive<W: std::io::Write, G: PathGenerator> {
pub state: StorageState,
archive: tar::Builder<W>,
path_generator: G,
}
impl<W, G> TarArchive<W, G>
where
W: std::io::Write,
G: PathGenerator,
{
pub fn new(buffer: W, path_generator: G) -> Self {
Self {
archive: tar::Builder::new(buffer),
state: StorageState::Open,
path_generator,
}
}
pub fn get_mut(&mut self) -> &mut W {
self.archive.get_mut()
}
pub fn get_ref(&self) -> &W {
self.archive.get_ref()
}
}
impl<W, G> StorageBackend for TarArchive<W, G>
where
W: std::io::Write,
G: PathGenerator,
{
type Error = TarArchiveError;
fn append_file(&mut self, mfile: libatm::MIDIFile, mode: Option<u32>) -> Result<(), Self::Error> {
if self.state == StorageState::Closed {
return Err(TarArchiveError::IOError(std::io::Error::new(
std::io::ErrorKind::Other,
"Archive is closed for writing, cannot append file",
)));
}
let path = self.path_generator.gen_path_for_file(&mfile)?;
let mut header = tar::Header::new_old();
header.set_size(mfile.gen_size() as u64);
match mode {
Some(mode) => header.set_mode(mode),
None => header.set_mode(644),
}
let data = mfile.gen_file()?;
self
.archive
.append_data(&mut header, &path, data.as_slice())
.map_err(|e| TarArchiveError::IOError(e))
}
fn finish(&mut self) -> Result<(), Self::Error> {
match self.state {
StorageState::Open => {
self.state = StorageState::Closed;
self.archive.finish().map_err(|e| TarArchiveError::IOError(e))
},
_ => Ok(())
}
}
}
impl<W, G> IntoInner for TarArchive<W, G>
where
W: std::io::Write,
G: PathGenerator,
{
type Inner = W;
fn into_inner(mut self) -> Result<Self::Inner, <Self as StorageBackend>::Error> {
self.finish()?;
self.archive.into_inner().map_err(|e| TarArchiveError::IOError(e))
}
}