Skip to content

Commit

Permalink
Change serde-cbor to minicbor (#69)
Browse files Browse the repository at this point in the history
  • Loading branch information
MathiasKoch authored Nov 21, 2024
1 parent 4fd33ab commit fdbf36a
Show file tree
Hide file tree
Showing 11 changed files with 47 additions and 44 deletions.
11 changes: 7 additions & 4 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -27,8 +27,11 @@ heapless = { version = "0.7.0", features = ["serde"] }
mqttrust = { version = "0.6" }
nb = "1"
serde = { version = "1.0.126", default-features = false, features = ["derive"] }
serde_cbor = { version = "^0.11", default-features = false, optional = true }
serde-json-core = { version = "0.4.0" }

minicbor = { version = "0.25", optional = true }
minicbor-serde = { version = "0.3.2", optional = true }

smlang = "0.5.0"
fugit-timer = "0.1.2"
shadow-derive = { path = "shadow_derive", version = "0.2.1" }
Expand All @@ -54,12 +57,12 @@ hex = "0.4.3"
[features]
default = ["ota_mqtt_data", "provision_cbor"]

provision_cbor = ["serde_cbor"]
provision_cbor = ["dep:minicbor", "dep:minicbor-serde"]

ota_mqtt_data = ["serde_cbor"]
ota_mqtt_data = ["dep:minicbor", "dep:minicbor-serde"]
ota_http_data = []

std = ["serde/std", "serde_cbor?/std"]
std = ["serde/std", "minicbor-serde?/std"]

defmt = ["dep:defmt", "mqttrust/defmt-impl", "heapless/defmt-impl"]

Expand Down
9 changes: 3 additions & 6 deletions rust-toolchain.toml
Original file line number Diff line number Diff line change
@@ -1,7 +1,4 @@
[toolchain]
channel = "nightly-2023-06-28"
components = [ "rust-src", "rustfmt", "llvm-tools-preview", "clippy" ]
targets = [
"x86_64-unknown-linux-gnu",
"thumbv7em-none-eabihf"
]
channel = "nightly-2024-09-06"
components = ["rust-src", "rustfmt", "llvm-tools-preview", "clippy"]
targets = ["x86_64-unknown-linux-gnu", "thumbv7em-none-eabihf"]
1 change: 1 addition & 0 deletions src/fmt.rs
Original file line number Diff line number Diff line change
Expand Up @@ -223,6 +223,7 @@ pub struct NoneError;
pub trait Try {
type Ok;
type Error;
#[allow(dead_code)]
fn into_result(self) -> Result<Self::Ok, Self::Error>;
}

Expand Down
2 changes: 0 additions & 2 deletions src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,5 @@ pub mod ota;
pub mod provisioning;
pub mod shadows;

pub use serde_cbor;

#[cfg(test)]
pub mod test;
2 changes: 1 addition & 1 deletion src/ota/data_interface/mqtt.rs
Original file line number Diff line number Diff line change
Expand Up @@ -181,7 +181,7 @@ where
payload: &'c mut [u8],
) -> Result<FileBlock<'c>, OtaError> {
Ok(
serde_cbor::de::from_mut_slice::<cbor::GetStreamResponse>(payload)
minicbor_serde::from_slice::<cbor::GetStreamResponse>(payload)
.map_err(|_| OtaError::Encoding)?
.into(),
)
Expand Down
7 changes: 4 additions & 3 deletions src/ota/encoding/cbor.rs
Original file line number Diff line number Diff line change
Expand Up @@ -76,9 +76,10 @@ pub fn to_slice<T>(value: &T, slice: &mut [u8]) -> Result<usize, ()>
where
T: serde::ser::Serialize,
{
let mut serializer = serde_cbor::ser::Serializer::new(serde_cbor::ser::SliceWrite::new(slice));
let mut serializer =
minicbor_serde::Serializer::new(minicbor::encode::write::Cursor::new(slice));
value.serialize(&mut serializer).map_err(|_| ())?;
Ok(serializer.into_inner().bytes_written())
Ok(serializer.into_encoder().writer().position())
}

