jbaublitz / neli

Rust type safe netlink library
BSD 3-Clause "New" or "Revised" License
180 stars 35 forks source link

Support FromBytes for [u8; N] #210

Open isomer opened 1 year ago

isomer commented 1 year ago

Would adding this feature cause a breaking change? No

Is your feature request related to a problem? Please describe.

Some attributes return fixed length byte arrays. (eg a mac address, [u8;6], or the 802.11 VHT MCS Set [u8;32] etc). Some types (eg IP Addresses) have conversions from fixed sized arrays, but not from slices.

Describe the solution you'd like

I would like attr.get_payload_as::<[u8;32]>() to work, which I think is approximately:

impl<const N: usize> FromBytes for [u8;N] { ... }
impl<const N: usize> ToBytes for [u8;N] { ... }
impl<const N: usize> Size for [u8;N] { ... }

(I don't understand the difference between FromBytes and FromBytesWithInput, maybe this should be the WithInput variant? I dunno. This also means I don't understand when to use .get_payload_as() vs .get_payload_as_with_len())

It might also be possible (although I imagine a bit tricker to implement in an efficient manner) to have:

impl<const N: usize, T: Size + FromBytes> FromBytes for [T; N] { ... }
impl<const N: usize, T: Size + ToBytes> ToBytes for [T;N] { ... }
impl<const N: usize, T: Size + FromBytes> Size for [T; N] { ... }

which would allow for arbitrary arrays of u8, u16, u32 and even more complex types. (Interface counters are often returned as arrays of u32 or u64 for instance).

Describe alternatives you've considered Currently I get the reference to the slice, then use TryFrom to convert it to the correct sized array but this includes an extra error type that couldn't occur if get_payload_as() had returned the correct size.

jbaublitz commented 1 year ago

Hi @isomer! I can likely include this in the final release of 0.7.0. I'll try to put up a PR with code that you can comment on and test soon.