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
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
use std::collections::BTreeSet;
use std::ffi::{OsStr, OsString};
use std::fs;
use std::io;
use std::io::{Error, ErrorKind, Write};
use std::mem::size_of;
use std::path::Path;
use byteorder::{LittleEndian, WriteBytesExt};
use log::debug;
use crate::{
ItemKind, Location, Metadata, CORRUPTION_CHECK_BYTES, FILE_ID, FORMAT_VERSION, PATH_SEPARATOR,
};
pub struct Item {
kind: ItemKind,
contents: Vec<u8>,
/// Path of the file within the bank, including any leading directory.
path_os: OsString,
}
impl Item {
#[must_use]
pub fn file_name_bytes(&self) -> Vec<u8> {
self.path_os.to_string_lossy().as_bytes().to_owned()
}
}
pub struct BankWriter<WriterType: Write> {
inner: WriterType,
items: Vec<Item>,
/// If the data has already been committed with a call to `write()`.
written: bool,
}
impl<WriterType: Write> BankWriter<WriterType> {
pub fn new(inner: WriterType) -> BankWriter<WriterType> {
BankWriter {
inner,
items: Vec::new(),
written: false,
}
}
/// Adding an item with empty contents results in the item being treated as a directory
/// instead of a file. It is a limitation of the format that there is no way to have
/// zero-length contents.
///
/// * `kind` - type of the file
/// * `file_name` - name of the file within the bank, without any leading directory
/// * `contents` - the data to include in the bank
///
/// # Errors
///
/// Will return `Err` if the bank has already been written
pub fn add(&mut self, kind: ItemKind, file_name: &OsStr, contents: Vec<u8>) -> io::Result<()> {
if self.written {
return Err(Error::new(
ErrorKind::Other,
"Cannot add to a bank that has already been written",
));
}
// Add the leading directory so the item is ready to use.
let file_name = if let Some(dir_name) = kind.directory() {
let mut path_str = OsString::from(dir_name);
path_str.push(PATH_SEPARATOR.to_string());
path_str.push(file_name);
path_str
} else {
file_name.to_owned()
};
self.items.push(Item {
kind,
contents,
path_os: file_name,
});
Ok(())
}
/// * `kind` - type of the file
/// * `file_name` - name of the file within the bank
/// * `data_path` - location of the file that contains the data to include
///
/// # Errors
///
/// Will return `Err` if the bank has already been written
pub fn add_file<P: AsRef<Path>>(
&mut self,
kind: ItemKind,
file_name: &OsStr,
data_path: P,
) -> io::Result<()> {
let contents = fs::read(data_path)?;
self.add(kind, file_name, contents)
}
/// A default ID will be created if one is not provided.
///
/// # Errors
///
/// Will return `Err` if the bank has already been written
pub fn add_metadata(&mut self, metadata: &Metadata) -> io::Result<()> {
// Create the ID from the author and name if there isn't one.
let contents = if metadata.id.is_empty() {
let mut id_parts = Vec::with_capacity(2);
let author_part = Metadata::sanitize_id(&metadata.author);
let name_part = Metadata::sanitize_id(&metadata.name);
if !author_part.is_empty() {
id_parts.push(author_part);
}
if !name_part.is_empty() {
id_parts.push(name_part);
}
let metadata = Metadata {
version: metadata.version,
id: id_parts.join("."),
name: metadata.name.clone(),
author: metadata.author.clone(),
description: metadata.description.clone(),
hash: metadata.hash.clone(),
extra: metadata.extra.clone(),
};
// Pretty-print the JSON to match what Bank Maker does. Bank
// Maker uses \n\r end of line on Windows and \n on Mac.
serde_json::to_vec_pretty(&metadata)?
} else {
serde_json::to_vec_pretty(metadata)?
};
debug!(
"Adding metadata contents: {}",
String::from_utf8_lossy(&contents)
);
self.add(
ItemKind::Metadata,
OsStr::new(Metadata::FILE_NAME),
contents,
)
}
/// Commit the contents added to the bank. All bytes will be written to the
/// underlying stream before returning.
///
/// # Errors
///
/// Will return `Err` if the bank has already been written
pub fn write(&mut self) -> io::Result<()> {
// The file is written in one pass, without seeking backwards, to allow
// the possibility of streaming the output.
if self.written {
return Err(Error::new(
ErrorKind::Other,
"The bank has already been written",
));
}
// Include metadata if it hasn't been provided.
if !self
.items
.iter()
.any(|item| item.kind == ItemKind::Metadata)
{
debug!("Adding default metadata");
self.add_metadata(&Metadata::default())?;
}
let kinds = self
.items
.iter()
.map(|item| item.kind)
.collect::<BTreeSet<ItemKind>>();
debug!("Kinds of items in this bank are {:?}", kinds);
// Header
self.inner.write_all(FILE_ID)?;
self.inner.write_all(CORRUPTION_CHECK_BYTES)?;
self.inner.write_all(FORMAT_VERSION)?;
// Number of files and directories added to the bank.
let file_count = self.items.len();
let directory_count = kinds.iter().filter_map(ItemKind::directory).count();
let location_count = file_count + directory_count;
self.inner
.write_u64::<LittleEndian>(location_count as u64)?;
debug!("Number of location is {location_count}");
// Offsets
let location_block_start =
FILE_ID.len() + CORRUPTION_CHECK_BYTES.len() + FORMAT_VERSION.len() + size_of::<u64>();
let file_name_block_length: usize = kinds
.iter()
.map(|kind| {
// All the filenames and directory names for the kind.
let dir_name_len = kind.directory().map_or(0, |dir| dir.as_bytes().len() + 1);
let file_names_len = self
.items
.iter()
.map(|item| {
if item.kind == *kind {
item.file_name_bytes().len() + 1
} else {
0
}
})
.sum::<usize>();
file_names_len + dir_name_len
})
.sum();
let mut data_offset = (location_block_start
+ (location_count * Location::BLOCK_SIZE)
+ size_of::<u64>()
+ file_name_block_length) as u64;
// Locations
let mut file_name_block = Vec::new();
for kind in &kinds {
// Some kinds of items require a directory entry.
if let Some(directory) = kind.directory() {
debug!("Writing directory {directory}");
self.inner
.write_u64::<LittleEndian>(file_name_block.len() as u64)?;
file_name_block.extend_from_slice(directory.as_bytes());
file_name_block.push(0_u8);
self.inner.write_u64::<LittleEndian>(0)?; // Data offset
self.inner.write_u64::<LittleEndian>(0)?; // Data size
}
for item in self.items.iter().filter(|item| item.kind == *kind) {
self.inner
.write_u64::<LittleEndian>(file_name_block.len() as u64)?;
file_name_block.extend(item.file_name_bytes());
file_name_block.push(0_u8);
let contents_len = item.contents.len() as u64;
self.inner.write_u64::<LittleEndian>(data_offset)?;
self.inner.write_u64::<LittleEndian>(contents_len)?;
data_offset += contents_len;
}
}
debug!("File name block length is {file_name_block_length}");
self.inner
.write_u64::<LittleEndian>(file_name_block_length as u64)?;
self.inner.write_all(&file_name_block)?;
// Write the contents of each item.
for kind in kinds {
for item in self.items.iter().filter(|item| kind == item.kind) {
debug!(
"Writing item {} ({} bytes)",
item.path_os.to_string_lossy(),
item.contents.len()
);
self.inner.write_all(&item.contents)?;
}
}
self.inner.flush()?;
self.written = true;
Ok(())
}
}