cobs-0.2.3/.cargo_vcs_info.json0000644000000001360000000000100117640ustar { "git": { "sha1": "627ae5ec1e723313c5e6f08676473614482bfde7" }, "path_in_vcs": "" }cobs-0.2.3/.gitignore000064400000000000000000000000300072674642500125650ustar 00000000000000target Cargo.lock *.swp cobs-0.2.3/.travis.yml000064400000000000000000000004310072674642500127130ustar 00000000000000language: rust rust: - stable - beta - nightly install: - rustup target add thumbv7em-none-eabihf script: - cargo build - cargo test # Check for no_std compatibility by building for an embedded target - cargo build --no-default-features --target=thumbv7em-none-eabihf cobs-0.2.3/Cargo.toml0000644000000022720000000000100077650ustar # THIS FILE IS AUTOMATICALLY GENERATED BY CARGO # # When uploading crates to the registry Cargo will automatically # "normalize" Cargo.toml files for maximal compatibility # with all versions of Cargo and also rewrite `path` dependencies # to registry (e.g., crates.io) dependencies. # # If you are reading this file be aware that the original Cargo.toml # will likely look very different (and much more reasonable). # See Cargo.toml.orig for the original contents. [package] edition = "2018" name = "cobs" version = "0.2.3" authors = [ "Allen Welkie <>", "James Munns ", ] description = """ This is an implementation of the Consistent Overhead Byte Stuffing (COBS) algorithm. COBS is an algorithm for transforming a message into an encoding where a specific value (the \"sentinel\" value) is not used. This value can then be used to mark frame boundaries in a serial communication channel. """ keywords = [ "consistent", "overhead", "byte", "stuffing", ] license = "MIT OR Apache-2.0" repository = "https://github.com/jamesmunns/cobs.rs" [dev-dependencies.quickcheck] version = "^0.5.0" [features] default = ["use_std"] use_std = [] cobs-0.2.3/Cargo.toml.orig000064400000000000000000000012770072674642500135020ustar 00000000000000[package] name = "cobs" version = "0.2.3" authors = ["Allen Welkie <>", "James Munns "] license = "MIT OR Apache-2.0" description = """ This is an implementation of the Consistent Overhead Byte Stuffing (COBS) algorithm. COBS is an algorithm for transforming a message into an encoding where a specific value (the "sentinel" value) is not used. This value can then be used to mark frame boundaries in a serial communication channel. """ repository = "https://github.com/jamesmunns/cobs.rs" keywords = ["consistent", "overhead", "byte", "stuffing"] edition = "2018" [features] default = ["use_std"] use_std = [] [dev-dependencies] quickcheck = "^0.5.0" cobs-0.2.3/LICENSE-APACHE000064400000000000000000000261360072674642500125400ustar 00000000000000 Apache License Version 2.0, January 2004 http://www.apache.org/licenses/ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 1. Definitions. "License" shall mean the terms and conditions for use, reproduction, and distribution as defined by Sections 1 through 9 of this document. "Licensor" shall mean the copyright owner or entity authorized by the copyright owner that is granting the License. "Legal Entity" shall mean the union of the acting entity and all other entities that control, are controlled by, or are under common control with that entity. For the purposes of this definition, "control" means (i) the power, direct or indirect, to cause the direction or management of such entity, whether by contract or otherwise, or (ii) ownership of fifty percent (50%) or more of the outstanding shares, or (iii) beneficial ownership of such entity. "You" (or "Your") shall mean an individual or Legal Entity exercising permissions granted by this License. "Source" form shall mean the preferred form for making modifications, including but not limited to software source code, documentation source, and configuration files. "Object" form shall mean any form resulting from mechanical transformation or translation of a Source form, including but not limited to compiled object code, generated documentation, and conversions to other media types. "Work" shall mean the work of authorship, whether in Source or Object form, made available under the License, as indicated by a copyright notice that is included in or attached to the work (an example is provided in the Appendix below). "Derivative Works" shall mean any work, whether in Source or Object form, that is based on (or derived from) the Work and for which the editorial revisions, annotations, elaborations, or other modifications represent, as a whole, an original work of authorship. For the purposes of this License, Derivative Works shall not include works that remain separable from, or merely link (or bind by name) to the interfaces of, the Work and Derivative Works thereof. "Contribution" shall mean any work of authorship, including the original version of the Work and any modifications or additions to that Work or Derivative Works thereof, that is intentionally submitted to Licensor for inclusion in the Work by the copyright owner or by an individual or Legal Entity authorized to submit on behalf of the copyright owner. For the purposes of this definition, "submitted" means any form of electronic, verbal, or written communication sent to the Licensor or its representatives, including but not limited to communication on electronic mailing lists, source code control systems, and issue tracking systems that are managed by, or on behalf of, the Licensor for the purpose of discussing and improving the Work, but excluding communication that is conspicuously marked or otherwise designated in writing by the copyright owner as "Not a Contribution." "Contributor" shall mean Licensor and any individual or Legal Entity on behalf of whom a Contribution has been received by Licensor and subsequently incorporated within the Work. 2. Grant of Copyright License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable copyright license to reproduce, prepare Derivative Works of, publicly display, publicly perform, sublicense, and distribute the Work and such Derivative Works in Source or Object form. 3. Grant of Patent License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable (except as stated in this section) patent license to make, have made, use, offer to sell, sell, import, and otherwise transfer the Work, where such license applies only to those patent claims licensable by such Contributor that are necessarily infringed by their Contribution(s) alone or by combination of their Contribution(s) with the Work to which such Contribution(s) was submitted. If You institute patent litigation against any entity (including a cross-claim or counterclaim in a lawsuit) alleging that the Work or a Contribution incorporated within the Work constitutes direct or contributory patent infringement, then any patent licenses granted to You under this License for that Work shall terminate as of the date such litigation is filed. 4. Redistribution. You may reproduce and distribute copies of the Work or Derivative Works thereof in any medium, with or without modifications, and in Source or Object form, provided that You meet the following conditions: (a) You must give any other recipients of the Work or Derivative Works a copy of this License; and (b) You must cause any modified files to carry prominent notices stating that You changed the files; and (c) You must retain, in the Source form of any Derivative Works that You distribute, all copyright, patent, trademark, and attribution notices from the Source form of the Work, excluding those notices that do not pertain to any part of the Derivative Works; and (d) If the Work includes a "NOTICE" text file as part of its distribution, then any Derivative Works that You distribute must include a readable copy of the attribution notices contained within such NOTICE file, excluding those notices that do not pertain to any part of the Derivative Works, in at least one of the following places: within a NOTICE text file distributed as part of the Derivative Works; within the Source form or documentation, if provided along with the Derivative Works; or, within a display generated by the Derivative Works, if and wherever such third-party notices normally appear. The contents of the NOTICE file are for informational purposes only and do not modify the License. You may add Your own attribution notices within Derivative Works that You distribute, alongside or as an addendum to the NOTICE text from the Work, provided that such additional attribution notices cannot be construed as modifying the License. You may add Your own copyright statement to Your modifications and may provide additional or different license terms and conditions for use, reproduction, or distribution of Your modifications, or for any such Derivative Works as a whole, provided Your use, reproduction, and distribution of the Work otherwise complies with the conditions stated in this License. 5. Submission of Contributions. Unless You explicitly state otherwise, any Contribution intentionally submitted for inclusion in the Work by You to the Licensor shall be under the terms and conditions of this License, without any additional terms or conditions. Notwithstanding the above, nothing herein shall supersede or modify the terms of any separate license agreement you may have executed with Licensor regarding such Contributions. 6. Trademarks. This License does not grant permission to use the trade names, trademarks, service marks, or product names of the Licensor, except as required for reasonable and customary use in describing the origin of the Work and reproducing the content of the NOTICE file. 7. Disclaimer of Warranty. Unless required by applicable law or agreed to in writing, Licensor provides the Work (and each Contributor provides its Contributions) on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied, including, without limitation, any warranties or conditions of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. You are solely responsible for determining the appropriateness of using or redistributing the Work and assume any risks associated with Your exercise of permissions under this License. 8. Limitation of Liability. In no event and under no legal theory, whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or agreed to in writing, shall any Contributor be liable to You for damages, including any direct, indirect, special, incidental, or consequential damages of any character arising as a result of this License or out of the use or inability to use the Work (including but not limited to damages for loss of goodwill, work stoppage, computer failure or malfunction, or any and all other commercial damages or losses), even if such Contributor has been advised of the possibility of such damages. 9. Accepting Warranty or Additional Liability. While redistributing the Work or Derivative Works thereof, You may choose to offer, and charge a fee for, acceptance of support, warranty, indemnity, or other liability obligations and/or rights consistent with this License. However, in accepting such obligations, You may act only on Your own behalf and on Your sole responsibility, not on behalf of any other Contributor, and only if You agree to indemnify, defend, and hold each Contributor harmless for any liability incurred by, or claims asserted against, such Contributor by reason of your accepting any such warranty or additional liability. END OF TERMS AND CONDITIONS APPENDIX: How to apply the Apache License to your work. To apply the Apache License to your work, attach the following boilerplate notice, with the fields enclosed by brackets "{}" replaced with your own identifying information. (Don't include the brackets!) The text should be enclosed in the appropriate comment syntax for the file format. We also recommend that a file or class name and description of purpose be included on the same "printed page" as the copyright notice for easier identification within third-party archives. Copyright {yyyy} {name of copyright owner} Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. cobs-0.2.3/LICENSE-MIT000064400000000000000000000020520072674642500122370ustar 00000000000000Copyright (c) 2015 The cobs.rs Developers Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. cobs-0.2.3/README.md000064400000000000000000000015720072674642500120700ustar 00000000000000# `cobs` This is an implementation of the Consistent Overhead Byte Stuffing (COBS) algorithm in Rust. COBS is an algorithm for transforming a message into an encoding where a specific value (the "sentinel" value) is not used. This value can then be used to mark frame boundaries in a serial communication channel. See www.wikipedia.org/wiki/Consistent_Overhead_Byte_Stuffing for details. ## License Licensed under either of * Apache License, Version 2.0, ([LICENSE-APACHE](LICENSE-APACHE) or http://www.apache.org/licenses/LICENSE-2.0) * MIT license ([LICENSE-MIT](LICENSE-MIT) or http://opensource.org/licenses/MIT) at your option. ### Contribution Unless you explicitly state otherwise, any contribution intentionally submitted for inclusion in the work by you, as defined in the Apache-2.0 license, shall be dual licensed as above, without any additional terms or conditions. cobs-0.2.3/src/dec.rs000064400000000000000000000314520072674642500125010ustar 00000000000000/// The [`CobsDecoder`] type is used to decode a stream of bytes to a /// given mutable output slice. This is often useful when heap data /// structures are not available, or when not all message bytes are /// received at a single point in time. #[derive(Debug)] pub struct CobsDecoder<'a> { /// Destination slice for decoded message dest: &'a mut [u8], /// Index of next byte to write in `dest` dest_idx: usize, /// Decoder state as an enum state: DecoderState, } /// The [`DecoderState`] is used to track the current state of a /// streaming decoder. This struct does not contain the output buffer /// (or a reference to one), and can be used when streaming the decoded /// output to a custom data type. #[derive(Debug)] pub enum DecoderState { /// State machine has not received any non-zero bytes Idle, /// 1-254 bytes, can be header or 00 Grab(u8), /// 255 bytes, will be a header next GrabChain(u8), } fn add(to: &mut [u8], idx: usize, data: u8) -> Result<(), ()> { *to.get_mut(idx) .ok_or_else(|| ())? = data; Ok(()) } /// [`DecodeResult`] represents the possible non-error outcomes of /// pushing an encoded data byte into the [`DecoderState`] state machine pub enum DecodeResult { /// The given input byte did not prompt an output byte, either because the /// state machine is still idle, or we have just processed a header byte. /// More data is needed to complete the message. NoData, /// We have received a complete and well-encoded COBS message. The /// contents of the associated output buffer may now be used DataComplete, /// The following byte should be appended to the current end of the decoded /// output buffer. /// More data is needed to complete the message. DataContinue(u8), } impl DecoderState { /// Push a single encoded byte into the state machine. If the input was /// unexpected, such as an early end of a framed message segment, an Error will /// be returned, and the current associated output buffer contents should be discarded. /// /// If a complete message is indicated, the decoding state machine will automatically /// reset itself to the Idle state, and may be used to begin decoding another message. /// /// NOTE: Sentinel value must be included in the input to this function for the /// decoding to complete pub fn feed(&mut self, data: u8) -> Result { use DecoderState::*; use DecodeResult::*; let (ret, state) = match (&self, data) { // Currently Idle, received a terminator, ignore, stay idle (Idle, 0x00) => (Ok(NoData), Idle), // Currently Idle, received a byte indicating the // next 255 bytes have no zeroes, so we will have 254 unmodified // data bytes, then an overhead byte (Idle, 0xFF) => (Ok(NoData), GrabChain(0xFE)), // Currently Idle, received a byte indicating there will be a // zero that must be modified in the next 1..=254 bytes (Idle, n) => (Ok(NoData), Grab(n - 1)), // We have reached the end of a data run indicated by an overhead // byte, AND we have recieved the message terminator. This was a // well framed message! (Grab(0), 0x00) => (Ok(DataComplete), Idle), // We have reached the end of a data run indicated by an overhead // byte, and the next segment of 254 bytes will have no modified // sentinel bytes (Grab(0), 0xFF) => { (Ok(DataContinue(0)), GrabChain(0xFE)) }, // We have reached the end of a data run indicated by an overhead // byte, and we will treat this byte as a modified sentinel byte. // place the sentinel byte in the output, and begin processing the // next non-sentinel sequence (Grab(0), n) => { (Ok(DataContinue(0)), Grab(n - 1)) }, // We were not expecting the sequence to terminate, but here we are. // Report an error due to early terminated message (Grab(_), 0) => { (Err(()), Idle) } // We have not yet reached the end of a data run, decrement the run // counter, and place the byte into the decoded output (Grab(i), n) => { (Ok(DataContinue(n)), Grab(*i - 1)) }, // We have reached the end of a data run indicated by an overhead // byte, AND we have recieved the message terminator. This was a // well framed message! (GrabChain(0), 0x00) => { (Ok(DataComplete), Idle) } // We have reached the end of a data run, and we will begin another // data run with an overhead byte expected at the end (GrabChain(0), 0xFF) => (Ok(NoData), GrabChain(0xFE)), // We have reached the end of a data run, and we will expect `n` data // bytes unmodified, followed by a sentinel byte that must be modified (GrabChain(0), n) => (Ok(NoData), Grab(n - 1)), // We were not expecting the sequence to terminate, but here we are. // Report an error due to early terminated message (GrabChain(_), 0) => { (Err(()), Idle) } // We have not yet reached the end of a data run, decrement the run // counter, and place the byte into the decoded output (GrabChain(i), n) => { (Ok(DataContinue(n)), GrabChain(*i - 1)) }, }; *self = state; ret } } impl<'a> CobsDecoder<'a> { /// Create a new streaming Cobs Decoder. Provide the output buffer /// for the decoded message to be placed in pub fn new(dest: &'a mut [u8]) -> CobsDecoder<'a> { CobsDecoder { dest, dest_idx: 0, state: DecoderState::Idle, } } /// Push a single byte into the streaming CobsDecoder. Return values mean: /// /// * Ok(None) - State machine okay, more data needed /// * Ok(Some(N)) - A message of N bytes was successfully decoded /// * Err(M) - Message decoding failed, and M bytes were written to output /// /// NOTE: Sentinel value must be included in the input to this function for the /// decoding to complete pub fn feed(&mut self, data: u8) -> Result, usize> { match self.state.feed(data) { Err(()) => Err(self.dest_idx), Ok(DecodeResult::NoData) => Ok(None), Ok(DecodeResult::DataContinue(n)) => { add(self.dest, self.dest_idx, n).map_err(|_| self.dest_idx)?; self.dest_idx += 1; Ok(None) } Ok(DecodeResult::DataComplete) => { Ok(Some(self.dest_idx)) } } } /// Push a slice of bytes into the streaming CobsDecoder. Return values mean: /// /// * Ok(None) - State machine okay, more data needed /// * Ok(Some((N, M))) - A message of N bytes was successfully decoded, /// using M bytes from `data` (and earlier data) /// * Err(J) - Message decoding failed, and J bytes were written to output /// /// NOTE: Sentinel value must be included in the input to this function for the /// decoding to complete pub fn push(&mut self, data: &[u8]) -> Result, usize> { for (consumed_idx, d) in data.iter().enumerate() { let x = self.feed(*d); if let Some(decoded_bytes_ct) = x? { // convert from index to number of bytes consumed return Ok(Some((decoded_bytes_ct, consumed_idx + 1))); } } Ok(None) } } // This needs to be a macro because `src` and `dst` could be the same or different. macro_rules! decode_raw ( ($src:ident, $dst:ident) => ({ let mut source_index = 0; let mut dest_index = 0; // Stop at the first terminator, if any let src_end = if let Some(end) = $src.iter().position(|b| *b == 0) { end } else { $src.len() }; while source_index < src_end { let code = $src[source_index]; if source_index + code as usize > src_end && code != 1 { return Err(()); } source_index += 1; // TODO: There are potential `panic!`s in these dest_index offsets for _ in 1..code { $dst[dest_index] = $src[source_index]; source_index += 1; dest_index += 1; } if 0xFF != code && source_index < src_end { $dst[dest_index] = 0; dest_index += 1; } } DecodeReport { dst_used: dest_index, src_used: source_index, } }) ); /// Decodes the `source` buffer into the `dest` buffer. /// /// This function uses the typical sentinel value of 0. /// /// # Failures /// /// This will return `Err(())` if there was a decoding error. Otherwise, /// it will return `Ok(n)` where `n` is the length of the decoded message. pub fn decode(source: &[u8], dest: &mut[u8]) -> Result { let mut dec = CobsDecoder::new(dest); // Did we decode a message, using some or all of the buffer? match dec.push(source).or(Err(()))? { Some((d_used, _s_used)) => return Ok(d_used), None => {}, } // If we consumed the entire buffer, but did NOT get a message, // AND the message did not end with a zero, try providing one to // complete the decoding. if source.last() != Some(&0) { // Explicitly push sentinel of zero if let Some((d_used, _s_used)) = dec.push(&[0]).or(Err(()))? { return Ok(d_used) } } // Nope, no early message, no missing terminator, just failed to decode Err(()) } /// A report of the source and destination bytes used during in-place decoding #[derive(Debug)] pub struct DecodeReport { // The number of source bytes used, NOT INCLUDING the sentinel byte, // if there was one. pub src_used: usize, // The number of bytes of the source buffer that now include the // decoded result pub dst_used: usize, } /// Decodes a message in-place. /// /// This is the same function as `decode_in_place`, but provides a report /// of both the number of source bytes consumed as well as the size of the /// destination used. pub fn decode_in_place_report(buff: &mut[u8]) -> Result { Ok(decode_raw!(buff, buff)) } /// Decodes a message in-place. /// /// This is the same function as `decode`, but replaces the encoded message /// with the decoded message instead of writing to another buffer. /// /// The returned `usize` is the number of bytes used for the DECODED value, /// NOT the number of source bytes consumed during decoding. pub fn decode_in_place(buff: &mut[u8]) -> Result { Ok(decode_raw!(buff, buff).dst_used) } /// Decodes the `source` buffer into the `dest` buffer using an arbitrary sentinel value. /// /// This is done by XOR-ing each byte of the source message with the chosen sentinel value, /// which transforms the message into the same message encoded with a sentinel value of 0. /// Then the regular decoding transformation is performed. /// /// The returned `usize` is the number of bytes used for the DECODED value, /// NOT the number of source bytes consumed during decoding. pub fn decode_with_sentinel(source: &[u8], dest: &mut[u8], sentinel: u8) -> Result { for (x, y) in source.iter().zip(dest.iter_mut()) { *y = *x ^ sentinel; } decode_in_place(dest) } /// Decodes a message in-place using an arbitrary sentinel value. /// /// The returned `usize` is the number of bytes used for the DECODED value, /// NOT the number of source bytes consumed during decoding. pub fn decode_in_place_with_sentinel(buff: &mut[u8], sentinel: u8) -> Result { for x in buff.iter_mut() { *x ^= sentinel; } decode_in_place(buff) } #[cfg(feature = "use_std")] /// Decodes the `source` buffer into a vector. pub fn decode_vec(source: &[u8]) -> Result, ()> { let mut decoded = vec![0; source.len()]; match decode(source, &mut decoded[..]) { Ok(n) => { decoded.truncate(n); Ok(decoded) }, Err(()) => Err(()), } } #[cfg(feature = "use_std")] /// Decodes the `source` buffer into a vector with an arbitrary sentinel value. pub fn decode_vec_with_sentinel(source: &[u8], sentinel: u8) -> Result, ()> { let mut decoded = vec![0; source.len()]; match decode_with_sentinel(source, &mut decoded[..], sentinel) { Ok(n) => { decoded.truncate(n); Ok(decoded) }, Err(()) => Err(()), } } cobs-0.2.3/src/enc.rs000064400000000000000000000171440072674642500125150ustar 00000000000000#[cfg(feature = "use_std")] use crate::max_encoding_length; /// The [`CobsEncoder`] type is used to encode a stream of bytes to a /// given mutable output slice. This is often useful when heap data /// structures are not available, or when not all message bytes are /// received at a single point in time. #[derive(Debug)] pub struct CobsEncoder<'a> { dest: &'a mut [u8], dest_idx: usize, state: EncoderState, } /// The [`EncoderState`] is used to track the current state of a /// streaming encoder. This struct does not contain the output buffer /// (or a reference to one), and can be used when streaming the encoded /// output to a custom data type /// /// **IMPORTANT NOTE**: When implementing a custom streaming encoder, /// the [`EncoderState`] state machine assumes that the output buffer /// **ALREADY** contains a single placeholder byte, and no other bytes. /// This placeholder byte will be later modified with the first distance /// to the next header/zero byte. #[derive(Clone, Debug)] pub struct EncoderState { code_idx: usize, num_bt_sent: u8, offset_idx: u8, } /// [`PushResult`] is used to represent the changes to an (encoded) /// output data buffer when an unencoded byte is pushed into [`EncoderState`]. pub enum PushResult { /// The returned byte should be placed at the current end of the data buffer AddSingle(u8), /// The byte at the given index should be replaced with the given byte. /// Additionally, a placeholder byte should be inserted at the current /// end of the output buffer to be later modified ModifyFromStartAndSkip((usize, u8)), /// The byte at the given index should be replaced with the given byte. /// Then, the last u8 in this tuple should be inserted at the end of the /// current output buffer. Finally, a placeholder byte should be inserted at /// the current end of the output buffer to be later modified ModifyFromStartAndPushAndSkip((usize, u8, u8)) } impl Default for EncoderState { /// Create a default initial state representation for a COBS encoder fn default() -> Self { Self { code_idx: 0, num_bt_sent: 1, offset_idx: 1, } } } impl EncoderState { /// Push a single unencoded byte into the encoder state machine pub fn push(&mut self, data: u8) -> PushResult { if data == 0 { let ret = PushResult::ModifyFromStartAndSkip((self.code_idx, self.num_bt_sent)); self.code_idx += usize::from(self.offset_idx); self.num_bt_sent = 1; self.offset_idx = 1; ret } else { self.num_bt_sent += 1; self.offset_idx += 1; if 0xFF == self.num_bt_sent { let ret = PushResult::ModifyFromStartAndPushAndSkip((self.code_idx, self.num_bt_sent, data)); self.num_bt_sent = 1; self.code_idx += usize::from(self.offset_idx); self.offset_idx = 1; ret } else { PushResult::AddSingle(data) } } } /// Finalize the encoding process for a single message. /// The byte at the given index should be replaced with the given value, /// and the sentinel value (typically 0u8) must be inserted at the current /// end of the output buffer, serving as a framing byte. pub fn finalize(self) -> (usize, u8) { (self.code_idx, self.num_bt_sent) } } impl<'a> CobsEncoder<'a> { /// Create a new streaming Cobs Encoder pub fn new(out_buf: &'a mut [u8]) -> CobsEncoder<'a> { CobsEncoder { dest: out_buf, dest_idx: 1, state: EncoderState::default(), } } /// Push a slice of data to be encoded pub fn push(&mut self, data: &[u8]) -> Result<(), ()> { // TODO: could probably check if this would fit without // iterating through all data for x in data { use PushResult::*; match self.state.push(*x) { AddSingle(y) => { *self.dest.get_mut(self.dest_idx) .ok_or_else(|| ())? = y; } ModifyFromStartAndSkip((idx, mval)) => { *self.dest.get_mut(idx) .ok_or_else(|| ())? = mval; } ModifyFromStartAndPushAndSkip((idx, mval, nval1)) => { *self.dest.get_mut(idx) .ok_or_else(|| ())? = mval; *self.dest.get_mut(self.dest_idx) .ok_or_else(|| ())? = nval1; self.dest_idx += 1; } } // All branches above require advancing the pointer at least once self.dest_idx += 1; } Ok(()) } /// Complete encoding of the output message. Does NOT terminate /// the message with the sentinel value pub fn finalize(self) -> Result { if self.dest_idx == 1 { return Ok(0); } // Get the last index that needs to be fixed let (idx, mval) = self.state.finalize(); // If the current code index is outside of the destination slice, // we do not need to write it out if let Some(i) = self.dest.get_mut(idx) { *i = mval; } return Ok(self.dest_idx); } } /// Encodes the `source` buffer into the `dest` buffer. /// /// This function uses the typical sentinel value of 0. It returns the number of bytes /// written to in the `dest` buffer. /// /// # Panics /// /// This function will panic if the `dest` buffer is not large enough for the /// encoded message. You can calculate the size the `dest` buffer needs to be with /// the `max_encoding_length` function. pub fn encode(source: &[u8], dest: &mut[u8]) -> usize { let mut enc = CobsEncoder::new(dest); enc.push(source).unwrap(); enc.finalize().unwrap() } /// Attempts to encode the `source` buffer into the `dest` buffer. /// /// This function uses the typical sentinel value of 0. It returns the number of bytes /// written to in the `dest` buffer. /// /// If the destination buffer does not have enough room, an error will be returned pub fn try_encode(source: &[u8], dest: &mut[u8]) -> Result { let mut enc = CobsEncoder::new(dest); enc.push(source)?; enc.finalize() } /// Encodes the `source` buffer into the `dest` buffer using an /// arbitrary sentinel value. /// /// This is done by first encoding the message with the typical sentinel value /// of 0, then XOR-ing each byte of the encoded message with the chosen sentinel /// value. This will ensure that the sentinel value doesn't show up in the encoded /// message. See the paper "Consistent Overhead Byte Stuffing" for details. pub fn encode_with_sentinel(source: &[u8], dest: &mut[u8], sentinel: u8) -> usize { let encoded_size = encode(source, dest); for x in &mut dest[..encoded_size] { *x ^= sentinel; } return encoded_size; } #[cfg(feature = "use_std")] /// Encodes the `source` buffer into a vector. pub fn encode_vec(source: &[u8]) -> Vec { let mut encoded = vec![0; max_encoding_length(source.len())]; let encoded_len = encode(source, &mut encoded[..]); encoded.truncate(encoded_len); return encoded; } #[cfg(feature = "use_std")] /// Encodes the `source` buffer into a vector with an arbitrary sentinel value. pub fn encode_vec_with_sentinel(source: &[u8], sentinel: u8) -> Vec { let mut encoded = vec![0; max_encoding_length(source.len())]; let encoded_len = encode_with_sentinel(source, &mut encoded[..], sentinel); encoded.truncate(encoded_len); return encoded; } cobs-0.2.3/src/lib.rs000064400000000000000000000007610072674642500125130ustar 00000000000000#![cfg_attr(not(feature = "use_std"), no_std)] // In the future, don't do this. mod dec; mod enc; pub use crate::dec::*; pub use crate::enc::*; /// Calculates the maximum possible size of an encoded message given the length /// of the source message. This may be useful for calculating how large the /// `dest` buffer needs to be in the encoding functions. pub fn max_encoding_length(source_len: usize) -> usize { source_len + (source_len / 254) + if source_len % 254 > 0 { 1 } else { 0 } } cobs-0.2.3/tests/test.rs000064400000000000000000000151000072674642500132700ustar 00000000000000extern crate cobs; extern crate quickcheck; use quickcheck::{quickcheck, TestResult}; use cobs::{max_encoding_length, encode, decode, encode_vec, decode_vec}; use cobs::{encode_vec_with_sentinel, decode_vec_with_sentinel}; use cobs::{CobsEncoder, CobsDecoder}; fn test_pair(source: Vec, encoded: Vec) { let mut test_encoded = encoded.clone(); let mut test_decoded = source.clone(); // Mangle data to ensure data is re-populated correctly test_encoded.iter_mut().for_each(|i| *i = 0x80); encode(&source[..], &mut test_encoded[..]); // Mangle data to ensure data is re-populated correctly test_decoded.iter_mut().for_each(|i| *i = 0x80); decode(&encoded[..], &mut test_decoded[..]).unwrap(); assert_eq!(encoded, test_encoded); assert_eq!(source, test_decoded); } fn test_roundtrip(source: Vec) { let encoded = encode_vec(&source); let decoded = decode_vec(&encoded).expect("decode_vec"); assert_eq!(source, decoded); } #[test] fn decode_malforemd() { let malformed_buf: [u8;32] = [68, 69, 65, 68, 66, 69, 69, 70, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]; let mut dest_buf : [u8;32] = [0;32]; if let Err(()) = decode(&malformed_buf, &mut dest_buf){ return; } else { assert!(false, "invalid test result."); } } #[test] fn stream_roundtrip() { for ct in 1..=1000 { let source: Vec = (ct..2*ct) .map(|x: usize| (x & 0xFF) as u8) .collect(); let mut dest = vec![0u8; max_encoding_length(source.len())]; let sz_en = { let mut ce = CobsEncoder::new(&mut dest); for c in source.chunks(17) { ce.push(c).unwrap(); } let sz = ce.finalize().unwrap(); sz }; let mut decoded = source.clone(); decoded.iter_mut().for_each(|i| *i = 0x80); let sz_de = { let mut cd = CobsDecoder::new(&mut decoded); for c in dest[0..sz_en].chunks(11) { cd.push(c).unwrap(); } let sz_msg = cd.feed(0).unwrap().unwrap(); sz_msg }; assert_eq!(sz_de, source.len()); assert_eq!(source, decoded); } } #[test] fn test_max_encoding_length() { assert_eq!(max_encoding_length(253), 254); assert_eq!(max_encoding_length(254), 255); assert_eq!(max_encoding_length(255), 257); assert_eq!(max_encoding_length(254 * 2), 255 * 2); assert_eq!(max_encoding_length(254 * 2 + 1), 256 * 2); } #[test] fn test_encode_1() { test_pair(vec![10, 11, 0, 12], vec![3, 10, 11, 2, 12]) } #[test] fn test_encode_2() { test_pair(vec![0, 0, 1, 0], vec![1, 1, 2, 1, 1]) } #[test] fn test_encode_3() { test_pair(vec![255, 0], vec![2, 255, 1]) } #[test] fn test_encode_4() { test_pair(vec![1], vec![2, 1]) } #[test] fn test_roundtrip_1() { test_roundtrip(vec![1,2,3]); } #[test] fn test_roundtrip_2() { for i in 0..5usize { let mut v = Vec::new(); for j in 0..252+i { v.push(j as u8); } test_roundtrip(v); } } fn identity(source: Vec, sentinel: u8) -> TestResult { let encoded = encode_vec_with_sentinel(&source[..], sentinel); // Check that the sentinel doesn't show up in the encoded message for x in encoded.iter() { if *x == sentinel { return TestResult::error("Sentinel found in encoded message."); } } // Check that the decoding the encoded message returns the original message match decode_vec_with_sentinel(&encoded[..], sentinel) { Ok(decoded) => { if source == decoded { TestResult::passed() } else { TestResult::failed() } } Err(_) => TestResult::error("Decoding Error"), } } #[test] fn test_encode_decode_with_sentinel() { quickcheck(identity as fn(Vec, u8) -> TestResult); } #[test] fn test_encode_decode() { fn identity_default_sentinel(source: Vec) -> TestResult { identity(source, 0) } quickcheck(identity_default_sentinel as fn(Vec) -> TestResult); } #[test] fn wikipedia_ex_6() { let mut unencoded: Vec = vec![]; (1..=0xFE).for_each(|i| unencoded.push(i)); // NOTE: trailing 0x00 is implicit let mut encoded: Vec = vec![]; encoded.push(0xFF); (1..=0xFE).for_each(|i| encoded.push(i)); test_pair(unencoded, encoded); } #[test] fn wikipedia_ex_7() { let mut unencoded: Vec = vec![]; (0..=0xFE).for_each(|i| unencoded.push(i)); // NOTE: trailing 0x00 is implicit let mut encoded: Vec = vec![]; encoded.push(0x01); encoded.push(0xFF); (1..=0xFE).for_each(|i| encoded.push(i)); test_pair(unencoded, encoded); } #[test] fn wikipedia_ex_8() { let mut unencoded: Vec = vec![]; (1..=0xFF).for_each(|i| unencoded.push(i)); // NOTE: trailing 0x00 is implicit let mut encoded: Vec = vec![]; encoded.push(0xFF); (1..=0xFE).for_each(|i| encoded.push(i)); encoded.push(0x02); encoded.push(0xFF); test_pair(unencoded, encoded); } #[test] fn wikipedia_ex_9() { let mut unencoded: Vec = vec![]; (2..=0xFF).for_each(|i| unencoded.push(i)); unencoded.push(0x00); // NOTE: trailing 0x00 is implicit let mut encoded: Vec = vec![]; encoded.push(0xFF); (2..=0xFF).for_each(|i| encoded.push(i)); encoded.push(0x01); encoded.push(0x01); test_pair(unencoded, encoded); } #[test] fn wikipedia_ex_10() { let mut unencoded: Vec = vec![]; (3..=0xFF).for_each(|i| unencoded.push(i)); unencoded.push(0x00); unencoded.push(0x01); // NOTE: trailing 0x00 is implicit let mut encoded: Vec = vec![]; encoded.push(0xFE); (3..=0xFF).for_each(|i| encoded.push(i)); encoded.push(0x02); encoded.push(0x01); test_pair(unencoded, encoded); } #[test] fn issue_15() { // Reported: https://github.com/awelkie/cobs.rs/issues/15 let my_string_buf = b"\x00\x11\x00\x22"; let max_len = cobs::max_encoding_length(my_string_buf.len()); assert!(max_len < 128); let mut buf = [0u8; 128]; let len = cobs::encode_with_sentinel( my_string_buf, &mut buf, b'\x00'); let cobs_buf = &buf[0..len]; let mut decoded_dest_buf = [0u8; 128]; let new_len = cobs::decode_with_sentinel( cobs_buf, &mut decoded_dest_buf, b'\x00').unwrap(); let decoded_buf = &decoded_dest_buf[0..new_len]; println!("{:?} {:?} {:?}", my_string_buf, cobs_buf, decoded_buf); assert_eq!(my_string_buf, decoded_buf); }