impl<'a> From<GetStreamResponse<'a>> for FileBlock<'a> {
Expand Down Expand Up @@ -170,7 +171,7 @@ mod test {
0, 0, 0, 0, 0, 0, 255,
];

let response: GetStreamResponse = serde_cbor::de::from_mut_slice(payload).unwrap();
let response: GetStreamResponse = minicbor_serde::from_slice(payload).unwrap();

assert_eq!(
response,
Expand Down
10 changes: 8 additions & 2 deletions src/provisioning/error.rs
Original file line number Diff line number Diff line change
Expand Up @@ -27,8 +27,14 @@ impl From<serde_json_core::de::Error> for Error {
}
}

impl From<serde_cbor::Error> for Error {
fn from(_e: serde_cbor::Error) -> Self {
impl From<minicbor_serde::error::DecodeError> for Error {
fn from(_e: minicbor_serde::error::DecodeError) -> Self {
Self::DeserializeCbor
}
}

impl<E> From<minicbor_serde::error::EncodeError<E>> for Error {
fn from(_: minicbor_serde::error::EncodeError<E>) -> Self {
Self::Overflow
}
}
21 changes: 10 additions & 11 deletions src/provisioning/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -111,17 +111,18 @@ where
parameters,
};

let payload = &mut [0u8; 1024];
let mut payload = [0u8; 1024];

let payload_len = match self.payload_format {
#[cfg(feature = "provision_cbor")]
PayloadFormat::Cbor => {
let mut serializer =
serde_cbor::ser::Serializer::new(serde_cbor::ser::SliceWrite::new(payload));
let mut serializer = minicbor_serde::Serializer::new(
minicbor::encode::write::Cursor::new(&mut payload[..]),
);
register_request.serialize(&mut serializer)?;
serializer.into_inner().bytes_written()
serializer.into_encoder().writer().position()
}
PayloadFormat::Json => serde_json_core::to_slice(&register_request, payload)?,
PayloadFormat::Json => serde_json_core::to_slice(&register_request, &mut payload)?,
};

self.mqtt.publish(
Expand Down Expand Up @@ -151,7 +152,7 @@ where
let response = match format {
#[cfg(feature = "provision_cbor")]
PayloadFormat::Cbor => {
serde_cbor::de::from_mut_slice::<CreateKeysAndCertificateResponse>(payload)?
minicbor_serde::from_slice::<CreateKeysAndCertificateResponse>(payload)?
}
PayloadFormat::Json => {
serde_json_core::from_slice::<CreateKeysAndCertificateResponse>(payload)?.0
Expand All @@ -173,7 +174,7 @@ where
let response = match format {
#[cfg(feature = "provision_cbor")]
PayloadFormat::Cbor => {
serde_cbor::de::from_mut_slice::<CreateCertificateFromCsrResponse>(payload)?
minicbor_serde::from_slice::<CreateCertificateFromCsrResponse>(payload)?
}
PayloadFormat::Json => {
serde_json_core::from_slice::<CreateCertificateFromCsrResponse>(payload)?.0
Expand All @@ -195,7 +196,7 @@ where
let response = match format {
#[cfg(feature = "provision_cbor")]
PayloadFormat::Cbor => {
serde_cbor::de::from_mut_slice::<RegisterThingResponse<'_, P>>(payload)?
minicbor_serde::from_slice::<RegisterThingResponse<'_, P>>(payload)?
}
PayloadFormat::Json => {
serde_json_core::from_slice::<RegisterThingResponse<'_, P>>(payload)?.0
Expand All @@ -217,9 +218,7 @@ where
) => {
let response = match format {
#[cfg(feature = "provision_cbor")]
PayloadFormat::Cbor => {
serde_cbor::de::from_mut_slice::<ErrorResponse>(payload)?
}
PayloadFormat::Cbor => minicbor_serde::from_slice::<ErrorResponse>(payload)?,
PayloadFormat::Json => serde_json_core::from_slice::<ErrorResponse>(payload)?.0,
};

Expand Down
18 changes: 8 additions & 10 deletions src/shadows/dao.rs
Original file line number Diff line number Diff line change
Expand Up @@ -9,11 +9,11 @@ pub trait ShadowDAO<S: Serialize + DeserializeOwned> {

impl<S: Serialize + DeserializeOwned> ShadowDAO<S> for () {
fn read(&mut self) -> Result<S, Error> {
Err(Error::NoPersistance)
Err(Error::NoPersistence)
}

fn write(&mut self, _state: &S) -> Result<(), Error> {
Err(Error::NoPersistance)
Err(Error::NoPersistence)
}
}

Expand Down Expand Up @@ -58,10 +58,8 @@ where
}

Ok(
serde_cbor::de::from_mut_slice::<S>(
&mut buf[U32_SIZE..len as usize + U32_SIZE],
)
.map_err(|_| Error::InvalidPayload)?,
minicbor_serde::from_slice::<S>(&mut buf[U32_SIZE..len as usize + U32_SIZE])

Check warning on line 61 in src/shadows/dao.rs

View workflow job for this annotation

GitHub Actions / clippy

the function `minicbor_serde::from_slice<S>` doesn't need a mutable reference

warning: the function `minicbor_serde::from_slice<S>` doesn't need a mutable reference --> src/shadows/dao.rs:61:53 | 61 | minicbor_serde::from_slice::<S>(&mut buf[U32_SIZE..len as usize + U32_SIZE]) | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ | = help: for further information visit https://rust-lang.github.io/rust-clippy/master/index.html#unnecessary_mut_passed = note: `#[warn(clippy::unnecessary_mut_passed)]` on by default
.map_err(|_| Error::InvalidPayload)?,
)
}
_ => Err(Error::InvalidPayload),
Expand All @@ -73,14 +71,14 @@ where

let buf = &mut [0u8; S::MAX_PAYLOAD_SIZE + U32_SIZE];

let mut serializer = serde_cbor::ser::Serializer::new(serde_cbor::ser::SliceWrite::new(
let mut serializer = minicbor_serde::Serializer::new(minicbor::encode::write::Cursor::new(
&mut buf[U32_SIZE..],
))
.packed_format();
));

state
.serialize(&mut serializer)
.map_err(|_| Error::InvalidPayload)?;
let len = serializer.into_inner().bytes_written();
let len = serializer.into_encoder().writer().position();

if len > S::MAX_PAYLOAD_SIZE {
return Err(Error::Overflow);
Expand Down
2 changes: 1 addition & 1 deletion src/shadows/error.rs
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@ use super::data_types::ErrorResponse;
#[cfg_attr(feature = "defmt", derive(defmt::Format))]
pub enum Error {
Overflow,
NoPersistance,
NoPersistence,
DaoRead,
DaoWrite,
InvalidPayload,
Expand Down
8 changes: 4 additions & 4 deletions src/shadows/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -194,7 +194,7 @@ where
self.handler.should_handle_topic(topic)
}

/// Handle incomming publish messages from the cloud on any topics relevant
/// Handle incoming publish messages from the cloud on any topics relevant
/// for this particular shadow.
///
/// This function needs to be fed all relevant incoming MQTT payloads in
Expand Down Expand Up @@ -343,10 +343,10 @@ where
/// and depending on whether the state update is rejected or accepted, it
/// will automatically update the local version after response
///
/// The returned `bool` from the update closure will determine wether the
/// The returned `bool` from the update closure will determine whether the
/// update is persisted using the `DAO`, or just updated in the cloud. This
/// can be handy for activity or status field updates that are not relevant
/// to store persistant on the device, but are required to be part of the
/// to store persistent on the device, but are required to be part of the
/// same cloud shadow.
pub fn update<F: FnOnce(&S, &mut S::PatchState) -> bool>(&mut self, f: F) -> Result<(), Error> {
let mut desired = S::PatchState::default();
Expand Down Expand Up @@ -404,7 +404,7 @@ where
self.handler.unsubscribe()
}

/// Handle incomming publish messages from the cloud on any topics relevant
/// Handle incoming publish messages from the cloud on any topics relevant
/// for this particular shadow.
///
/// This function needs to be fed all relevant incoming MQTT payloads in
Expand Down

0 comments on commit fdbf36a

Please sign in to comment.