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
use crate::endianness::{BigEndian, LittleEndian};
use crate::{BitStream, Endianness, Result};
use std::cell::RefCell;
use std::collections::HashMap;
use std::hash::Hash;
use std::marker::PhantomData;
use std::mem::size_of;
use std::rc::Rc;
use std::sync::Arc;

/// Trait for types that can be read from a stream without requiring the size to be configured
///
/// The `BitRead` trait can be used with `#[derive]` on structs and enums
///
/// # Structs
///
/// The implementation can be derived for a struct as long as every field in the struct implements `BitRead` or [`BitReadSized`]
///
/// The struct is read field by field in the order they are defined in, if the size for a field is set [`stream.read_sized()`][read_sized]
/// will be used, otherwise [`stream_read()`][read] will be used.
///
/// The size for a field can be set using 3 different methods
///  - set the size as an integer using the `size` attribute,
///  - use a previously defined field as the size using the `size` attribute
///  - read a set number of bits as an integer, using the resulting value as size using the `size_bits` attribute
///
/// ## Examples
///
/// ```
/// # use bitstream_reader_derive::BitRead;
/// #
/// #[derive(BitRead)]
/// struct TestStruct {
///     foo: u8,
///     str: String,
///     #[size = 2] // when `size` is set, the attributed will be read using `read_sized`
///     truncated: String,
///     bar: u16,
///     float: f32,
///     #[size = 3]
///     asd: u8,
///     #[size_bits = 2] // first read 2 bits as unsigned integer, then use the resulting value as size for the read
///     dynamic_length: u8,
///     #[size = "asd"] // use a previously defined field as size
///     previous_field: u8,
/// }
/// ```
///
/// # Enums
///
/// The implementation can be derived for an enum as long as every variant of the enum either has no field, or an unnamed field that implements `BitRead` or [`BitReadSized`]
///
/// The enum is read by first reading a set number of bits as the discriminant of the enum, then the variant for the read discriminant is read.
///
/// For details about setting the input size for fields implementing [`BitReadSized`] see the block about size in the `Structs` section above.
///
/// The discriminant for the variants defaults to incrementing by one for every field, starting with `0`.
/// You can overwrite the discriminant for a field, which will also change the discriminant for every following field.
///
/// ## Examples
///
/// ```
/// # use bitstream_reader_derive::BitRead;
/// #
/// #[derive(BitRead)]
/// #[discriminant_bits = 2]
/// enum TestBareEnum {
///     Foo,
///     Bar,
///     Asd = 3, // manually set the discriminant value for a field
/// }
/// ```
///
/// ```
/// # use bitstream_reader_derive::BitRead;
/// #
/// #[derive(BitRead)]
/// #[discriminant_bits = 2]
/// enum TestUnnamedFieldEnum {
///     #[size = 5]
///     Foo(i8),
///     Bar(bool),
///     #[discriminant = 3] // since rust only allows setting the discriminant on field-less enums, you can use an attribute instead
///     Asd(u8),
/// }
/// ```
///
/// [`BitReadSized`]: trait.BitReadSized.html
/// [read_sized]: struct.BitStream.html#method.read_sized
/// [read]: struct.BitStream.html#method.read
pub trait BitRead<E: Endianness>: Sized {
    /// Read the type from stream
    fn read(stream: &mut BitStream<E>) -> Result<Self>;
}

/// Trait to get the number of bits needed to read types that can be read from a stream without requiring the size to be configured.
pub trait BitSize {
    /// How many bits are required to read this type
    fn bit_size() -> usize;
}

/// Trait to allow skipping a type
///
/// This might be faster than trying to read it
pub trait BitSkip<E: Endianness>: BitRead<E> {
    /// Skip the type
    fn skip(stream: &mut BitStream<E>) -> Result<()> {
        Self::read(stream).map(|_| ())
    }
}

impl<T: BitRead<E> + BitSize, E: Endianness> BitSkip<E> for T {
    fn skip(stream: &mut BitStream<E>) -> Result<()> {
        stream.skip_bits(Self::bit_size())
    }
}

macro_rules! impl_read_int {
    ($type:ty) => {
        impl<E: Endianness> BitRead<E> for $type {
            #[inline]
            fn read(stream: &mut BitStream<E>) -> Result<$type> {
                stream.read_int::<$type>(size_of::<$type>() * 8)
            }
        }

        impl BitSize for $type {
            #[inline]
            fn bit_size() -> usize {
                size_of::<$type>() * 8
            }
        }
    };
}

