diff options
author | Curly Bryce <curlybryce@protonmail.com> | 2024-07-03 19:13:13 -0600 |
---|---|---|
committer | Curly Bryce <curlybryce@protonmail.com> | 2024-07-03 19:13:13 -0600 |
commit | c06632d0dfdb19e047ae1175a46b926e6772650f (patch) | |
tree | ca41cd0637af6d21a850b88cc0b8d143a06d0014 /src/uid.rs | |
parent | 99f49f5bedbf9cdd3ccdd689da3acb4fe8ff685e (diff) | |
download | poko_server-c06632d0dfdb19e047ae1175a46b926e6772650f.tar.gz poko_server-c06632d0dfdb19e047ae1175a46b926e6772650f.tar.bz2 poko_server-c06632d0dfdb19e047ae1175a46b926e6772650f.zip |
Serialize, Deserialize UID to make coding easier
Diffstat (limited to 'src/uid.rs')
-rw-r--r-- | src/uid.rs | 78 |
1 files changed, 65 insertions, 13 deletions
@@ -1,24 +1,76 @@ -use serde::{Deserialize, Serialize}; +use base16ct::lower; +use rocket::request::FromParam; +use serde::{de::{IntoDeserializer, Visitor}, ser::SerializeTupleStruct, Deserialize, Deserializer, Serialize}; -#[derive(Debug, Serialize, Deserialize, Clone, Copy, PartialEq, Eq)] +#[derive(Debug, Clone, Copy, PartialEq, Eq)] pub struct UID(u8, u8); -impl UID { - pub fn to_hex(&self) -> String { - hex::encode_upper(vec![self.0, self.1]) +pub const EMPTY_UID: UID = UID(0,0); +struct UIDVisitor; +impl<'de> Visitor<'de> for UIDVisitor { + type Value = UID; + + fn expecting(&self, formatter: &mut std::fmt::Formatter) -> std::fmt::Result { + formatter.write_str("A Hex String containing 2 bytes") } - pub fn from(s: String) -> Result<Self, String> { - if s.is_ascii() { - if s.len() == 4 { - match hex::decode(s) { + + fn visit_str<E>(self, v: &str) -> Result<Self::Value, E> + where + E: serde::de::Error, { + println!("TEST"); + if v.is_ascii() { + if v.len() == 4 { + match hex::decode(v) { Ok(n) => Ok(UID(n[0], n[1])), - Err(_) => Err("Could not decode hex".into()) + Err(_) => panic!() + } + } else { + println!("NOT"); + panic!() + } + } else { + panic!() + } + } +} +impl<'de> Deserialize<'de> for UID { + fn deserialize<D>(deserializer: D) -> Result<Self, D::Error> + where + D: serde::Deserializer<'de> { + println!("TEST2"); + deserializer.deserialize_str(UIDVisitor) + } +} +impl From<&str> for UID { + fn from(value: &str) -> Self { + if value.is_ascii() { + if value.len() == 4 { + match hex::decode(value) { + Ok(n) => UID(n[0], n[1]), + Err(_) => panic!("Could not decode hex") } - } else { - Err("UID length is incorrect".into()) + panic!(); } } else { - Err("UID String is not valid".into()) + panic!(); + } + } +} +impl Serialize for UID { + fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error> + where + S: serde::Serializer { + serializer.serialize_str(&lower::encode_string(&[self.0, self.1])) + } +} +impl<'a> FromParam<'a> for UID { + type Error = &'a str; + + fn from_param(param: &'a str) -> Result<Self, Self::Error> { + let x: Result<UID, serde_json::Error> = param.into_deserializer().deserialize_str(UIDVisitor); + match x { + Ok(n) => Ok(n), + Err(_) => Err("Could not convert param using deserializer"), } } } |