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
use crate::{BitReadStream, BitWriteStream, Endianness, Result};
use std::mem::size_of;
use std::rc::Rc;
use std::sync::Arc;

/// Trait for types that can be written to a stream without requiring the size to be configured
///
/// The `BitWrite` 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 `BitWrite` or [`BitWriteSized`]
///
/// The struct is written field by field in the order they are defined in, if the size for a field is set [`stream.write_sized()`][write_sized]
/// will be used, otherwise [`write_read()`][write] 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
///
/// ## Examples
///
/// ```
/// # use bitbuffer::BitWrite;
/// #
/// #[derive(BitWrite)]
/// 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 = "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 `BitWrite` or [`BitWriteSized`]
///
/// The enum is written by first writing a set number of bits as the discriminant of the enum, then the variant written.
///
/// For details about setting the input size for fields implementing [`BitWriteSized`] 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 bitbuffer::BitWrite;
/// #
/// #[derive(BitWrite)]
/// #[discriminant_bits = 2]
/// enum TestBareEnum {
///     Foo,
///     Bar,
///     Asd = 3, // manually set the discriminant value for a field
/// }
/// ```
///
/// ```
/// # use bitbuffer::BitWrite;
/// #
/// #[derive(BitWrite)]
/// #[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),
/// }
/// ```
///
/// [write_sized]: BitWriteStream::write_sized
/// [write]: BitWriteStream::write
pub trait BitWrite<E: Endianness> {
    /// Write the type to stream
    fn write(&self, stream: &mut BitWriteStream<E>) -> Result<()>;
}

macro_rules! impl_write_int {
    ($type:ty) => {
        impl<E: Endianness> BitWrite<E> for $type {
            #[inline]
            fn write(&self, stream: &mut BitWriteStream<E>) -> Result<()> {
                stream.write_int::<$type>(*self, size_of::<$type>() * 8)
            }
        }
    };
}

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

impl<E: Endianness> BitWrite<E> for f32 {
    #[inline]
    fn write(&self, stream: &mut BitWriteStream<E>) -> Result<()> {
        stream.write_float::<f32>(*self)
    }
}

impl<E: Endianness> BitWrite<E> for f64 {
    #[inline]
    fn write(&self, stream: &mut BitWriteStream<E>) -> Result<()> {
        stream.write_float::<f64>(*self)
    }
}

impl<E: Endianness> BitWrite<E> for bool {
    #[inline]
    fn write(&self, stream: &mut BitWriteStream<E>) -> Result<()> {
        stream.write_bool(*self)
    }
}

impl<E: Endianness> BitWrite<E> for str {
    #[inline]
    fn write(&self, stream: &mut BitWriteStream<E>) -> Result<()> {
        stream.write_string(self, None)
    }
}

impl<E: Endianness> BitWrite<E> for String {
    #[inline]
    fn write(&self, stream: &mut BitWriteStream<E>) -> Result<()> {
        stream.write_string(self, None)
    }
}

impl<E: Endianness> BitWrite<E> for BitReadStream<'_, E> {
    #[inline]
    fn write(&self, stream: &mut BitWriteStream<E>) -> Result<()> {
        stream.write_bits(self)
    }
}

impl<E: Endianness, T: BitWrite<E>, const N: usize> BitWrite<E> for [T; N] {
    #[inline]
    fn write(&self, stream: &mut BitWriteStream<E>) -> Result<()> {
        for element in self.iter() {
            stream.write(element)?;
        }
        Ok(())
    }
}

impl<T: BitWrite<E>, E: Endianness> BitWrite<E> for Box<T> {
    #[inline]
    fn write(&self, stream: &mut BitWriteStream<E>) -> Result<()> {
        stream.write(self.as_ref())
    }
}

impl<T: BitWrite<E>, E: Endianness> BitWrite<E> for Rc<T> {
    #[inline]
    fn write(&self, stream: &mut BitWriteStream<E>) -> Result<()> {
        stream.write(self.as_ref())
    }
}

impl<T: BitWrite<E>, E: Endianness> BitWrite<E> for Arc<T> {
    #[inline]
    fn write(&self, stream: &mut BitWriteStream<E>) -> Result<()> {
        stream.write(self.as_ref())
    }
}

impl<T: BitWrite<E>, E: Endianness> BitWrite<E> for Vec<T> {
    #[inline]
    fn write(&self, stream: &mut BitWriteStream<E>) -> Result<()> {
        for item in self {
            stream.write(item)?;
        }
        Ok(())
    }
}

