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
#![deny(missing_docs)]

/*!
This crate simplifies writing data to and reading data from streams.
You just need to implement the traits `ToStream` and `FromStream`.
You might have to implement value specific traits to custom settings types.
**/

mod arrays;
mod bool;
/// Settings for collection streaming.
pub mod collections;
/// Settings for number streaming.
pub mod numbers;
mod wrappers;

use std::io::{Read, Write};

#[derive(Debug)]
/// The error type when writing data to a stream.
pub enum WriteError {
    /// Stream interaction failed.
    Stream,
}

#[derive(Debug)]
/// The error type when reading data from stream.
pub enum ReadError {
    /// Stream interaction failed.
    Stream,
    /// An invalid byte was found.
    Invalid,
}

#[derive(Debug)]
/// The error type when reading and writing data to and from stream.
pub enum Error {
    /// The error occured during writing.
    Write(WriteError),
    /// The error occured during reading.
    Read(ReadError),
}

impl From<WriteError> for Error {
    fn from(error: WriteError) -> Error {
        Error::Write(error)
    }
}

impl From<ReadError> for Error {
    fn from(error: ReadError) -> Error {
        Error::Read(error)
    }
}

/// A trait for types, which can be written to streams.
/// Most argument types might need some settings.
pub trait ToStream<S> {
    /// Writes a value of this type to a stream. Return an error on failure.
    fn to_stream<W: Write>(&self, stream: &mut W) -> Result<(), WriteError>;
}

/// A trait for types, which can be read from streams.
pub trait FromStream<S>: Sized {
    /// Reads a value of this type from a stream and returns it. Returns an error on failure instead.
    fn from_stream<R: Read>(stream: &mut R) -> Result<Self, ReadError>;
}

#[inline(always)]
/// A simple function to write a value to a stream.
pub fn to_stream<S, V: ToStream<S>, W: Write>(value: &V, stream: &mut W) -> Result<(), WriteError> {
    value.to_stream(stream)
}

#[inline(always)]
/// A simple function to read a value from a stream.
pub fn from_stream<S, V: FromStream<S>, R: Read>(stream: &mut R) -> Result<V, ReadError> {
    V::from_stream(stream)
}

/// Some simple default settings for streaming.
pub mod default_settings;