Skip to content

Commit

Permalink
Merge pull request #52 from jklmnn/issue-51
Browse files Browse the repository at this point in the history
Make bytes dependency optional
  • Loading branch information
00imvj00 authored Feb 12, 2025
2 parents 0f1ce9d + 447a6a7 commit dd9d381
Show file tree
Hide file tree
Showing 9 changed files with 63 additions and 57 deletions.
10 changes: 6 additions & 4 deletions .github/workflows/master.yml
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,8 @@ jobs:
- uses: actions/checkout@v2
- name: Build
run: cargo build --verbose
- name: Check
run: cargo fmt -- --check
- name: Run tests
run: cargo test --verbose
- name: Build serde
Expand All @@ -23,18 +25,18 @@ jobs:
- name: Build no_std
run: cargo build --verbose --no-default-features
- name: Run tests no_std
run: cargo test --verbose --no-default-features
run: cargo test --verbose --no-default-features --tests --lib
- name: Build no_std
run: cargo build --verbose --no-default-features --features=derive
- name: Run tests no_std
run: cargo test --verbose --no-default-features --features=derive
run: cargo test --verbose --no-default-features --features=derive --tests --lib
- name: Build defmt
run: cargo build --verbose --no-default-features --features=defmt
- name: Run tests defmt
run: cargo test --verbose --no-default-features --features=defmt
run: cargo test --verbose --no-default-features --features=defmt --tests --lib
- name: Build defmt derive
run: cargo build --verbose --no-default-features --features=defmt --features=derive
- name: Run tests defmt derive
run: cargo test --verbose --no-default-features --features=defmt --features=derive
run: cargo test --verbose --no-default-features --features=defmt --features=derive --tests --lib


2 changes: 1 addition & 1 deletion Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,7 @@ std = ["bytes/std", "serde/std"]
defmt = ["dep:defmt", "heapless/defmt-03"]

[dependencies]
bytes = { version = "1.0", default-features = false}
bytes = { version = "1.0", default-features = false, optional = true }
serde = { version = "1.0", features = ["derive"], optional = true }
heapless = { version = "0.8" }
defmt = { version = "0.3.10", optional = true }
Expand Down
17 changes: 8 additions & 9 deletions src/connect.rs
Original file line number Diff line number Diff line change
@@ -1,20 +1,19 @@
use crate::{decoder::*, encoder::*, *};
use core::str::FromStr;
#[cfg(feature = "defmt")]
use defmt::Format;
use crate::{decoder::*, encoder::*, *};
#[cfg(not(feature = "std"))]
use heapless::String;
#[cfg(feature = "std")]
use std::string::String;
use core::str::FromStr;