macro_rules! impl_read_int_nonzero {
    ($type:ty) => {
        impl BitRead<LittleEndian> for Option<$type> {
            #[inline]
            fn read(stream: &mut BitStream<LittleEndian>) -> Result<Self> {
                Ok(<$type>::new(stream.read()?))
            }
        }

        impl BitRead<BigEndian> for Option<$type> {
            #[inline]
            fn read(stream: &mut BitStream<BigEndian>) -> Result<Self> {
                Ok(<$type>::new(stream.read()?))
            }
        }

        impl BitSize for $type {
            #[inline]
            fn bit_size() -> usize {
                size_of::<$type>() * 8
            }
        }
    };
}

impl_read_int!(u8);
impl_read_int!(u16);
impl_read_int!(u32);
impl_read_int!(u64);
impl_read_int!(u128);
impl_read_int!(i8);
impl_read_int!(i16);
impl_read_int!(i32);
impl_read_int!(i64);
impl_read_int!(i128);

impl_read_int_nonzero!(std::num::NonZeroU8);
impl_read_int_nonzero!(std::num::NonZeroU16);
impl_read_int_nonzero!(std::num::NonZeroU32);
impl_read_int_nonzero!(std::num::NonZeroU64);
impl_read_int_nonzero!(std::num::NonZeroU128);

impl<E: Endianness> BitRead<E> for f32 {
    #[inline]
    fn read(stream: &mut BitStream<E>) -> Result<f32> {
        stream.read_float::<f32>()
    }
}

impl BitSize for f32 {
    #[inline]
    fn bit_size() -> usize {
        32
    }
}

impl<E: Endianness> BitRead<E> for f64 {
    #[inline]
    fn read(stream: &mut BitStream<E>) -> Result<f64> {
        stream.read_float::<f64>()
    }
}

impl BitSize for f64 {
    #[inline]
    fn bit_size() -> usize {
        64
    }
}

impl<E: Endianness> BitRead<E> for bool {
    #[inline]
    fn read(stream: &mut BitStream<E>) -> Result<bool> {
        stream.read_bool()
    }
}

impl BitSize for bool {
    #[inline]
    fn bit_size() -> usize {
        1
    }
}

impl<E: Endianness> BitRead<E> for String {
    #[inline]
    fn read(stream: &mut BitStream<E>) -> Result<String> {
        stream.read_string(None)
    }
}

impl<E: Endianness, T: BitRead<E>> BitRead<E> for Rc<T> {
    #[inline]
    fn read(stream: &mut BitStream<E>) -> Result<Self> {
        Ok(Rc::new(T::read(stream)?))
    }
}

impl<E: Endianness, T: BitRead<E>> BitRead<E> for Arc<T> {
    #[inline]
    fn read(stream: &mut BitStream<E>) -> Result<Self> {
        Ok(Arc::new(T::read(stream)?))
    }
}

impl<E: Endianness, T: BitRead<E>> BitRead<E> for Box<T> {
    #[inline]
    fn read(stream: &mut BitStream<E>) -> Result<Self> {
        Ok(Box::new(T::read(stream)?))
    }
}

impl<T: BitSize> BitSize for Rc<T> {
    #[inline]
    fn bit_size() -> usize {
        T::bit_size()
    }
}

impl<T: BitSize> BitSize for Arc<T> {
    #[inline]
    fn bit_size() -> usize {
        T::bit_size()
    }
}

impl<T: BitSize> BitSize for Box<T> {
    #[inline]
    fn bit_size() -> usize {
        T::bit_size()
    }
}

macro_rules! impl_read_tuple {
    ($($type:ident),*) => {
        impl<E: Endianness, $($type: BitRead<E>),*> BitRead<E> for ($($type),*) {
            #[inline]
            fn read(stream: &mut BitStream<E>) -> Result<Self> {
                Ok(($(<$type>::read(stream)?),*))
            }
        }

        impl<$($type: BitSize),*> BitSize for ($($type),*) {
            #[inline]
            fn bit_size() -> usize {
                $(<$type>::bit_size() + )* 0
            }
        }
    };
}

impl_read_tuple!(T1, T2);
impl_read_tuple!(T1, T2, T3);
impl_read_tuple!(T1, T2, T3, T4);

