deku icon indicating copy to clipboard operation
deku copied to clipboard

Initial version of `as` attribute

Open coolreader18 opened this issue 3 years ago • 2 comments

Resolves #225.

Here's an initial draft of the "as" attribute, let me know what you think. Note that as of tomorrow, I'll be going to summer camp, so I may not be able to work on this very much; sorry about that :sweat_smile: It should really just be docs though, unless you want this initial PR to contain types that implement DekuRead/WriteAs as well.

coolreader18 avatar Jun 13 '21 01:06 coolreader18

This is neat! Thanks for making a PR. I'll give it a review shortly!

I propose adding an example, here's something I came up with to try it out. Feel free to add it to the PR.

use deku::prelude::*;
use std::net::Ipv4Addr;

#[derive(Debug, PartialEq, DekuRead, DekuWrite)]
struct Data {
    // Type does not implement DekuRead or DekuWrite
    #[deku(as = "MyIpAddr")]
    address: Ipv4Addr,
}

impl<'a> deku::DekuReadAs<'a, Ipv4Addr> for MyIpAddr {
    fn read_as(
        input: &'a deku::bitvec::BitSlice<deku::bitvec::Msb0, u8>,
        ctx: (),
    ) -> Result<(&'a deku::bitvec::BitSlice<deku::bitvec::Msb0, u8>, Ipv4Addr), DekuError> {
        u32::read(input, ctx).map(|(rest, v)| (rest, Ipv4Addr::from(v)))
    }
}

impl deku::DekuWriteAs<Ipv4Addr> for MyIpAddr {
    fn write_as(
        source: &Ipv4Addr,
        output: &mut deku::bitvec::BitVec<deku::bitvec::Msb0, u8>,
        ctx: (),
    ) -> Result<(), DekuError> {
        let ip: u32 = (*source).into();
        ip.write(output, ctx)
    }
}

struct MyIpAddr {}

fn main() {
    let data = Data {
        address: "127.0.0.1".parse().unwrap(),
    };

    let data_write = data.to_bytes().unwrap();
    assert_eq!(vec![1, 0, 0, 127], data_write);

    let (_rest, data_read) = Data::from_bytes((&data_write, 0)).unwrap();
    assert_eq!(data, data_read);
}

sharksforarms avatar Jun 15 '21 14:06 sharksforarms

Hey @coolreader18 just a friendly ping! Are you still interested in working on this?

sharksforarms avatar Jul 10 '21 02:07 sharksforarms