pipa-lang 1.0.0-alpha.1

A tiny template language
Documentation
// SPDX-FileCopyrightText: Copyright 2026 olav@occy.org
// SPDX-License-Identifier: MPL-2.0

use serde::Deserialize;
use serde::Serialize;

#[derive(Clone, Default, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize)]
pub struct Key(#[serde(with = "crate::serde::bytes_as_base64")] Vec<u8>);

impl core::fmt::Debug for Key {
    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
        f.debug_tuple("Key")
            .field(&String::from_utf8_lossy(&self.0))
            .finish()
    }
}

impl core::fmt::Display for Key {
    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
        write!(f, "{}", String::from_utf8_lossy(&self.0))
    }
}

impl AsRef<[u8]> for Key {
    fn as_ref(&self) -> &[u8] {
        &self.0
    }
}

impl<T: AsRef<[u8]>> PartialEq<T> for Key {
    fn eq(&self, other: &T) -> bool {
        self.as_ref() == other.as_ref()
    }
}

impl<'a> TryFrom<&'a Key> for &'a str {
    type Error = ();

    fn try_from(value: &'a Key) -> Result<Self, Self::Error> {
        core::str::from_utf8(&value.0).map_err(|_| ())
    }
}

impl From<usize> for Key {
    fn from(value: usize) -> Self {
        Self(value.to_string().into_bytes())
    }
}

impl From<&str> for Key {
    fn from(value: &str) -> Self {
        Self(value.to_string().into_bytes())
    }
}

impl From<String> for Key {
    fn from(value: String) -> Self {
        Self(value.into_bytes())
    }
}

impl From<&[u8]> for Key {
    fn from(value: &[u8]) -> Self {
        Self(value.to_vec())
    }
}

impl From<Key> for Vec<u8> {
    fn from(value: Key) -> Self {
        value.0
    }
}

impl Key {
    pub(crate) fn new(key: Vec<u8>) -> Self {
        Self(key)
    }

    pub(crate) fn is_empty(&self) -> bool {
        self.0.is_empty()
    }
}