use serde::{Deserialize, Serialize};
use std::net::Ipv4Addr;

/// This represents one of several Message options that takes an Ipv4Addr value.
#[derive(Debug, PartialEq, Serialize, Deserialize, Clone)]
pub struct AddressOption(Ipv4Addr);

impl AddressOption {
    /// Create an `AddressOption` directly from an `Ipv4Addr`.
    pub fn new(ip: Ipv4Addr) -> Self {
        Self(ip)
    }

    /// Used, when serializing, to add to the byte buffer.
    #[inline]
    pub fn extend_into(&self, bytes: &mut Vec<u8>, tag: u8) {
        bytes.push(tag); // tag
        bytes.push(4); // length
        bytes.extend_from_slice(&self.0.octets()); // value
    }

    /// Get the `Ipv4Addr` that this type wraps.
    pub fn inner(&self) -> Ipv4Addr {
        self.0
    }
}

impl From<&[u8]> for AddressOption {
    fn from(value: &[u8]) -> Self {
        Self(Ipv4Addr::new(value[0], value[1], value[2], value[3]))
    }
}