/// Trait for types that can be read from a stream, requiring the size to be configured
///
/// The meaning of the set sized depends on the type being read (e.g, number of bits for integers,
/// number of bytes for strings, number of items for Vec's, etc)
///
/// The `BitReadSized` trait can be used with `#[derive]` on structs
///
/// The implementation can be derived for a struct as long as every field in the struct implements [`BitRead`] or `BitReadSized`
///
/// The struct is read field by field in the order they are defined in, if the size for a field is set [`stream.read_sized()`][read_sized]
/// will be used, otherwise [`stream_read()`][read] will be used.
///
/// The size for a field can be set using 4 different methods
///  - set the size as an integer using the `size` attribute,
///  - use a previously defined field as the size using the `size` attribute
///  - based on the input size by setting `size` attribute to `"input_size"`
///  - read a set number of bits as an integer, using the resulting value as size using the `size_bits` attribute
///
/// ## Examples
///
/// ```
/// # use bitstream_reader_derive::BitReadSized;
/// #
/// #[derive(BitReadSized, PartialEq, Debug)]
/// struct TestStructSized {
///     foo: u8,
///     #[size = "input_size"]
///     string: String,
///     #[size = "input_size"]
///     int: u8,
/// }
/// ```
///
/// # Enums
///
/// The implementation can be derived for an enum as long as every variant of the enum either has no field, or an unnamed field that implements [`BitRead`] or `BitReadSized`
///
/// The enum is read by first reading a set number of bits as the discriminant of the enum, then the variant for the read discriminant is read.
///
/// For details about setting the input size for fields implementing `BitReadSized` see the block about size in the `Structs` section above.
///
/// The discriminant for the variants defaults to incrementing by one for every field, starting with `0`.
/// You can overwrite the discriminant for a field, which will also change the discriminant for every following field.
///
/// ## Examples
///
/// ```
/// # use bitstream_reader_derive::BitReadSized;
/// #
/// #[derive(BitReadSized)]
/// #[discriminant_bits = 2]
/// enum TestUnnamedFieldEnum {
///     #[size = 5]
///     Foo(i8),
///     Bar(bool),
///     #[discriminant = 3] // since rust only allows setting the discriminant on field-less enums, you can use an attribute instead
///     #[size = "input_size"]
///     Asd(u8),
/// }
/// ```
///
/// [`BitRead`]: trait.BitRead.html
/// [read_sized]: struct.BitStream.html#method.read_sized
/// [read]: struct.BitStream.html#method.read
pub trait BitReadSized<E: Endianness>: Sized {
    /// Read the type from stream
    fn read(stream: &mut BitStream<E>, size: usize) -> Result<Self>;
}

/// Trait to get the number of bits needed to read types that can be read from a stream requiring the size to be configured.
pub trait BitSizeSized {
    /// How many bits are required to read this type
    fn bit_size(size: usize) -> usize;
}

macro_rules! impl_read_int_sized {
    ( $ type: ty) => {
        impl<E: Endianness> BitReadSized<E> for $type {
            #[inline]
            fn read(stream: &mut BitStream<E>, size: usize) -> Result<$type> {
                stream.read_int::<$type>(size)
            }
        }

        impl BitSizeSized for $type {
            #[inline]
            fn bit_size(size: usize) -> usize {
                size
            }
        }
    };
}

impl_read_int_sized!(u8);
impl_read_int_sized!(u16);
impl_read_int_sized!(u32);
impl_read_int_sized!(u64);
impl_read_int_sized!(u128);
impl_read_int_sized!(i8);
impl_read_int_sized!(i16);
impl_read_int_sized!(i32);
impl_read_int_sized!(i64);
impl_read_int_sized!(i128);

impl<E: Endianness> BitReadSized<E> for String {
    #[inline]
    fn read(stream: &mut BitStream<E>, size: usize) -> Result<String> {
        stream.read_string(Some(size))
    }
}

impl BitSizeSized for String {
    #[inline]
    fn bit_size(size: usize) -> usize {
        8 * size
    }
}

/// Read a boolean, if true, read `T`, else return `None`
impl<E: Endianness, T: BitRead<E>> BitRead<E> for Option<T> {
    fn read(stream: &mut BitStream<E>) -> Result<Self> {
        if stream.read()? {
            Ok(Some(stream.read()?))
        } else {
            Ok(None)
        }
    }
}

impl<T: BitSize> BitSize for Option<T> {
    #[inline]
    fn bit_size() -> usize {
        1 + T::bit_size()
    }
}

impl<E: Endianness, T: BitReadSized<E>> BitReadSized<E> for Option<T> {
    fn read(stream: &mut BitStream<E>, size: usize) -> Result<Self> {
        if stream.read()? {
            Ok(Some(stream.read_sized(size)?))
        } else {
            Ok(None)
        }
    }
}

impl<T: BitSizeSized> BitSizeSized for Option<T> {
    #[inline]
    fn bit_size(size: usize) -> usize {
        1 + T::bit_size(size)
    }
}

