From 13f50306a50c9ea21e1e72aeb1ce43c3fecc56b0 Mon Sep 17 00:00:00 2001 From: Emil Fresk Date: Sun, 4 Aug 2024 14:25:52 +0200 Subject: [PATCH] Add `map::Value` imps for `bool` and `Option` --- CHANGELOG.md | 2 ++ src/map.rs | 36 ++++++++++++++++++++++++++++++++++++ 2 files changed, 38 insertions(+) diff --git a/CHANGELOG.md b/CHANGELOG.md index 1625e0e..8d9ca63 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -4,6 +4,8 @@ ## Unreleased +- Added `Value` impls for `bool` and `Option` + ## 3.0.1 25-07-24 - Add `defmt` attributes to cache types. diff --git a/src/map.rs b/src/map.rs index 5e7f59f..8cd72b0 100644 --- a/src/map.rs +++ b/src/map.rs @@ -803,6 +803,42 @@ impl<'a, const N: usize> Value<'a> for [u8; N] { } } +impl<'a> Value<'a> for bool { + fn serialize_into(&self, buffer: &mut [u8]) -> Result { + ::serialize_into(&(*self as u8), buffer) + } + + fn deserialize_from(buffer: &'a [u8]) -> Result + where + Self: Sized, + { + Ok(::deserialize_from(buffer)? != 0) + } +} + +impl<'a, T: Value<'a>> Value<'a> for Option { + fn serialize_into(&self, buffer: &mut [u8]) -> Result { + if let Some(val) = self { + ::serialize_into(&1, buffer)?; + ::serialize_into(val, buffer) + } else { + ::serialize_into(&0, buffer) + } + } + + fn deserialize_from(buffer: &'a [u8]) -> Result + where + Self: Sized, + { + let descriminant = ::deserialize_from(buffer)?; + match descriminant { + 0 => Ok(None), + 1 => Ok(Some(::deserialize_from(buffer)?)), + _ => Err(SerializationError::InvalidFormat), + } + } +} + macro_rules! impl_map_item_num { ($int:ty) => { impl<'a> Value<'a> for $int {