ptcrab/data/
write_to.rs

1use duplicate::duplicate_item;
2use std::error::Error as StdError;
3use std::io::{Error as IoError, Seek, Write};
4
5//--------------------------------------------------------------------------------------------------
6
7/// Allows encoding `self` as bytes written to some sink.
8pub trait WriteTo {
9    /// Error type on write/seek failure.
10    type Error: StdError;
11
12    /// Encodes `self` as bytes and writes them to the given sink.
13    ///
14    /// Returns the stream position before writing.
15    fn write_to<W: Write + Seek>(&self, sink: &mut W) -> Result<u64, Self::Error>;
16}
17
18impl<const N: usize> WriteTo for [u8; N] {
19    type Error = IoError;
20
21    fn write_to<W: Write + Seek>(&self, sink: &mut W) -> Result<u64, Self::Error> {
22        sink.stream_position()
23            .and_then(|start_pos| sink.write_all(self).map(|_| start_pos))
24    }
25}
26
27#[duplicate_item(
28    _Num_;
29    [f32];
30    [i8];
31    [i16];
32    [i32];
33    [u8];
34    [u16];
35    [u32];
36)]
37impl WriteTo for _Num_ {
38    type Error = IoError;
39
40    fn write_to<W: Write + Seek>(&self, sink: &mut W) -> Result<u64, Self::Error> {
41        self.to_le_bytes().write_to(sink)
42    }
43}
44
45impl<X, Y> WriteTo for (X, Y)
46where
47    X: WriteTo<Error = IoError>,
48    Y: WriteTo<Error = IoError>,
49{
50    type Error = IoError;
51
52    fn write_to<W: Write + Seek>(&self, sink: &mut W) -> Result<u64, Self::Error> {
53        self.0
54            .write_to(sink)
55            .and_then(|start_pos| self.1.write_to(sink).map(|_| start_pos))
56    }
57}