1 //! Traits used in this library
2 use std::io;
3 
4 /// Configuration parameter trait.
5 ///
6 /// Use the list of implementors to see which parameters are available for which struct.
7 pub trait Parameter<Object> {
8     /// Result type of `set_param`.
9     // TODO: Use default type () when associated type defaults get stable.
10     type Result;
11     /// Sets `self` as a parameter of `Object`.
set_param(self, &mut Object) -> Self::Result12     fn set_param(self, &mut Object) -> Self::Result;
13 }
14 
15 /// Implemented for objects that have parameters.
16 ///
17 /// Provides a unified `set`-method to simplify the configuration.
18 pub trait SetParameter: Sized {
19     /// Sets `value` as a parameter of `self`.
set<T: Parameter<Self>>(&mut self, value: T) -> <T as Parameter<Self>>::Result20     fn set<T: Parameter<Self>>(&mut self, value: T) -> <T as Parameter<Self>>::Result {
21         value.set_param(self)
22     }
23 }
24 
25 impl<T> SetParameter for T {}
26 
27 /// Writer extension to write little endian data
28 pub trait WriteBytesExt<T> {
29     /// Writes `T` to a bytes stream. Least significant byte first.
write_le(&mut self, n: T) -> io::Result<()>30     fn write_le(&mut self, n: T) -> io::Result<()>;
31 
32     /*
33     #[inline]
34     fn write_byte(&mut self, n: u8) -> io::Result<()> where Self: Write {
35         self.write_all(&[n])
36     }
37     */
38 }
39 
40 impl<W: io::Write + ?Sized> WriteBytesExt<u8> for W {
41     #[inline]
write_le(&mut self, n: u8) -> io::Result<()>42     fn write_le(&mut self, n: u8) -> io::Result<()> {
43         self.write_all(&[n])
44 
45     }
46 }
47 
48 impl<W: io::Write + ?Sized> WriteBytesExt<u16> for W {
49     #[inline]
write_le(&mut self, n: u16) -> io::Result<()>50     fn write_le(&mut self, n: u16) -> io::Result<()> {
51         self.write_all(&[n as u8, (n>>8) as u8])
52 
53     }
54 }
55 
56 impl<W: io::Write + ?Sized> WriteBytesExt<u32> for W {
57     #[inline]
write_le(&mut self, n: u32) -> io::Result<()>58     fn write_le(&mut self, n: u32) -> io::Result<()> {
59         self.write_le(n as u16)?;
60         self.write_le((n >> 16) as u16)
61 
62     }
63 }
64 
65 impl<W: io::Write + ?Sized> WriteBytesExt<u64> for W {
66     #[inline]
write_le(&mut self, n: u64) -> io::Result<()>67     fn write_le(&mut self, n: u64) -> io::Result<()> {
68         self.write_le(n as u32)?;
69         self.write_le((n >> 32) as u32)
70 
71     }
72 }