binary-io 0.1.0

A crate for reading and writing binary data files, according to LCS4. Also supports an extend version of the NBT format, as well as the ShadeNBT format.
Documentation
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
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
//! Implementation of LCS4 IO for

pub use std::io::Error as IoError;
use std::{
    error::Error as StdError,
    io::{ErrorKind, Seek},
    mem::MaybeUninit,
    rc::Rc,
    sync::Arc,
};
use std::{
    fmt::Display,
    io::{Read, Write},
    slice,
};

/// An enumeration that stores the possible byte order modes as specified by LCS4
#[derive(Copy, Clone, PartialEq, Eq, Debug)]
pub enum ByteOrder {
    /// The Big Endian (Most Significant Byte first) Byte Order
    BigEndian,
    /// The Little Endian (Least Significant Byte first) Byte Order
    LittleEndian,
}

impl ByteOrder {
    /// Returns the Byte Order used by the host
    pub const fn native() -> Self {
        #[cfg(target_endian = "little")]
        {
            Self::LittleEndian
        }
        #[cfg(target_endian = "big")]
        {
            Self::BigEndian
        }
        #[cfg(not(any(target_endian = "little", target_endian = "big")))]
        {
            compile_error!("Unsupported Native Byte Order")
        }
    }
}

/// A Trait for types that can perform binary IO Reads
pub trait DataInput: Read {
    ///
    /// Reads exactly bytes.len() bytes into bytes.
    /// Returns an error if an End of File prevents reading the entire array.
    fn read_fully(&mut self, bytes: &mut [u8]) -> std::io::Result<()> {
        let len = <Self as Read>::read(self, bytes)?;
        if len != bytes.len() {
            Err(std::io::Error::new(
                ErrorKind::UnexpectedEof,
                "Unexpected EOF in read_fully",
            ))
        } else {
            Ok(())
        }
    }
    /// Reads a single byte, and returns it, or an error if a byte cannot be read
    fn read_byte(&mut self) -> std::io::Result<u8> {
        let mut ret = 0u8;
        self.read_fully(slice::from_mut(&mut ret))?;
        Ok(ret)
    }
    /// Gets the current byte order mode
    fn byte_order(&self) -> ByteOrder;
    /// Sets the current byte order mode
    fn set_byte_order(&mut self, order: ByteOrder);
}

impl<R: DataInput> DataInput for &mut R {
    fn byte_order(&self) -> ByteOrder {
        R::byte_order(self)
    }

    fn set_byte_order(&mut self, order: ByteOrder) {
        R::set_byte_order(self, order)
    }

    fn read_fully(&mut self, bytes: &mut [u8]) -> std::io::Result<()> {
        R::read_fully(self, bytes)
    }

    fn read_byte(&mut self) -> std::io::Result<u8> {
        R::read_byte(self)
    }
}

impl<R: DataInput> DataInput for Box<R> {
    fn byte_order(&self) -> ByteOrder {
        R::byte_order(self)
    }

    fn set_byte_order(&mut self, order: ByteOrder) {
        R::set_byte_order(self, order)
    }

    fn read_fully(&mut self, bytes: &mut [u8]) -> std::io::Result<()> {
        R::read_fully(self, bytes)
    }

    fn read_byte(&mut self) -> std::io::Result<u8> {
        R::read_byte(self)
    }
}

///
/// A type that can perform Binary IO Reads by passing through reads to a type that implements Read
pub struct DataInputStream<R: ?Sized> {
    order: ByteOrder,
    read: R,
}

impl<R> DataInputStream<R> {
    ///
    /// Constructs a new DataInputStream from a given stream, in the given byte order mode
    pub const fn new(read: R, order: ByteOrder) -> Self {
        Self { read, order }
    }

    ///
    /// Constructs a new DataInputStream from a given stream, in the native byte order mode
    pub const fn new_native(read: R) -> Self {
        Self::new(read, ByteOrder::native())
    }

    ///
    /// Returns the inner stream
    pub fn into_inner(self) -> R {
        self.read
    }
}