macro_rules! impl_write_tuple {
    ($($i:tt: $type:ident),*) => {
        impl<'a, E: Endianness, $($type: BitWrite<E>),*> BitWrite<E> for ($($type),*) {
            #[inline]
            fn write(&self, stream: &mut BitWriteStream<E>) -> Result<()> {
                $(self.$i.write(stream)?;)*
                Ok(())
            }
        }
    };
}

impl_write_tuple!(0: T1, 1: T2);
impl_write_tuple!(0: T1, 1: T2, 2: T3);
impl_write_tuple!(0: T1, 1: T2, 2: T3, 3: T4);

/// Trait for types that can be written to a stream, requiring the size to be configured
///
/// The meaning of the set sized depends on the type being written (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 [`BitWrite`] or `BitWriteSized`
///
/// The struct is written field by field in the order they are defined in, if the size for a field is set [`stream.write_sized()`][write_sized]
/// will be used, otherwise [`stream.write()`][write] 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"`
///
/// ## Examples
///
/// ```
/// # use bitbuffer::BitWriteSized;
/// #
/// #[derive(BitWriteSized, 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 [`BitWrite`] or `BitWriteSized`
///
/// The enum is written by first writing a set number of bits as the discriminant of the enum, then the variant is written.
///
/// For details about setting the input size for fields implementing `BitWriteSized` 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 bitbuffer::BitWriteSized;
/// #
/// #[derive(BitWriteSized)]
/// #[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),
/// }
/// ```
///
/// [write_sized]: BitReadStream::write_sized
/// [write]: BitReadStream::write
pub trait BitWriteSized<E: Endianness> {
    /// Write the type to stream
    fn write_sized(&self, stream: &mut BitWriteStream<E>, len: usize) -> Result<()>;
}

impl<E: Endianness> BitWriteSized<E> for str {
    #[inline]
    fn write_sized(&self, stream: &mut BitWriteStream<E>, len: usize) -> Result<()> {
        stream.write_string(self, Some(len))
    }
}

impl<E: Endianness> BitWriteSized<E> for String {
    #[inline]
    fn write_sized(&self, stream: &mut BitWriteStream<E>, len: usize) -> Result<()> {
        stream.write_string(self, Some(len))
    }
}

macro_rules! impl_write_sized_int {
    ($type:ty) => {
        impl<E: Endianness> BitWriteSized<E> for $type {
            #[inline]
            fn write_sized(&self, stream: &mut BitWriteStream<E>, len: usize) -> Result<()> {
                stream.write_int::<$type>(*self, len)
            }
        }
    };
}

impl_write_sized_int!(u8);
impl_write_sized_int!(u16);
impl_write_sized_int!(u32);
impl_write_sized_int!(u64);
impl_write_sized_int!(u128);
impl_write_sized_int!(usize);
impl_write_sized_int!(i8);
impl_write_sized_int!(i16);
impl_write_sized_int!(i32);
impl_write_sized_int!(i64);
impl_write_sized_int!(i128);
impl_write_sized_int!(isize);

impl<E: Endianness> BitWriteSized<E> for BitReadStream<'_, E> {
    #[inline]
    fn write_sized(&self, stream: &mut BitWriteStream<E>, len: usize) -> Result<()> {
        let bits = self.clone().read_bits(len)?;
        stream.write_bits(&bits)
    }
}

impl<E: Endianness, T: BitWriteSized<E>, const N: usize> BitWriteSized<E> for [T; N] {
    #[inline]
    fn write_sized(&self, stream: &mut BitWriteStream<E>, len: usize) -> Result<()> {
        for element in self.iter() {
            stream.write_sized(element, len)?;
        }
        Ok(())
    }
}

impl<T: BitWriteSized<E>, E: Endianness> BitWriteSized<E> for Box<T> {
    #[inline]
    fn write_sized(&self, stream: &mut BitWriteStream<E>, len: usize) -> Result<()> {
        stream.write_sized(self.as_ref(), len)
    }
}

impl<T: BitWriteSized<E>, E: Endianness> BitWriteSized<E> for Rc<T> {
    #[inline]
    fn write_sized(&self, stream: &mut BitWriteStream<E>, len: usize) -> Result<()> {
        stream.write_sized(self.as_ref(), len)
    }
}

impl<T: BitWriteSized<E>, E: Endianness> BitWriteSized<E> for Arc<T> {
    #[inline]
    fn write_sized(&self, stream: &mut BitWriteStream<E>, len: usize) -> Result<()> {
        stream.write_sized(self.as_ref(), len)
    }
}