/// Protocol version.
///
/// Sent in [`Connect`] packet.
///
/// [`Connect`]: struct.Connect.html
///
#[cfg_attr(feature = "defmt",derive(Format))]
#[cfg_attr(feature = "defmt", derive(Format))]
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Protocol {
/// [MQTT 3.1.1] is the most commonly implemented version. [MQTT 5] isn't yet supported my by
Expand All @@ -34,7 +33,7 @@ impl Protocol {
("MQIsdp", 3) => Ok(Protocol::MQIsdp),
("MQTT", 4) => Ok(Protocol::MQTT311),
_ => Err(Error::InvalidProtocol(String::from_str(name).unwrap(), 0)),
}
}
}
pub(crate) fn from_buffer<'a>(buf: &'a [u8], offset: &mut usize) -> Result<Self, Error> {
let protocol_name = read_str(buf, offset)?;
Expand Down Expand Up @@ -71,7 +70,7 @@ impl Protocol {
///
/// [Connect]: struct.Connect.html
/// [MQTT 3.1.3.3]: http://docs.oasis-open.org/mqtt/mqtt/v3.1.1/os/mqtt-v3.1.1-os.html#_Toc398718031
#[cfg_attr(feature = "defmt",derive(Format))]
#[cfg_attr(feature = "defmt", derive(Format))]
#[derive(Debug, Clone, PartialEq)]
pub struct LastWill<'a> {
pub topic: &'a str,
Expand All @@ -86,7 +85,7 @@ pub struct LastWill<'a> {
///
/// [Connack]: struct.Connack.html
/// [MQTT 3.2.2.3]: http://docs.oasis-open.org/mqtt/mqtt/v3.1.1/os/mqtt-v3.1.1-os.html#_Toc398718035
#[cfg_attr(feature = "defmt",derive(Format))]
#[cfg_attr(feature = "defmt", derive(Format))]
#[derive(Debug, Clone, Copy, PartialEq)]
pub enum ConnectReturnCode {
Accepted,
Expand Down Expand Up @@ -123,7 +122,7 @@ impl ConnectReturnCode {
/// Connect packet ([MQTT 3.1]).
///
/// [MQTT 3.1]: http://docs.oasis-open.org/mqtt/mqtt/v3.1.1/os/mqtt-v3.1.1-os.html#_Toc398718028
#[cfg_attr(feature = "defmt",derive(Format))]
#[cfg_attr(feature = "defmt", derive(Format))]
#[derive(Debug, Clone, PartialEq)]
pub struct Connect<'a> {
pub protocol: Protocol,
Expand All @@ -138,7 +137,7 @@ pub struct Connect<'a> {
/// Connack packet ([MQTT 3.2]).
///
/// [MQTT 3.2]: http://docs.oasis-open.org/mqtt/mqtt/v3.1.1/os/mqtt-v3.1.1-os.html#_Toc398718033
#[cfg_attr(feature = "defmt",derive(Format))]
#[cfg_attr(feature = "defmt", derive(Format))]
#[derive(Debug, Clone, Copy, PartialEq)]
pub struct Connack {
pub session_present: bool,
Expand Down
46 changes: 26 additions & 20 deletions src/decoder_test.rs
Original file line number Diff line number Diff line change
@@ -1,7 +1,9 @@
use crate::*;
#[cfg(feature = "std")]
use bytes::BytesMut;
use subscribe::LimitedString;
#[cfg(not(feature = "std"))]
use core::str::FromStr;
use subscribe::LimitedString;

macro_rules! header {
($t:ident, $d:expr, $q:ident, $r:expr) => {
Expand All @@ -14,10 +16,6 @@ macro_rules! header {
};
}

fn bm(d: &[u8]) -> BytesMut {
BytesMut::from(d)
}

/// Test all possible header first byte, using remaining_len=0.
#[test]
fn header_firstbyte() {
Expand Down Expand Up @@ -115,25 +113,34 @@ fn non_utf8_string() {
/// are rarer.
#[test]
fn inner_length_too_long() {
let mut data = bm(&[
let mut slice: &[u8] = &[
0b00010000, 20, // Connect packet, remaining_len=20
0x00, 0x04, 'M' as u8, 'Q' as u8, 'T' as u8, 'T' as u8, 0x04, 0b01000000, // +password
0x00, 0x0a, // keepalive 10 sec
0x00, 0x04, 't' as u8, 'e' as u8, 's' as u8, 't' as u8, // client_id
0x00, 0x03, 'm' as u8, 'q' as u8, // password with invalid length
]);
assert_eq!(Err(Error::InvalidLength), decode_slice(&mut data));
];

let mut slice: &[u8] = &[
assert_eq!(Err(Error::InvalidLength), decode_slice(&mut slice));
// assert_eq!(slice, []);
}

#[cfg(feature = "std")]
fn bm(d: &[u8]) -> BytesMut {
BytesMut::from(d)
}

#[cfg(feature = "std")]
#[test]
fn inner_length_too_long_bytes() {
let mut data = bm(&[
0b00010000, 20, // Connect packet, remaining_len=20
0x00, 0x04, 'M' as u8, 'Q' as u8, 'T' as u8, 'T' as u8, 0x04, 0b01000000, // +password
0x00, 0x0a, // keepalive 10 sec
0x00, 0x04, 't' as u8, 'e' as u8, 's' as u8, 't' as u8, // client_id
0x00, 0x03, 'm' as u8, 'q' as u8, // password with invalid length
];

assert_eq!(Err(Error::InvalidLength), decode_slice(&mut slice));
// assert_eq!(slice, []);
]);
assert_eq!(Err(Error::InvalidLength), decode_slice(&mut data));
}

#[test]
Expand Down Expand Up @@ -186,12 +193,8 @@ fn test_decode_packet_n() {
'e' as u8, // will msg = 'offline'
0x00, 0x04, 'r' as u8, 'u' as u8, 's' as u8, 't' as u8, // username = 'rust'
0x00, 0x02, 'm' as u8, 'q' as u8, // password = 'mq'

// pingreq packet
0b11000000, 0b00000000,

// pingresp packet
0b11010000, 0b00000000,
0b11000000, 0b00000000, // pingreq packet
0b11010000, 0b00000000, // pingresp packet
];

let pkt1 = Connect {
Expand Down Expand Up @@ -495,7 +498,10 @@ fn test_unsubscribe() {
match decode_slice(&mut data) {
Ok(Some(Packet::Unsubscribe(a))) => {
assert_eq!(a.pid.get(), 10);
assert_eq!(a.topics.get(0), Some(&LimitedString::from_str("a").unwrap()));
assert_eq!(
a.topics.get(0),
Some(&LimitedString::from_str("a").unwrap())
);
}
other => panic!("Failed decode: {:?}", other),
}
Expand Down
11 changes: 6 additions & 5 deletions src/encoder_test.rs
Original file line number Diff line number Diff line change
@@ -1,10 +1,8 @@
use crate::*;
use core::convert::TryFrom;
use subscribe::{LimitedString, LimitedVec};
#[cfg(not(feature = "std"))]
use core::str::FromStr;

#[cfg(feature = "std")]
use bytes::BytesMut;
use subscribe::{LimitedString, LimitedVec};

// macro_rules! assert_decode {
// ($res:pat, $pkt:expr) => {
Expand Down Expand Up @@ -173,7 +171,10 @@ fn test_unsubscribe() {
#[cfg(feature = "std")]
let topics: LimitedVec<LimitedString> = [LimitedString::from("a/b")].iter().cloned().collect();
#[cfg(not(feature = "std"))]
let topics: LimitedVec<LimitedString> = [LimitedString::from_str("a/b").unwrap()].iter().cloned().collect();
let topics: LimitedVec<LimitedString> = [LimitedString::from_str("a/b").unwrap()]
.iter()
.cloned()
.collect();

let packet = Unsubscribe::new(Pid::try_from(12321).unwrap(), topics).into();
// assert_decode!(Packet::Unsubscribe(_), &packet);
Expand Down
4 changes: 2 additions & 2 deletions src/packet.rs
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,7 @@ use crate::*;
///
/// [`encode()`]: fn.encode.html
/// [`decode_slice()`]: fn.decode_slice.html
#[cfg_attr(feature = "defmt",derive(Format))]
#[cfg_attr(feature = "defmt", derive(Format))]
#[derive(Debug, Clone, PartialEq)]
pub enum Packet<'a> {
/// [MQTT 3.1](http://docs.oasis-open.org/mqtt/mqtt/v3.1.1/os/mqtt-v3.1.1-os.html#_Toc398718028)
Expand Down Expand Up @@ -111,7 +111,7 @@ packet_from_borrowed!(Connect, Publish);
packet_from!(Suback, Connack, Subscribe, Unsubscribe);

/// Packet type variant, without the associated data.
#[cfg_attr(feature = "defmt",derive(Format))]
#[cfg_attr(feature = "defmt", derive(Format))]
#[derive(Debug, Copy, Clone, PartialEq, Eq, Hash, PartialOrd, Ord)]
pub enum PacketType {
Connect,
Expand Down
4 changes: 2 additions & 2 deletions src/publish.rs
Original file line number Diff line number Diff line change
@@ -1,11 +1,11 @@
use crate::{decoder::*, encoder::*, *};
#[cfg(feature = "defmt")]
use defmt::Format;
use crate::{decoder::*, encoder::*, *};

/// Publish packet ([MQTT 3.3]).
///
/// [MQTT 3.3]: http://docs.oasis-open.org/mqtt/mqtt/v3.1.1/os/mqtt-v3.1.1-os.html#_Toc398718037
#[cfg_attr(feature = "defmt",derive(Format))]
#[cfg_attr(feature = "defmt", derive(Format))]
#[derive(Debug, Clone, PartialEq)]
pub struct Publish<'a> {
pub dup: bool,
Expand Down
12 changes: 6 additions & 6 deletions src/subscribe.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
use crate::{decoder::*, encoder::*, *};
#[cfg(feature = "defmt")]
use defmt::Format;
use crate::{decoder::*, encoder::*, *};
#[cfg(feature = "derive")]
use serde::{Deserialize, Serialize};

Expand All @@ -21,7 +21,7 @@ use core::str::FromStr;
/// [Subscribe] packets contain a `Vec` of those.
///
/// [Subscribe]: struct.Subscribe.html
#[cfg_attr(feature = "defmt",derive(Format))]
#[cfg_attr(feature = "defmt", derive(Format))]
#[derive(Debug, Clone, PartialEq)]
#[cfg_attr(feature = "derive", derive(Serialize, Deserialize))]
pub struct SubscribeTopic {
Expand All @@ -43,7 +43,7 @@ impl SubscribeTopic {
/// [Suback] packets contain a `Vec` of those.
///
/// [Suback]: struct.Subscribe.html
#[cfg_attr(feature = "defmt",derive(Format))]
#[cfg_attr(feature = "defmt", derive(Format))]
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum SubscribeReturnCodes {
Success(QoS),
Expand Down Expand Up @@ -73,7 +73,7 @@ impl SubscribeReturnCodes {
/// Subscribe packet ([MQTT 3.8]).
///
/// [MQTT 3.8]: http://docs.oasis-open.org/mqtt/mqtt/v3.1.1/os/mqtt-v3.1.1-os.html#_Toc398718063
#[cfg_attr(feature = "defmt",derive(Format))]
#[cfg_attr(feature = "defmt", derive(Format))]
#[derive(Debug, Clone, PartialEq)]
pub struct Subscribe {
pub pid: Pid,
Expand All @@ -83,7 +83,7 @@ pub struct Subscribe {
/// Subsack packet ([MQTT 3.9]).
///
/// [MQTT 3.9]: http://docs.oasis-open.org/mqtt/mqtt/v3.1.1/os/mqtt-v3.1.1-os.html#_Toc398718068
#[cfg_attr(feature = "defmt",derive(Format))]
#[cfg_attr(feature = "defmt", derive(Format))]
#[derive(Debug, Clone, PartialEq)]
pub struct Suback {
pub pid: Pid,
Expand All @@ -93,7 +93,7 @@ pub struct Suback {
/// Unsubscribe packet ([MQTT 3.10]).
///
/// [MQTT 3.10]: http://docs.oasis-open.org/mqtt/mqtt/v3.1.1/os/mqtt-v3.1.1-os.html#_Toc398718072
#[cfg_attr(feature = "defmt",derive(Format))]
#[cfg_attr(feature = "defmt", derive(Format))]
#[derive(Debug, Clone, PartialEq)]
pub struct Unsubscribe {
pub pid: Pid,
Expand Down
14 changes: 6 additions & 8 deletions src/utils.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,5 @@
#[cfg(feature = "defmt")]
use defmt::{Format};

use defmt::Format;

use crate::encoder::write_u16;
use core::{convert::TryFrom, fmt, num::NonZeroU16};
Expand All @@ -20,8 +19,7 @@ use std::{
/// [`encode()`]: fn.encode.html
/// [`decode()`]: fn.decode.html

#[cfg_attr(feature = "defmt",derive(Format))]
#[cfg_attr(feature = "defmt", derive(Format))]
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum Error {
/// Not enough space in the write buffer.
Expand All @@ -47,7 +45,7 @@ pub enum Error {
/// length rather than a buffer size issue.
InvalidLength,
/// Trying to decode a non-utf8 string.
InvalidString(#[cfg_attr(feature = "defmt",defmt(Debug2Format))] core::str::Utf8Error),
InvalidString(#[cfg_attr(feature = "defmt", defmt(Debug2Format))] core::str::Utf8Error),
/// Catch-all error when converting from `std::io::Error`.
///
/// Note: Only available when std is available.
Expand Down Expand Up @@ -114,7 +112,7 @@ impl From<IoError> for Error {
/// [MQTT-2.3.1-1]: https://docs.oasis-open.org/mqtt/mqtt/v3.1.1/os/mqtt-v3.1.1-os.html#_Toc398718025
/// [MQTT-2.2.1-3]: https://docs.oasis-open.org/mqtt/mqtt/v5.0/os/mqtt-v5.0-os.html#_Toc3901026
#[cfg_attr(feature = "defmt",derive(Format))]
#[cfg_attr(feature = "defmt", derive(Format))]
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
#[cfg_attr(feature = "derive", derive(Serialize, Deserialize))]
pub struct Pid(NonZeroU16);
Expand Down Expand Up @@ -195,7 +193,7 @@ impl TryFrom<u16> for Pid {
/// Packet delivery [Quality of Service] level.
///
/// [Quality of Service]: http://docs.oasis-open.org/mqtt/mqtt/v3.1.1/os/mqtt-v3.1.1-os.html#_Toc398718099
#[cfg_attr(feature = "defmt",derive(Format))]
#[cfg_attr(feature = "defmt", derive(Format))]
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[cfg_attr(feature = "derive", derive(Serialize, Deserialize))]
pub enum QoS {
Expand Down Expand Up @@ -233,7 +231,7 @@ impl QoS {
/// [`Publish`]: struct.Publish.html
/// [`QoS`]: enum.QoS.html
/// [`Pid`]: struct.Pid.html
#[cfg_attr(feature = "defmt",derive(Format))]
#[cfg_attr(feature = "defmt", derive(Format))]
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[cfg_attr(feature = "derive", derive(Serialize, Deserialize))]
pub enum QosPid {
Expand Down

0 comments on commit dd9d381

Please sign in to comment.