impl<R: Read + ?Sized> Read for DataInputStream<R> {
    fn read(&mut self, buf: &mut [u8]) -> std::io::Result<usize> {
        self.read.read(buf)
    }
}

impl<R: Read + ?Sized> DataInput for DataInputStream<R> {
    fn byte_order(&self) -> ByteOrder {
        self.order
    }

    fn set_byte_order(&mut self, order: ByteOrder) {
        self.order = order
    }
}

impl<R: Read + Seek + ?Sized> Seek for DataInputStream<R> {
    fn seek(&mut self, pos: std::io::SeekFrom) -> std::io::Result<u64> {
        self.read.seek(pos)
    }
}

///
/// A trait for types which can be deserialized from a stream of bytes according to LCS 4
pub trait Deserializeable {
    /// Deserializes the bytes on the stream and stores the result in self or returns an error
    fn deserialize<R: DataInput + ?Sized>(&mut self, input: &mut R) -> std::io::Result<()>;
}

impl<T: Deserializeable + ?Sized> Deserializeable for &mut T {
    fn deserialize<R: DataInput + ?Sized>(&mut self, input: &mut R) -> std::io::Result<()> {
        T::deserialize(self, input)
    }
}

impl<T: Deserializeable + ?Sized> Deserializeable for Box<T> {
    fn deserialize<R: DataInput + ?Sized>(&mut self, input: &mut R) -> std::io::Result<()> {
        T::deserialize(self, input)
    }
}

impl<T: Deserializeable> Deserializeable for [T] {
    fn deserialize<R: DataInput + ?Sized>(&mut self, input: &mut R) -> std::io::Result<()> {
        for r in self {
            r.deserialize(input)?;
        }
        Ok(())
    }
}

impl<T: Deserializeable, const N: usize> Deserializeable for [T; N] {
    fn deserialize<R: DataInput + ?Sized>(&mut self, input: &mut R) -> std::io::Result<()> {
        <[T]>::deserialize(self, input)
    }
}

impl<T: Deserializeable> Deserializeable for Option<T> {
    fn deserialize<R: DataInput + ?Sized>(&mut self, input: &mut R) -> std::io::Result<()> {
        match self {
            Some(t) => t.deserialize(input),
            None => Ok(()),
        }
    }
}

///
/// A trait for types which can be deserialized and produce a new instance
/// It's intended that this impl should be more efficient then creating a new instance, then reading into it
pub trait DeserializeCopy: Deserializeable + Sized {
    /// Deserializes the bytes on the stream and returns the resulting value or an error
    fn deserialize_copy<R: DataInput + ?Sized>(input: &mut R) -> std::io::Result<Self>;
}

impl<T: DeserializeCopy> DeserializeCopy for Box<T> {
    fn deserialize_copy<R: DataInput + ?Sized>(input: &mut R) -> std::io::Result<Self> {
        T::deserialize_copy(input).map(Box::new)
    }
}

// MCG too OP
impl<T: DeserializeCopy, const N: usize> DeserializeCopy for [T; N] {
    fn deserialize_copy<R: DataInput + ?Sized>(input: &mut R) -> std::io::Result<Self> {
        let mut uninit = MaybeUninit::<[T; N]>::uninit();
        let ptr = uninit.as_mut_ptr().cast::<T>();
        for i in 0..N {
            // SAFETY:
            // i is between 0 and N, and the array has length N
            let ptr = unsafe { ptr.add(i) };
            // SAFETY:
            // ptr is within the array uninit, and thus is valid
            unsafe { ptr.write(T::deserialize_copy(input)?) }
        }
        // SAFETY:
        // uninit is initialized by initializing each element in the above loop
        Ok(unsafe { uninit.assume_init() })
    }
}

/// A Trait for types that can perform binary IO Writes
pub trait DataOutput: Write {
    ///
    /// Writes all of `bytes` to the underlying stream or returns an error
    fn write_bytes(&mut self, bytes: &[u8]) -> std::io::Result<()> {
        Ok(self.write_all(bytes)?)
    }
    ///
    /// Writes byte to the underlying stream or returns an error
    fn write_byte(&mut self, byte: u8) -> std::io::Result<()> {
        self.write_bytes(slice::from_ref(&byte))
    }
    ///
    /// Returns the byte order mode for the stream
    fn byte_order(&self) -> ByteOrder;
    ///
    /// Sets the byte order mode on the stream
    fn set_byte_order(&mut self, order: ByteOrder);
}

