5 releases (stable)

3.0.0 Sep 7, 2020
2.1.0 Mar 4, 2019
2.0.0 Feb 28, 2019
1.0.0 Oct 10, 2018
0.1.0 Oct 10, 2018

#1249 in Encoding

Download history 6288/week @ 2023-11-30 6096/week @ 2023-12-07 4941/week @ 2023-12-14 2450/week @ 2023-12-21 2306/week @ 2023-12-28 3675/week @ 2024-01-04 4345/week @ 2024-01-11 4477/week @ 2024-01-18 4706/week @ 2024-01-25 4731/week @ 2024-02-01 4618/week @ 2024-02-08 5389/week @ 2024-02-15 4526/week @ 2024-02-22 4307/week @ 2024-02-29 5490/week @ 2024-03-07 3694/week @ 2024-03-14

18,920 downloads per month
Used in 11 crates (5 directly)

Apache-2.0

7KB

Workflow Status Average time to resolve an issue Percentage of issues still open Maintenance

codicon

Traits for encoding and decoding.

This crate provides generic traits for encoding and decoding to a std::io::Read or std::io::Write type, respectively.

We often need to express that a type can be encoded or decoded. We also need a way to express the type of the encoding or decoding as well as parameters that may be used for that encoding or decoding. This tiny crate solves this problem.

Examples

Let's say we want u8 to be able to be encoded in a (made up) format Foo which simply writes the byte without modification. We can express this encoding as follows:

use codicon::*;

struct Foo;

impl Encoder<Foo> for u8 {
    type Error = std::io::Error;

    fn encode(&self, mut writer: impl Write, params: Foo) -> std::io::Result<()> {
        writer.write_all(std::slice::from_ref(self))?;
        Ok(())
    }
}

let mut buf = [0u8; 1];
7u8.encode(&mut buf.as_mut(), Foo).unwrap();
assert_eq!(buf[0], 7u8);

Note that we used a unit struct because the Foo encoding doesn't take any options. But if you wanted to specify encoding options, you could just make a type with parameters.

Decoding works the same as encoding:

use codicon::*;

struct Foo;

impl Decoder<Foo> for u8 {
    type Error = std::io::Error;

    fn decode(mut reader: impl Read, params: Foo) -> std::io::Result<Self> {
        let mut byte = 0u8;
        reader.read_exact(std::slice::from_mut(&mut byte))?;
        Ok(byte)
    }
}

let buf = [7u8; 1];
assert_eq!(u8::decode(&mut buf.as_ref(), Foo).unwrap(), 7u8);

License: Apache-2.0

No runtime deps