1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335
//! # Flavors - Plugins for `postcard` //! //! "Flavors" in `postcard` are used as modifiers to the serialization //! process. Flavors typically modify one or both of the following: //! //! 1. The output medium of the serialization, e.g. whether the data is serialized to a `[u8]` slice, or a `heapless::Vec`. //! 2. The format of the serialization, such as encoding the serialized output in a COBS format, performing CRC32 checksumming while serializing, etc. //! //! Flavors are implemented using the `SerFlavor` trait, which acts as a "middleware" for receiving the bytes as serialized by `serde`. //! Multiple flavors may be combined to obtain a desired combination of behavior and storage. //! When flavors are combined, it is expected that the storage flavor (such as `Slice` or `HVec`) is the innermost flavor. //! //! Custom flavors may be defined by users of the `postcard` crate, however some commonly useful flavors have been provided in //! this module. If you think your custom flavor would be useful to others, PRs adding flavors are very welcome! //! //! ## Usability //! //! Flavors may not always be convenient to use directly, as they may expose some implementation details of how the //! inner workings of the flavor behaves. It is typical to provide a convenience method for using a flavor, to prevent //! the user from having to specify generic parameters, setting correct initialization values, or handling the output of //! the flavor correctly. See `postcard::to_vec()` for an example of this. //! //! It is recommended to use the [`serialize_with_flavor()`](../fn.serialize_with_flavor.html) method for serialization. See it's documentation for information //! regarding usage and generic type parameters. //! //! ## Examples //! //! ### Using a single flavor //! //! In the first example, we use the `Slice` flavor, to store the serialized output into a mutable `[u8]` slice. //! No other modification is made to the serialization process. //! //! ```rust //! use postcard::{ //! serialize_with_flavor, //! flavors::Slice, //! }; //! //! let mut buf = [0u8; 32]; //! //! let data: &[u8] = &[0x01, 0x00, 0x20, 0x30]; //! let buffer = &mut [0u8; 32]; //! let res = serialize_with_flavor::<[u8], Slice, &mut [u8]>( //! data, //! Slice::new(buffer) //! ).unwrap(); //! //! assert_eq!(res, &[0x04, 0x01, 0x00, 0x20, 0x30]); //! ``` //! //! ### Using combined flavors //! //! In the second example, we mix `Slice` with `Cobs`, to cobs encode the output while //! the data is serialized. Notice how `Slice` (the storage flavor) is the innermost flavor used. //! //! ```rust //! use postcard::{ //! serialize_with_flavor, //! flavors::{Cobs, Slice}, //! }; //! //! let mut buf = [0u8; 32]; //! //! let data: &[u8] = &[0x01, 0x00, 0x20, 0x30]; //! let buffer = &mut [0u8; 32]; //! let res = serialize_with_flavor::<[u8], Cobs<Slice>, &mut [u8]>( //! data, //! Cobs::try_new(Slice::new(buffer)).unwrap(), //! ).unwrap(); //! //! assert_eq!(res, &[0x03, 0x04, 0x01, 0x03, 0x20, 0x30, 0x00]); //! ``` use crate::error::{Error, Result}; use cobs::{EncoderState, PushResult}; use core::ops::Index; use core::ops::IndexMut; use heapless::{ArrayLength, Vec}; /// The SerFlavor trait acts as a combinator/middleware interface that can be used to pass bytes /// through storage or modification flavors. See the module level documentation for more information /// and examples. pub trait SerFlavor { /// The `Output` type is what this flavor "resolves" to when the serialization is complete. /// For storage flavors, this is typically a concrete type. For modification flavors, this is /// typically a generic parameter for the storage flavor they are wrapped around. type Output; /// The try_extend() trait method can be implemented when there is a more efficient way of processing /// multiple bytes at once, such as copying a slice to the output, rather than iterating over one byte /// at a time. fn try_extend(&mut self, data: &[u8]) -> core::result::Result<(), ()> { data.iter() .try_for_each(|d| self.try_push(*d)) .map_err(|_| ()) } /// The try_push() trait method can be used to push a single byte to be modified and/or stored fn try_push(&mut self, data: u8) -> core::result::Result<(), ()>; /// The release() trait method finalizes the modification or storage operation, and resolved into /// the type defined by `SerFlavor::Output` associated type. fn release(self) -> core::result::Result<Self::Output, ()>; } //////////////////////////////////////////////////////////////////////////////// // Storage Flavors //////////////////////////////////////////////////////////////////////////////// //////////////////////////////////////// // Slice //////////////////////////////////////// /// The `Slice` flavor is a storage flavor, storing the serialized (or otherwise modified) bytes into a plain /// `[u8]` slice. The `Slice` flavor resolves into a sub-slice of the original slice buffer. pub struct Slice<'a> { buf: &'a mut [u8], idx: usize, } impl<'a> Slice<'a> { /// Create a new `Slice` flavor from a given backing buffer pub fn new(buf: &'a mut [u8]) -> Self { Slice { buf, idx: 0 } } } impl<'a> SerFlavor for Slice<'a> { type Output = &'a mut [u8]; fn try_extend(&mut self, data: &[u8]) -> core::result::Result<(), ()> { let len = data.len(); if (len + self.idx) > self.buf.len() { return Err(()); } self.buf[self.idx..self.idx + len].copy_from_slice(data); self.idx += len; Ok(()) } fn try_push(&mut self, data: u8) -> core::result::Result<(), ()> { if self.idx >= self.buf.len() { return Err(()); } self.buf[self.idx] = data; self.idx += 1; Ok(()) } fn release(self) -> core::result::Result<Self::Output, ()> { let (used, _unused) = self.buf.split_at_mut(self.idx); Ok(used) } } impl<'a> Index<usize> for Slice<'a> { type Output = u8; fn index(&self, idx: usize) -> &u8 { &self.buf[idx] } } impl<'a> IndexMut<usize> for Slice<'a> { fn index_mut(&mut self, idx: usize) -> &mut u8 { &mut self.buf[idx] } } //////////////////////////////////////// // HVec //////////////////////////////////////// /// The `HVec` flavor is a wrapper type around a `heapless::Vec`. This is a stack /// allocated data structure, with a fixed maximum size and variable amount of contents pub struct HVec<B: ArrayLength<u8>>(Vec<u8, B>); impl<'a, B> SerFlavor for HVec<B> where B: ArrayLength<u8>, { type Output = Vec<u8, B>; #[inline(always)] fn try_extend(&mut self, data: &[u8]) -> core::result::Result<(), ()> { self.0.extend_from_slice(data) } #[inline(always)] fn try_push(&mut self, data: u8) -> core::result::Result<(), ()> { self.0.push(data).map_err(|_| ()) } fn release(self) -> core::result::Result<Vec<u8, B>, ()> { Ok(self.0) } } impl<B: ArrayLength<u8>> Index<usize> for HVec<B> { type Output = u8; fn index(&self, idx: usize) -> &u8 { &self.0[idx] } } impl<B: ArrayLength<u8>> IndexMut<usize> for HVec<B> { fn index_mut(&mut self, idx: usize) -> &mut u8 { &mut self.0[idx] } } impl<B: ArrayLength<u8>> Default for HVec<B> { fn default() -> Self { Self(Vec::new()) } } /// The `StdVec` flavor is a wrapper type around a `std::vec::Vec`. /// /// This type is only available when the (non-default) `use-std` feature is active #[cfg(feature = "use-std")] pub struct StdVec(pub std::vec::Vec<u8>); #[cfg(feature = "use-std")] impl SerFlavor for StdVec { type Output = std::vec::Vec<u8>; #[inline(always)] fn try_extend(&mut self, data: &[u8]) -> core::result::Result<(), ()> { self.0.extend_from_slice(data); Ok(()) } #[inline(always)] fn try_push(&mut self, data: u8) -> core::result::Result<(), ()> { self.0.push(data); Ok(()) } fn release(self) -> core::result::Result<Self::Output, ()> { Ok(self.0) } } #[cfg(feature = "use-std")] impl Index<usize> for StdVec { type Output = u8; fn index(&self, idx: usize) -> &u8 { &self.0[idx] } } #[cfg(feature = "use-std")] impl IndexMut<usize> for StdVec { fn index_mut(&mut self, idx: usize) -> &mut u8 { &mut self.0[idx] } } //////////////////////////////////////////////////////////////////////////////// // Modification Flavors //////////////////////////////////////////////////////////////////////////////// //////////////////////////////////////// // COBS //////////////////////////////////////// /// The `Cobs` flavor implements [Consistent Overhead Byte Stuffing] on /// the serialized data. The output of this flavor includes the termination/sentinel /// byte of `0x00`. /// /// This protocol is useful when sending data over a serial interface without framing such as a UART /// /// [Consistent Overhead Byte Stuffing]: https://en.wikipedia.org/wiki/Consistent_Overhead_Byte_Stuffing pub struct Cobs<B> where B: SerFlavor + IndexMut<usize, Output = u8>, { flav: B, cobs: EncoderState, } impl<B> Cobs<B> where B: SerFlavor + IndexMut<usize, Output = u8>, { /// Create a new Cobs modifier Flavor. If there is insufficient space /// to push the leading header byte, the method will return an Error pub fn try_new(mut bee: B) -> Result<Self> { bee.try_push(0).map_err(|_| Error::SerializeBufferFull)?; Ok(Self { flav: bee, cobs: EncoderState::default(), }) } } impl<'a, B> SerFlavor for Cobs<B> where B: SerFlavor + IndexMut<usize, Output = u8>, { type Output = <B as SerFlavor>::Output; #[inline(always)] fn try_push(&mut self, data: u8) -> core::result::Result<(), ()> { use PushResult::*; match self.cobs.push(data) { AddSingle(n) => self.flav.try_push(n), ModifyFromStartAndSkip((idx, mval)) => { self.flav[idx] = mval; self.flav.try_push(0) } ModifyFromStartAndPushAndSkip((idx, mval, nval)) => { self.flav[idx] = mval; self.flav.try_push(nval)?; self.flav.try_push(0) } } } fn release(mut self) -> core::result::Result<Self::Output, ()> { let (idx, mval) = self.cobs.finalize(); self.flav[idx] = mval; self.flav.try_push(0)?; self.flav.release() } }