Skip to content

Support nested array #348

@fengyc

Description

@fengyc

The code like below could not compile:

    #[derive(Debug, EtherCrabWireReadWrite)]
    #[wire(bits = 104)]
    struct Check {
        #[wire(bits = 32)]
        foo: u32,
        #[wire(bits = 24)]
        control: Inner,
        #[wire(bits = 48)]
        status: [Inner; 2],
    }

    #[derive(Debug, Copy, Clone, EtherCrabWireReadWrite)]
    #[wire(bits = 24)]
    struct Inner {
        #[wire(bits = 1)]
        yes: bool,
        #[wire(bits = 1)]
        no: bool,
        #[wire(pre_skip = 6, bits = 16)]
        stuff: u16,
    }

The error:

error[E0277]: the trait bound `[Inner; 2]: EtherCrabWireWrite` is not satisfied
  --> src/ethercat.rs:40:14
   |
40 |     control: [Inner; 2],
   |              ^^^^^^^^^^ the trait `EtherCrabWireWrite` is not implemented for `[Inner; 2]`
   |
   = help: the following other types implement trait `EtherCrabWireWrite`:
             &[u8]
             [u8; N]

Is it possible to support nested array? for example, replace the impl for [u8; N] with:

impl<const N: usize, T> EtherCrabWireWrite for [T; N]
where
    T: EtherCrabWireWrite,
{
    fn pack_to_slice_unchecked<'buf>(&self, buf: &'buf mut [u8]) -> &'buf [u8] {
        if N == 0 {
            return &mut buf[0..0];
        }
        let chunk_size = self[0].packed_len();
        let buf = &mut buf[0..self.packed_len()];
        let mut chunk = &mut buf[..];
        for i in 0..N {
            let _ = EtherCrabWireWrite::pack_to_slice_unchecked(&self[i], chunk);
            chunk = &mut chunk[chunk_size..];
        }
        buf
    }

    fn packed_len(&self) -> usize {
        if N == 0 {
            return 0;
        }
        N * self[0].packed_len()
    }
}

Metadata

Metadata

Assignees

No one assigned

    Labels

    featureNew feature or request

    Type

    No type
    No fields configured for issues without a type.

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions