Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Implement serde traits and Hash for Code #5

Merged
merged 3 commits into from Mar 25, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
8 changes: 6 additions & 2 deletions .github/workflows/rust.yml
Expand Up @@ -14,10 +14,14 @@ jobs:

steps:
- uses: actions/checkout@v4
- name: Build
- name: Build with all features
run: cargo build --all-features
- name: Run tests
- name: Run tests with all features
run: cargo test --all-features
- name: Build with no features
run: cargo build --no-default-features
- name: Run tests with no features
run: cargo test --no-default-features
- name: Run clippy
uses: actions-rs/clippy-check@v1
with:
Expand Down
8 changes: 8 additions & 0 deletions CHANGELOG.md
@@ -1,5 +1,13 @@
# Changelog

## Unreleased

### New features

- Implemented `Hash` for `Code`.
- Implemented `serde::Serialize` and `serde::Deserialize` for `Code`, behind new `serde` feature
flag.

## 0.1.0

Initial release.
6 changes: 6 additions & 0 deletions Cargo.toml
Expand Up @@ -11,6 +11,7 @@ categories = ["hardware-support", "parser-implementations"]

[dependencies]
thiserror = "1.0.30"
serde = { version = "1.0.197", optional = true }

[dev-dependencies]
cc1101 = { version = "0.1.3", features = ["std"] }
Expand All @@ -21,3 +22,8 @@ eyre = "0.6.9"
log = "0.4.20"
pretty_env_logger = "0.5.0"
rppal = { version = "0.17.1", features = ["hal"] }
serde_test = "1.0.176"

[features]
default = ["serde"]
serde = ["dep:serde"]
82 changes: 81 additions & 1 deletion src/lib.rs
Expand Up @@ -27,7 +27,7 @@ pub enum Error {
}

/// A decoded RF button code.
#[derive(Clone, Eq, PartialEq)]
#[derive(Clone, Eq, Hash, PartialEq)]
pub struct Code {
/// The decoded value.
pub value: u32,
Expand All @@ -45,6 +45,44 @@ impl Debug for Code {
}
}

#[cfg(feature = "serde")]
impl<'de> serde::Deserialize<'de> for Code {
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
where
D: serde::Deserializer<'de>,
{
let s = String::deserialize(deserializer)?;
if s.len() > 8 {
return Err(serde::de::Error::invalid_value(
serde::de::Unexpected::Str(&s),
&"no more than 8 characters",
));
}
let value =
u32::from_str_radix(&s, 16).map_err(|e| serde::de::Error::custom(e.to_string()))?;
Ok(Self {
value,
length: s.len() as u8 * 4,
})
}
}

#[cfg(feature = "serde")]
impl serde::Serialize for Code {
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
where
S: serde::Serializer,
{
if self.length % 4 != 0 {
return Err(serde::ser::Error::custom(
"Only codes with length a multiple of 4 can be serialized.",
));
}
let s = format!("{:01$x}", self.value, usize::from(self.length) / 4);
serializer.serialize_str(&s)
}
}

/// Given a sequence of pulse durations in microseconds (starting with a high pulse), try to decode
/// a button code.
pub fn decode(pulses: &[u16]) -> Result<Code, Error> {
Expand Down Expand Up @@ -153,4 +191,46 @@ mod tests {
})
);
}

#[cfg(feature = "serde")]
#[test]
fn serde_code() {
use serde_test::{assert_tokens, Token};

assert_tokens(
&Code {
value: 0,
length: 12,
},
&[Token::Str("000")],
);
assert_tokens(
&Code {
value: 0xf,
length: 4,
},
&[Token::Str("f")],
);
assert_tokens(
&Code {
value: 0x123456,
length: 24,
},
&[Token::Str("123456")],
);
assert_tokens(
&Code {
value: 0xabcdef,
length: 24,
},
&[Token::Str("abcdef")],
);
assert_tokens(
&Code {
value: 0xff112233,
length: 32,
},
&[Token::Str("ff112233")],
);
}
}