///
/// A type that can serialize types according to LCS4
pub struct DataOutputStream<W: ?Sized> {
    order: ByteOrder,
    write: W,
}

impl<W> DataOutputStream<W> {
    ///
    /// Constructs a new DataOutputStream from the given underlying stream and byte order mode
    pub const fn new(write: W, order: ByteOrder) -> Self {
        Self { write, order }
    }

    ///
    /// Constructs a new DataOutputStream from the given underlying stream and the native byte order mode
    pub const fn new_native(write: W) -> Self {
        Self::new(write, ByteOrder::native())
    }

    ///
    /// unwraps the DataOutputStream into the inner stream
    pub fn into_inner(self) -> W {
        self.write
    }
}

impl<W: Write + ?Sized> Write for DataOutputStream<W> {
    fn write(&mut self, buf: &[u8]) -> std::io::Result<usize> {
        self.write.write(buf)
    }

    fn flush(&mut self) -> std::io::Result<()> {
        self.write.flush()
    }
}

impl<W: Write + ?Sized> DataOutput for DataOutputStream<W> {
    fn byte_order(&self) -> ByteOrder {
        self.order
    }

    fn set_byte_order(&mut self, order: ByteOrder) {
        self.order = order;
    }
}

impl<W: Write + Seek + ?Sized> Seek for DataOutputStream<W> {
    fn seek(&mut self, pos: std::io::SeekFrom) -> std::io::Result<u64> {
        self.write.seek(pos)
    }
}

///
/// A trait for types that can be serialized as a sequence of bytes according to LCS 4
pub trait Serializeable {
    ///
    /// Serializes the type to the stream
    fn serialize<W: DataOutput + ?Sized>(&self, output: &mut W) -> std::io::Result<()>;
}

impl<T: Serializeable + ?Sized> Serializeable for &T {
    fn serialize<W: DataOutput + ?Sized>(&self, output: &mut W) -> std::io::Result<()> {
        T::serialize(self, output)
    }
}
impl<T: Serializeable + ?Sized> Serializeable for &mut T {
    fn serialize<W: DataOutput + ?Sized>(&self, output: &mut W) -> std::io::Result<()> {
        T::serialize(self, output)
    }
}

impl<T: Serializeable + ?Sized> Serializeable for Box<T> {
    fn serialize<W: DataOutput + ?Sized>(&self, output: &mut W) -> std::io::Result<()> {
        T::serialize(self, output)
    }
}

impl<T: Serializeable + ?Sized> Serializeable for Rc<T> {
    fn serialize<W: DataOutput + ?Sized>(&self, output: &mut W) -> std::io::Result<()> {
        T::serialize(self, output)
    }
}

impl<T: Serializeable + ?Sized> Serializeable for Arc<T> {
    fn serialize<W: DataOutput + ?Sized>(&self, output: &mut W) -> std::io::Result<()> {
        T::serialize(self, output)
    }
}

impl<T: Serializeable> Serializeable for [T] {
    fn serialize<W: DataOutput + ?Sized>(&self, output: &mut W) -> std::io::Result<()> {
        for t in self {
            t.serialize(output)?;
        }
        Ok(())
    }
}

impl<T: Serializeable, const N: usize> Serializeable for [T; N] {
    fn serialize<W: DataOutput + ?Sized>(&self, output: &mut W) -> std::io::Result<()> {
        for t in self {
            t.serialize(output)?;
        }
        Ok(())
    }
}

impl<T: Serializeable> Serializeable for Option<T> {
    fn serialize<W: DataOutput + ?Sized>(&self, output: &mut W) -> std::io::Result<()> {
        match self {
            Some(v) => v.serialize(output),
            None => Ok(()),
        }
    }
}

