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
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
use std::convert::TryFrom;
use std::io::{self, Cursor, Read, Seek, SeekFrom, Write};
use byteorder::{BigEndian, ReadBytesExt, WriteBytesExt};
use flate2::read::ZlibEncoder;
use flate2::Compression;
use num_enum::TryFromPrimitive;
use crate::{Error, Result};
pub(crate) const SECTOR_SIZE: usize = 4096;
pub(crate) const REGION_HEADER_SIZE: usize = 2 * SECTOR_SIZE;
pub(crate) const CHUNK_HEADER_SIZE: usize = 5;
pub struct Region<S> {
stream: S,
offsets: Vec<u64>,
}
impl<S> Region<S>
where
S: Read + Write + Seek,
{
pub fn new(mut stream: S) -> Result<Self> {
stream.rewind()?;
stream.write_all(&[0; REGION_HEADER_SIZE])?;
Ok(Self {
stream,
offsets: vec![2],
})
}
pub fn from_stream(stream: S) -> Result<Self> {
let mut tmp = Self {
stream,
offsets: vec![],
};
let mut max_offset = 0;
let mut max_offsets_sector_count = 0;
for z in 0..32 {
for x in 0..32 {
let loc = tmp.location(x, z)?;
if loc.offset == 0 && loc.sectors == 0 {
continue;
}
tmp.offsets.push(loc.offset);
if loc.offset > max_offset {
max_offset = loc.offset;
max_offsets_sector_count = loc.sectors;
}
}
}
tmp.offsets.sort_unstable();
tmp.offsets.push(max_offset + max_offsets_sector_count);
Ok(tmp)
}
pub fn into_inner(mut self) -> io::Result<S> {
self.stream.rewind()?;
Ok(self.stream)
}
pub fn read_chunk(&mut self, x: usize, z: usize) -> Result<Option<Vec<u8>>> {
self.compression_scheme(x, z)?
.map(|scheme| match scheme {
CompressionScheme::Zlib => {
let mut decoder = flate2::write::ZlibDecoder::new(vec![]);
self.read_compressed_chunk(x, z, &mut decoder)?;
Ok(decoder.finish()?)
}
CompressionScheme::Gzip => {
let mut decoder = flate2::write::GzDecoder::new(vec![]);
self.read_compressed_chunk(x, z, &mut decoder)?;
Ok(decoder.finish()?)
}
CompressionScheme::Uncompressed => {
let mut buf = vec![];
self.read_compressed_chunk(x, z, &mut buf)?;
Ok(buf)
}
})
.transpose()
}
pub fn write_chunk(&mut self, x: usize, z: usize, uncompressed_chunk: &[u8]) -> Result<()> {
let mut buf = vec![];
let mut enc = ZlibEncoder::new(uncompressed_chunk, Compression::fast());
enc.read_to_end(&mut buf)?;
self.write_compressed_chunk(x, z, CompressionScheme::Zlib, &buf)
}
pub fn write_compressed_chunk(
&mut self,
x: usize,
z: usize,
scheme: CompressionScheme,
compressed_chunk: &[u8],
) -> Result<()> {
let loc = self.location(x, z)?;
let required_sectors =
unstable_div_ceil(CHUNK_HEADER_SIZE + compressed_chunk.len(), SECTOR_SIZE);
if loc.offset == 0 && loc.sectors == 0 {
let offset = *self.offsets.last().expect("offset should always exist");
self.offsets.push(offset + required_sectors as u64);
self.set_chunk(offset, scheme, compressed_chunk)?;
self.set_header(x, z, offset, required_sectors)?;
} else {
let i = self.offsets.binary_search(&loc.offset).unwrap();
let start_offset = self.offsets[i];
let end_offset = self.offsets[i + 1];
let available_sectors = (end_offset - start_offset) as usize;
if required_sectors <= available_sectors {
self.set_chunk(start_offset, scheme, compressed_chunk)?;
self.set_header(x, z, start_offset, required_sectors)?;
} else {
self.offsets.remove(i);
let offset = *self.offsets.last().unwrap() as u64;
self.offsets.push(offset + required_sectors as u64);
self.set_chunk(offset, scheme, compressed_chunk)?;
self.set_header(x, z, offset, required_sectors)?;
}
}
Ok(())
}
fn read_compressed_chunk(
&mut self,
x: usize,
z: usize,
writer: &mut dyn Write,
) -> Result<bool> {
if x >= 32 || z >= 32 {
return Err(Error::InvalidOffset(x as isize, z as isize));
}
let loc = self.location(x, z)?;
if loc.offset == 0 && loc.sectors == 0 {
Ok(false)
} else {
self.stream
.seek(SeekFrom::Start(loc.offset * SECTOR_SIZE as u64))?;
let mut buf = [0u8; 5];
self.stream.read_exact(&mut buf)?;
let metadata = ChunkMeta::new(&buf)?;
let mut adapted = (&mut self.stream).take(metadata.compressed_len as u64);
io::copy(&mut adapted, writer)?;
Ok(true)
}
}
fn compression_scheme(&mut self, x: usize, z: usize) -> Result<Option<CompressionScheme>> {
if x >= 32 || z >= 32 {
return Err(Error::InvalidOffset(x as isize, z as isize));
}
let loc = self.location(x, z)?;
if loc.offset == 0 && loc.sectors == 0 {
Ok(None)
} else {
self.stream
.seek(SeekFrom::Start(loc.offset * SECTOR_SIZE as u64))?;
let mut buf = [0u8; 5];
self.stream.read_exact(&mut buf)?;
let metadata = ChunkMeta::new(&buf)?;
Ok(Some(metadata.compression_scheme))
}
}
pub fn iter(&mut self) -> RegionIter<'_, S> {
RegionIter::new(self)
}
pub(crate) fn location(&mut self, x: usize, z: usize) -> io::Result<ChunkLocation> {
self.stream.seek(SeekFrom::Start(header_pos(x, z)))?;
let mut buf = [0u8; 4];
self.stream.read_exact(&mut buf[..])?;
let mut offset = 0u64;
offset |= (buf[0] as u64) << 16;
offset |= (buf[1] as u64) << 8;
offset |= buf[2] as u64;
let sectors = buf[3] as u64;
Ok(ChunkLocation { offset, sectors })
}
fn set_chunk(&mut self, offset: u64, scheme: CompressionScheme, chunk: &[u8]) -> Result<()> {
self.stream
.seek(SeekFrom::Start(offset * SECTOR_SIZE as u64))?;
self.stream.write_all(&self.chunk_meta(
chunk.len() as u32,
scheme,
))?;
self.stream.write_all(chunk)?;
Ok(())
}
fn set_header(
&mut self,
x: usize,
z: usize,
offset: u64,
new_sector_count: usize,
) -> Result<()> {
if new_sector_count > 255 {
return Err(Error::ChunkTooLarge);
}
let mut buf = [0u8; 4];
buf[0] = ((offset & 0xFF0000) >> 16) as u8;
buf[1] = ((offset & 0x00FF00) >> 8) as u8;
buf[2] = (offset & 0x0000FF) as u8;
buf[3] = new_sector_count as u8;
self.stream.seek(SeekFrom::Start(header_pos(x, z)))?;
self.stream.write_all(&buf)?;
Ok(())
}
fn chunk_meta(&self, compressed_chunk_size: u32, scheme: CompressionScheme) -> [u8; 5] {
let mut buf = [0u8; 5];
let mut c = Cursor::new(buf.as_mut_slice());
c.write_u32::<BigEndian>(compressed_chunk_size + 1).unwrap();
c.write_u8(match scheme {
CompressionScheme::Gzip => 1,
CompressionScheme::Zlib => 2,
CompressionScheme::Uncompressed => 3,
})
.unwrap();
buf
}
}
#[derive(Debug, TryFromPrimitive)]
#[repr(u8)]
pub enum CompressionScheme {
Gzip = 1,
Zlib = 2,
Uncompressed = 3,
}
pub struct RegionIter<'a, S>
where
S: Read + Write + Seek,
{
inner: &'a mut Region<S>,
index: usize,
}
impl<'a, S> RegionIter<'a, S>
where
S: Read + Write + Seek,
{
fn new(inner: &'a mut Region<S>) -> Self {
Self { inner, index: 0 }
}
fn next_xz(&mut self) -> Option<(usize, usize)> {
let index = self.index;
self.index += 1;
if index == 32 * 32 {
return None;
}
let x = index % 32;
let z = index / 32;
Some((x, z))
}
}
pub struct ChunkData {
pub x: usize,
pub z: usize,
pub data: Vec<u8>,
}
impl<'a, S> Iterator for RegionIter<'a, S>
where
S: Read + Write + Seek,
{
type Item = Result<ChunkData>;
fn next(&mut self) -> Option<Self::Item> {
while let Some((x, z)) = self.next_xz() {
let c = self.inner.read_chunk(x, z);
match c {
Ok(Some(c)) => return Some(Ok(ChunkData { x, z, data: c })),
Ok(None) => {}
Err(e) => return Some(Err(e)),
}
}
None
}
}
pub const fn unstable_div_ceil(lhs: usize, rhs: usize) -> usize {
let d = lhs / rhs;
let r = lhs % rhs;
if r > 0 && rhs > 0 {
d + 1
} else {
d
}
}
fn header_pos(x: usize, z: usize) -> u64 {
(4 * ((x % 32) + (z % 32) * 32)) as u64
}
#[derive(Debug)]
pub struct ChunkLocation {
pub offset: u64,
pub sectors: u64,
}
#[derive(Debug)]
struct ChunkMeta {
pub compressed_len: u32,
pub compression_scheme: CompressionScheme,
}
impl ChunkMeta {
fn new(mut data: &[u8]) -> Result<Self> {
let len = data.read_u32::<BigEndian>()?;
let scheme = data.read_u8()?;
let scheme =
CompressionScheme::try_from(scheme).map_err(|_| Error::UnknownCompression(scheme))?;
Ok(Self {
compressed_len: len - 1,
compression_scheme: scheme,
})
}
}