From e4e12c984ba1b90a06906c78978c466d0e661447 Mon Sep 17 00:00:00 2001 From: Victor Koenders Date: Thu, 14 Oct 2021 19:34:35 +0200 Subject: [PATCH] Added support for the bool type --- src/de/impls.rs | 10 ++++++++++ src/enc/impls.rs | 6 ++++++ src/error.rs | 3 +++ tests/basic_types.rs | 3 +++ 4 files changed, 22 insertions(+) diff --git a/src/de/impls.rs b/src/de/impls.rs index 3fee1ac..7f683f0 100644 --- a/src/de/impls.rs +++ b/src/de/impls.rs @@ -1,6 +1,16 @@ use super::{BorrowDecodable, BorrowDecode, Decodable, Decode}; use crate::error::DecodeError; +impl<'de> Decodable for bool { + fn decode(mut decoder: D) -> Result { + match decoder.decode_u8()? { + 0 => Ok(false), + 1 => Ok(true), + x => Err(DecodeError::InvalidBooleanValue(x)), + } + } +} + impl<'de> Decodable for u8 { fn decode(mut decoder: D) -> Result { decoder.decode_u8() diff --git a/src/enc/impls.rs b/src/enc/impls.rs index eed2f03..5b57ea6 100644 --- a/src/enc/impls.rs +++ b/src/enc/impls.rs @@ -1,6 +1,12 @@ use super::{Encode, Encodeable}; use crate::error::EncodeError; +impl Encodeable for bool { + fn encode(&self, mut encoder: E) -> Result<(), EncodeError> { + encoder.encode_u8(if *self { 1 } else { 0 }) + } +} + impl Encodeable for u8 { fn encode(&self, mut encoder: E) -> Result<(), EncodeError> { encoder.encode_u8(*self) diff --git a/src/error.rs b/src/error.rs index e5279db..86c36ee 100644 --- a/src/error.rs +++ b/src/error.rs @@ -49,6 +49,9 @@ pub enum DecodeError { /// The decoder tried to decode a `char` and failed. The given buffer contains the bytes that are read at the moment of failure. InvalidCharEncoding([u8; 4]), + + /// The decoder tried to decode a `bool` and failed. The given value is what is actually read. + InvalidBooleanValue(u8), } /// Integer types. Used by [DecodeError]. These types have no purpose other than being shown in errors. diff --git a/tests/basic_types.rs b/tests/basic_types.rs index b8c5132..7b270a6 100644 --- a/tests/basic_types.rs +++ b/tests/basic_types.rs @@ -75,6 +75,9 @@ fn test_numbers() { the_same(5.0f32); the_same(5.0f64); + the_same(true); + the_same(false); + for char in "aÀÁÂÃÄÅÆÇÈÉÊËÌÍÎÏÐÑÒÓÔÕÖרÙÚÛÜÝÞßàáâãäåæçèéêëìíîïðñòóôõö文".chars() { the_same(char);