impl Deserializeable for u8 {
    fn deserialize<R: DataInput + ?Sized>(&mut self, input: &mut R) -> std::io::Result<()> {
        input.read_fully(slice::from_mut(self))
    }
}

impl DeserializeCopy for u8 {
    fn deserialize_copy<R: DataInput + ?Sized>(input: &mut R) -> std::io::Result<Self> {
        input.read_byte()
    }
}

impl Deserializeable for i8 {
    fn deserialize<R: DataInput + ?Sized>(&mut self, input: &mut R) -> std::io::Result<()> {
        // SAFETY:
        // the pointer is from self
        // i8 and u8 have the same size, alignment, and representation
        input.read_fully(slice::from_mut(unsafe {
            &mut *(self as *mut i8 as *mut u8)
        }))
    }
}

impl DeserializeCopy for i8 {
    fn deserialize_copy<R: DataInput + ?Sized>(input: &mut R) -> std::io::Result<Self> {
        input.read_byte().map(|u| u as i8)
    }
}

impl Serializeable for u8 {
    fn serialize<W: DataOutput + ?Sized>(&self, input: &mut W) -> std::io::Result<()> {
        input.write_byte(*self)
    }
}

impl Serializeable for i8 {
    fn serialize<W: DataOutput + ?Sized>(&self, input: &mut W) -> std::io::Result<()> {
        input.write_byte(*self as u8)
    }
}

macro_rules! impl_for_tuples{
    () => {
        impl Deserializeable for (){
            fn deserialize<S: DataInput + ?Sized>(&mut self,_: &mut S) -> std::io::Result<()>{
                Ok(())
            }
        }
        impl DeserializeCopy for (){
            fn deserialize_copy<S: DataInput + ?Sized>(_: &mut S) -> std::io::Result<()>{
                Ok(())
            }
        }
        impl Serializeable for (){
            fn serialize<S: DataOutput + ?Sized>(&self,_: &mut S) -> std::io::Result<()>{
                Ok(())
            }
        }
    };
    ($a:ident) => {
        #[allow(non_snake_case)]
        impl<$a : Deserializeable + ?Sized> Deserializeable for ($a ,){
            fn deserialize<S: DataInput + ?Sized>(&mut self,input: &mut S) -> std::io::Result<()>{
                let ($a,) = self;
                $a.deserialize(input)
            }
        }
        #[allow(non_snake_case)]
        impl<$a : DeserializeCopy> DeserializeCopy for ($a ,){
            fn deserialize_copy<S: DataInput + ?Sized>(input: &mut S) -> std::io::Result<Self>{
                Ok((<$a>::deserialize_copy(input)?,))
            }
        }
        #[allow(non_snake_case)]
        impl<$a : Serializeable + ?Sized> Serializeable for ($a ,){
            fn serialize<S: DataOutput + ?Sized>(&self,input: &mut S) -> std::io::Result<()>{
                let ($a,) = self;
                $a.serialize(input)
            }
        }
    };
    ($($leading:ident),+) => {
        #[allow(non_snake_case)]
        impl<$($leading: Deserializeable),+ +?Sized> Deserializeable for ($($leading),+){
            fn deserialize<S: DataInput + ?Sized>(&mut self,input: &mut S) -> std::io::Result<()>{
                let ($($leading),+,) = self;
                $({$leading .deserialize(input)?})*
                Ok(())
            }
        }
        #[allow(non_snake_case)]
        impl<$($leading: DeserializeCopy),*> DeserializeCopy for ($($leading),* ){
            fn deserialize_copy<S: DataInput + ?Sized>(input: &mut S) -> std::io::Result<Self>{
                Ok(($($leading::deserialize_copy(input)?),*))
            }
        }
        #[allow(non_snake_case)]
        impl<$($leading: Serializeable),+ +?Sized> Serializeable for ($($leading),+){
            fn serialize<S: DataOutput + ?Sized>(&self,input: &mut S) -> std::io::Result<()>{
                let ($($leading),+,) = self;
                $({$leading .serialize(input)?})*
                Ok(())
            }
        }
    };
}

