From 3cb1aa0496810e35b12b25c39d5a231c42238457 Mon Sep 17 00:00:00 2001 From: trivernis Date: Tue, 1 Mar 2022 21:11:16 +0100 Subject: [PATCH] Add validation for serialization format Signed-off-by: trivernis --- src/hydrus_serializable/mod.rs | 25 +++++++++++++++++++------ src/hydrus_serializable/wrapper.rs | 15 +++++++++++++-- 2 files changed, 32 insertions(+), 8 deletions(-) diff --git a/src/hydrus_serializable/mod.rs b/src/hydrus_serializable/mod.rs index db86b78..bd6045f 100644 --- a/src/hydrus_serializable/mod.rs +++ b/src/hydrus_serializable/mod.rs @@ -15,10 +15,23 @@ pub trait HydrusSerializable: DeserializeOwned { fn type_id() -> u64; } +pub trait ConstNumberTrait { + fn value() -> u64; +} + +impl ConstNumberTrait for T +where + T: HydrusSerializable, +{ + fn value() -> u64 { + T::type_id() + } +} + #[derive(Clone, Debug)] -pub struct SerializableId(u64, PhantomData); +pub struct SerializableId(u64, PhantomData); -impl<'de, T: HydrusSerializable> Deserialize<'de> for SerializableId { +impl<'de, T: ConstNumberTrait> Deserialize<'de> for SerializableId { fn deserialize(deserializer: D) -> Result where D: Deserializer<'de>, @@ -29,11 +42,11 @@ impl<'de, T: HydrusSerializable> Deserialize<'de> for SerializableId { struct SerIdVisitor(PhantomData); -impl<'de, T: HydrusSerializable> Visitor<'de> for SerIdVisitor { +impl<'de, T: ConstNumberTrait> Visitor<'de> for SerIdVisitor { type Value = SerializableId; fn expecting(&self, formatter: &mut Formatter) -> std::fmt::Result { - write!(formatter, "an unsigned integer equal to {}", T::type_id()) + write!(formatter, "an unsigned integer equal to {}", T::value()) } fn visit_u8(self, v: u8) -> Result @@ -61,9 +74,9 @@ impl<'de, T: HydrusSerializable> Visitor<'de> for SerIdVisitor { where E: Error, { - let expected_value = T::type_id(); + let expected_value = T::value(); if v != expected_value { - Err(E::custom(format!("type not equal to {}", expected_value))) + Err(E::custom(format!("value not equal to {}", expected_value))) } else { Ok(SerializableId(expected_value, PhantomData)) } diff --git a/src/hydrus_serializable/wrapper.rs b/src/hydrus_serializable/wrapper.rs index 2d0bd97..1f7ffa4 100644 --- a/src/hydrus_serializable/wrapper.rs +++ b/src/hydrus_serializable/wrapper.rs @@ -1,10 +1,21 @@ -use crate::hydrus_serializable::{HydrusSerializable, SerializableId}; +use crate::hydrus_serializable::{ConstNumberTrait, HydrusSerializable, SerializableId}; use serde::Deserialize; +#[derive(Clone, Debug, Deserialize)] +pub struct VersionOne; + +impl ConstNumberTrait for VersionOne { + fn value() -> u64 { + 1 + } +} + #[derive(Clone, Debug, Deserialize)] #[serde(bound = "")] pub struct HydrusSerWrapper { + #[allow(unused)] pub type_id: SerializableId, - pub version: u8, + #[allow(unused)] + pub version: SerializableId, pub inner: T, }