#![cfg(any(feature = "std", feature = "arrayvec"))] use mqtt_tiny::coding::{length::Length, Decoder, Encoder}; use std::ops::Deref; // Select an appropriate vector type #[cfg(feature = "std")] type Vec = std::vec::Vec; #[cfg(all(not(feature = "std"), feature = "arrayvec"))] type Vec = arrayvec::ArrayVec; /// A test vector for encoded/decoded pairs #[derive(Debug, Clone, Copy)] pub struct Good { /// The encoded representation encoded: &'static [u8], /// The decoded representation decoded: [bool; 8], } impl Good { /// Good encoded/decoded pairs pub const fn all() -> &'static [Self] { &[ Self { encoded: &[0b0000_0000], decoded: [false; 8] }, Self { encoded: &[0b1010_1010], decoded: [true, false, true, false, true, false, true, false] }, Self { encoded: &[0b0101_0101], decoded: [false, true, false, true, false, true, false, true] }, Self { encoded: &[0b1111_1111], decoded: [true; 8] }, ] } } /// A test vector for known-bad encoded encoded fields #[derive(Debug)] pub struct BadEncoded { /// The invalid encoded representation encoded: &'static [u8], } impl BadEncoded { /// Good encoded/decoded pairs pub const fn all() -> &'static [Self] { &[Self { encoded: &[] }] } } /// Tests successful decoding #[test] pub fn decode() { for test_vector in Good::all() { // Decode and validate let encoded = test_vector.encoded.iter().copied(); let decoded = Decoder::new(encoded).bitmap().expect("Failed to decode valid flags"); assert_eq!(decoded, test_vector.decoded, "Invalid decoded flags") } } /// Tests successful encoding #[test] pub fn encode() { for test_vector in Good::all() { // Encode length let length: usize = Length::new().bitmap(&test_vector.decoded).into(); // Encode and validate let encoded = Encoder::default().bitmap(test_vector.decoded); let encoded: Vec = encoded.into_iter().collect(); assert_eq!(encoded.deref(), test_vector.encoded, "Invalid encoded flags"); assert_eq!(length, test_vector.encoded.len(), "Invalid encoded length"); } } /// Tests failing decoding #[test] pub fn decode_invalid() { for test_vector in BadEncoded::all() { // Decode and validate let encoded = test_vector.encoded.iter().copied(); let decoded = Decoder::new(encoded).bitmap(); assert!(decoded.is_err(), "Unexpected success when decoding invalid flags"); } }