impl_for_tuples!();
impl_for_tuples!(A);
impl_for_tuples!(A, B);
impl_for_tuples!(A, B, C);
impl_for_tuples!(A, B, C, D);
impl_for_tuples!(A, B, C, D, E);
impl_for_tuples!(A, B, C, D, E, F);
impl_for_tuples!(A, B, C, D, E, F, G);
impl_for_tuples!(A, B, C, D, E, F, G, H);
impl_for_tuples!(A, B, C, D, E, F, G, H, I);
impl_for_tuples!(A, B, C, D, E, F, G, H, I, J);
impl_for_tuples!(A, B, C, D, E, F, G, H, I, J, K);
impl_for_tuples!(A, B, C, D, E, F, G, H, I, J, K, L);

macro_rules! impl_for_primitives{
    [$($ty:ty),+] => {
        $(
            impl Deserializeable for $ty{
                fn deserialize<R: DataInput + ?Sized>(&mut self,input: &mut R) -> std::io::Result<()>{
                    let mut bytes = [0u8;std::mem::size_of::<$ty>()];
                    input.read_fully(&mut bytes)?;
                    *self = match input.byte_order(){
                        ByteOrder::BigEndian => <$ty>::from_be_bytes(bytes),
                        ByteOrder::LittleEndian => <$ty>::from_le_bytes(bytes)
                    };
                    Ok(())
                }
            }
            impl DeserializeCopy for $ty{
                fn deserialize_copy<R: DataInput + ?Sized>(input: &mut R) -> std::io::Result<Self>{
                    let mut bytes = [0u8;std::mem::size_of::<$ty>()];
                    input.read_fully(&mut bytes)?;
                    Ok(match input.byte_order(){
                        ByteOrder::BigEndian => <$ty>::from_be_bytes(bytes),
                        ByteOrder::LittleEndian => <$ty>::from_le_bytes(bytes)
                    })
                }
            }
            impl Serializeable for $ty{
                fn serialize<W: DataOutput + ?Sized>(&self,output: &mut W) -> std::io::Result<()>{
                    let bytes = match output.byte_order(){
                        ByteOrder::BigEndian => <$ty>::to_be_bytes(*self),
                        ByteOrder::LittleEndian => <$ty>::to_le_bytes(*self)
                    };
                    output.write_bytes(&bytes)
                }
            }
        )+
    }
}

impl_for_primitives![i16, u16, i32, u32, i64, u64, i128, u128, f32, f64];

impl Deserializeable for String {
    fn deserialize<R: DataInput + ?Sized>(&mut self, input: &mut R) -> std::io::Result<()> {
        let size = u16::deserialize_copy(input)? as usize;
        let mut vec = vec![0u8; size];
        input.read_fully(&mut vec)?;
        *self =
            String::from_utf8(vec).map_err(|e| std::io::Error::new(ErrorKind::InvalidData, e))?;
        Ok(())
    }
}

impl DeserializeCopy for String {
    fn deserialize_copy<R: DataInput + ?Sized>(input: &mut R) -> std::io::Result<Self> {
        let size = u16::deserialize_copy(input)? as usize;
        let mut vec = vec![0u8; size];
        input.read_fully(&mut vec)?;
        String::from_utf8(vec).map_err(|e| std::io::Error::new(ErrorKind::InvalidData, e))
    }
}

///
/// An error type that indicates a particular value is outside of a range imposed for {de,}serialization
#[derive(Copy, Clone, PartialEq, Eq, Debug)]
pub struct OutOfRange<T>(pub T);

impl<T: Display> Display for OutOfRange<T> {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.write_fmt(format_args!(
            "{} is not in range for this operation",
            &self.0
        ))
    }
}

impl<T> StdError for OutOfRange<T> where Self: std::fmt::Debug + Display {}

impl Serializeable for String {
    fn serialize<W: DataOutput + ?Sized>(&self, output: &mut W) -> std::io::Result<()> {
        let size = self.len();
        if size > u16::MAX as usize {
            Err(std::io::Error::new(
                ErrorKind::InvalidData,
                OutOfRange(size),
            ))
        } else {
            (size as u16).serialize(output)?;
            output.write_bytes(self.as_bytes())
        }
    }
}