use std::fmt::Display;
use serde::{Deserialize, Serialize};
use sha2::{Digest, Sha256};
use simd_json::{borrowed, derived::ValueTryIntoString, owned};
#[derive(Debug, PartialEq, Eq, Clone, Hash, Deserialize, Serialize)]
pub struct Label(pub(crate) String);
impl From<&str> for Label {
fn from(value: &str) -> Self {
Self(value.to_owned())
}
}
impl TryFrom<owned::Value> for Label {
type Error = value_parse::Error;
fn try_from(value: owned::Value) -> Result<Self, Self::Error> {
let string = value
.try_into_string()
.map_err(|err| value_parse::Error::StrExpected { err })?;
Ok(Self(string))
}
}
impl<'a> From<&'a Label> for borrowed::Value<'a> {
fn from(val: &'a Label) -> Self {
borrowed::Value::String(std::borrow::Cow::Borrowed(&val.0))
}
}
#[allow(missing_docs)]
pub mod value_parse {
#[derive(Debug, thiserror::Error)]
pub enum Error {
#[error("Expected string in json data, but found something else: {err}")]
StrExpected { err: simd_json::TryTypeError },
}
}
impl Display for Label {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
self.0.fmt(f)
}
}
impl Label {
#[must_use]
pub fn associate_color(&self) -> Color {
let colors = [
Color::from_rgba(244, 67, 54, 255), Color::from_rgba(233, 30, 99, 255), Color::from_rgba(156, 39, 176, 255), Color::from_rgba(103, 58, 183, 255), Color::from_rgba(63, 81, 181, 255), Color::from_rgba(33, 150, 243, 255), Color::from_rgba(3, 169, 244, 255), Color::from_rgba(0, 188, 212, 255), Color::from_rgba(0, 150, 136, 255), Color::from_rgba(76, 175, 80, 255), Color::from_rgba(139, 195, 74, 255), Color::from_rgba(205, 220, 57, 255), Color::from_rgba(255, 235, 59, 255), Color::from_rgba(255, 193, 7, 255), Color::from_rgba(255, 152, 0, 255), Color::from_rgba(255, 87, 34, 255), Color::from_rgba(121, 85, 72, 255), Color::from_rgba(158, 158, 158, 255), Color::from_rgba(96, 125, 139, 255), ];
let hash = Sha256::digest(self.to_string().as_bytes());
let id: usize = hash
.into_iter()
.map(|val| val as usize)
.fold(0, |acc, val| (acc + val) % colors.len());
colors[id]
}
}
#[derive(Default, Clone, Copy, Debug)]
pub struct Color {
pub red: u8,
pub green: u8,
pub blue: u8,
pub alpha: u8,
}
impl Color {
#[must_use]
pub fn from_rgba(red: u8, green: u8, blue: u8, alpha: u8) -> Self {
Self {
red,
green,
blue,
alpha,
}
}
}