use serde::{Deserialize, Serialize};

/// Represents a tokenized selector for a value in a JSON object.
#[derive(Debug, PartialEq, Eq, Serialize, Deserialize, Clone, Copy)]
#[serde(transparent)]
pub struct TokenizedSelector(
    #[serde(
        serialize_with = "hex::serde::serialize",
        deserialize_with = "hex_decode_array"
    )]
    pub(crate) [u8; 16],
);

impl TokenizedSelector {
    pub fn as_bytes(&self) -> [u8; 16] {
        self.0
    }
}

fn hex_decode_array<'de, D>(deserializer: D) -> Result<[u8; 16], D::Error>
where
    D: serde::Deserializer<'de>,
{
    let s = String::deserialize(deserializer)?;
    let mut out: [u8; 16] = [0; 16];
    hex::decode_to_slice(s, &mut out).map_err(serde::de::Error::custom)?;
    Ok(out)
}
