From 5d665608cb72794763055fb0b83592c088ce4cdb Mon Sep 17 00:00:00 2001 From: Djordje Nedic Date: Thu, 15 Feb 2024 12:38:23 +0100 Subject: [PATCH] Add conversions between DataBits, StopBits and their numeric representation --- CHANGELOG.md | 1 + src/lib.rs | 46 ++++++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 47 insertions(+) diff --git a/CHANGELOG.md b/CHANGELOG.md index 79ededc9..13b25a8a 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -7,6 +7,7 @@ project adheres to [Semantic Versioning](https://semver.org/). ## [Unreleased] ### Added +* Added conversions between `DataBits`, `StopBits` types and their numeric representations ### Changed ### Fixed * Fixes a bug where `available_ports()` returned disabled devices on Windows. diff --git a/src/lib.rs b/src/lib.rs index 27326248..47ecffbd 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -160,6 +160,31 @@ impl fmt::Display for DataBits { } } +impl From for u8 { + fn from(value: DataBits) -> Self { + match value { + DataBits::Five => 5, + DataBits::Six => 6, + DataBits::Seven => 7, + DataBits::Eight => 8, + } + } +} + +impl TryFrom for DataBits { + type Error = (); + + fn try_from(value: u8) -> core::result::Result { + match value { + 5 => Ok(Self::Five), + 6 => Ok(Self::Six), + 7 => Ok(Self::Seven), + 8 => Ok(Self::Eight), + _ => Err(()), + } + } +} + /// Parity checking modes /// /// When parity checking is enabled (`Odd` or `Even`) an extra bit is transmitted with @@ -214,6 +239,27 @@ impl fmt::Display for StopBits { } } +impl From for u8 { + fn from(value: StopBits) -> Self { + match value { + StopBits::One => 1, + StopBits::Two => 2, + } + } +} + +impl TryFrom for StopBits { + type Error = (); + + fn try_from(value: u8) -> core::result::Result { + match value { + 1 => Ok(Self::One), + 2 => Ok(Self::Two), + _ => Err(()), + } + } +} + /// Flow control modes #[derive(Debug, Copy, Clone, PartialEq, Eq)] #[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]