impl<E: Endianness> BitReadSized<E> for BitStream<E> {
    #[inline]
    fn read(stream: &mut BitStream<E>, size: usize) -> Result<Self> {
        stream.read_bits(size)
    }
}

impl<E: Endianness> BitSizeSized for BitStream<E> {
    #[inline]
    fn bit_size(size: usize) -> usize {
        size
    }
}

/// Read `T` `size` times and return as `Vec<T>`
impl<E: Endianness, T: BitRead<E>> BitReadSized<E> for Vec<T> {
    fn read(stream: &mut BitStream<E>, size: usize) -> Result<Self> {
        let mut vec = Vec::with_capacity(size);
        for _ in 0..size {
            vec.push(stream.read()?)
        }
        Ok(vec)
    }
}

impl<T: BitSize> BitSizeSized for Vec<T> {
    #[inline]
    fn bit_size(size: usize) -> usize {
        size * T::bit_size()
    }
}

// Once we have something like https://github.com/rust-lang/rfcs/issues/1053 we can do this optimization
//impl<E: Endianness> ReadSized<E> for Vec<u8> {
//    #[inline]
//    fn read(stream: &mut BitStream<E>, size: usize) -> Result<Self> {
//        stream.read_bytes(size)
//    }
//}

/// Read `K` and `T` `size` times and return as `HashMap<K, T>`
impl<E: Endianness, K: BitRead<E> + Eq + Hash, T: BitRead<E>> BitReadSized<E> for HashMap<K, T> {
    fn read(stream: &mut BitStream<E>, size: usize) -> Result<Self> {
        let mut map = HashMap::with_capacity(size);
        for _ in 0..size {
            let key = stream.read()?;
            let value = stream.read()?;
            map.insert(key, value);
        }
        Ok(map)
    }
}

impl<K: BitSize, T: BitSize> BitSizeSized for HashMap<K, T> {
    #[inline]
    fn bit_size(size: usize) -> usize {
        size * (K::bit_size() + T::bit_size())
    }
}

#[derive(Clone, Debug)]
/// Struct that lazily reads it's contents from the stream
///
/// Requires [`BitSize`] to be implemented for it's contents so it can grab the correct number of bytes
///
/// [`BitSize`]: trait.BitSize.html
pub struct LazyBitRead<T: BitRead<E> + BitSize, E: Endianness> {
    source: BitStream<E>,
    inner_type: PhantomData<T>,
}

impl<T: BitRead<E> + BitSize, E: Endianness> LazyBitRead<T, E> {
    #[inline]
    /// Get the contents of the lazy struct
    pub fn read(mut self) -> Result<T> {
        self.source.read::<T>()
    }
}

impl<T: BitRead<E> + BitSize, E: Endianness> BitRead<E> for LazyBitRead<T, E> {
    #[inline]
    fn read(stream: &mut BitStream<E>) -> Result<Self> {
        let bit_size = T::bit_size();
        Ok(LazyBitRead {
            source: stream.read_bits(bit_size)?,
            inner_type: PhantomData,
        })
    }
}

impl<T: BitRead<E> + BitSize, E: Endianness> BitSize for LazyBitRead<T, E> {
    #[inline]
    fn bit_size() -> usize {
        T::bit_size()
    }
}

#[derive(Clone, Debug)]
/// Struct that lazily reads it's contents from the stream
///
/// Requires [`BitSizeSized`] to be implemented for it's contents so it can grab the correct number of bytes
///
/// [`BitReadSized`]: trait.BitReadSized.html
pub struct LazyBitReadSized<T: BitReadSized<E> + BitSizeSized, E: Endianness> {
    source: RefCell<BitStream<E>>,
    size: usize,
    inner_type: PhantomData<T>,
}

impl<T: BitReadSized<E> + BitSizeSized, E: Endianness> LazyBitReadSized<T, E> {
    #[inline]
    /// Get the contents of the lazy struct
    pub fn value(self) -> Result<T> {
        self.source.borrow_mut().read_sized::<T>(self.size)
    }
}

impl<T: BitReadSized<E> + BitSizeSized, E: Endianness> BitReadSized<E> for LazyBitReadSized<T, E> {
    #[inline]
    fn read(stream: &mut BitStream<E>, size: usize) -> Result<Self> {
        let bit_size = T::bit_size(size);
        Ok(LazyBitReadSized {
            source: RefCell::new(stream.read_bits(bit_size)?),
            inner_type: PhantomData,
            size,
        })
    }
}

impl<T: BitReadSized<E> + BitSizeSized, E: Endianness> BitSizeSized for LazyBitReadSized<T, E> {
    #[inline]
    fn bit_size(size: usize) -> usize {
        T::bit_size(size)
    }
}