toe_beans/v4/message/options/
address_list.rs

1use serde::{Deserialize, Serialize};
2use std::net::Ipv4Addr;
3
4/// This represents one of several Message options that takes a list of Ipv4Addr values.
5#[derive(Debug, PartialEq, Serialize, Deserialize, Clone)]
6pub struct AddressListOption(Vec<Ipv4Addr>);
7
8impl AddressListOption {
9    /// Create an `AddressList` directly from a `Vec<Ipv4Addr>`.
10    pub fn new(list: Vec<Ipv4Addr>) -> Self {
11        Self(list)
12    }
13
14    /// Used, when serializing, to add to the byte buffer.
15    #[inline]
16    pub fn extend_into(&self, bytes: &mut Vec<u8>, tag: u8) {
17        bytes.push(tag); // tag
18        bytes.push((self.0.len() * 4) as u8); // length, multiples of 4, min 4
19        self.0
20            .iter()
21            .for_each(|ip| bytes.extend_from_slice(&ip.octets())); // value
22    }
23
24    /// Get the `Vec<Ipv4Addr>` this type wraps.
25    pub fn inner(self) -> Vec<Ipv4Addr> {
26        self.0
27    }
28}
29
30impl Into<String> for AddressListOption {
31    fn into(self) -> String {
32        format!("{:?}", self.0)
33    }
34}
35
36impl From<&[u8]> for AddressListOption {
37    fn from(value: &[u8]) -> Self {
38        Self(
39            value
40                .chunks(4)
41                .map(|chunk| Ipv4Addr::new(chunk[0], chunk[1], chunk[2], chunk[3]))
42                .collect(),
43        )
44    }
45}