blobby-0.3.1/.cargo_vcs_info.json0000644000000001440000000000100123050ustar { "git": { "sha1": "2a2dd109ac6a4c1428804e33ea8a7fe8b7fa9bcf" }, "path_in_vcs": "blobby" }blobby-0.3.1/CHANGELOG.md000064400000000000000000000013470072674642500127440ustar 00000000000000# Changelog All notable changes to this project will be documented in this file. The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/), and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html). ## 0.3.1 (2021-12-07) ### Added - `encode_blobs` function ([#280]) [#280]: https://github.com/RustCrypto/utils/pull/280 ## 0.3.0 (2020-07-01) ### Changed - New storage format with de-duplication capability ([#64]) [#64]: https://github.com/RustCrypto/utils/pull/64 ## 0.2.0 (2020-06-13) ### Added - `Blob5Iterator` ### Changed - Bumped MSRV to 1.34. - Removed `byteorder` from non-dev dependencies. ## 0.1.2 (2019-01-28) ## 0.1.1 (2018-09-26) ## 0.1.0 (2018-09-26) - Initial release blobby-0.3.1/Cargo.lock0000644000000005540000000000100102650ustar # This file is automatically @generated by Cargo. # It is not intended for manual editing. version = 3 [[package]] name = "blobby" version = "0.3.1" dependencies = [ "hex", ] [[package]] name = "hex" version = "0.4.3" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "7f24254aa9a54b5c858eaee2f5bccdb46aaf0e486a595ed5fd8f86ba55232a70" blobby-0.3.1/Cargo.toml0000644000000014460000000000100103110ustar # 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 = "blobby" version = "0.3.1" authors = ["RustCrypto Developers"] description = "Iterator over simple binary blob storage" documentation = "https://docs.rs/blobby" categories = ["no-std"] license = "MIT OR Apache-2.0" repository = "https://github.com/RustCrypto/utils" [dev-dependencies.hex] version = "0.4" blobby-0.3.1/Cargo.toml.orig000064400000000000000000000006040072674642500140150ustar 00000000000000[package] name = "blobby" version = "0.3.1" # Also update html_root_url in lib.rs when bumping this authors = ["RustCrypto Developers"] license = "MIT OR Apache-2.0" description = "Iterator over simple binary blob storage" documentation = "https://docs.rs/blobby" repository = "https://github.com/RustCrypto/utils" categories = ["no-std"] edition = "2018" [dev-dependencies] hex = "0.4" blobby-0.3.1/LICENSE-APACHE000064400000000000000000000251410072674642500130550ustar 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. blobby-0.3.1/LICENSE-MIT000064400000000000000000000020720072674642500125630ustar 00000000000000Copyright (c) 2018-2019 The RustCrypto Project 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. blobby-0.3.1/examples/convert.rs000064400000000000000000000036650072674642500150040ustar 00000000000000//! Convert utility use blobby::{encode_blobs, BlobIterator}; use std::io::{self, BufRead, BufReader, BufWriter, Write}; use std::{env, error::Error, fs::File}; fn encode(reader: impl BufRead, mut writer: impl Write) -> io::Result { let mut blobs = Vec::new(); for line in reader.lines() { let blob = hex::decode(line?.as_str()) .map_err(|e| io::Error::new(io::ErrorKind::InvalidData, e))?; blobs.push(blob); } let (data, idx_len) = encode_blobs(&blobs); let data_len = data.len(); println!("Index len: {:?}", idx_len); writer.write_all(&data).map(|_| data_len) } fn decode(mut reader: R, mut writer: W) -> io::Result { let mut data = Vec::new(); reader.read_to_end(&mut data)?; let res: Vec<_> = BlobIterator::new(&data) .map_err(|e| { io::Error::new( io::ErrorKind::InvalidData, format!("invalid blobby data: {:?}", e), ) })? .collect(); for blob in res.iter() { let blob = blob.map_err(|e| { io::Error::new( io::ErrorKind::InvalidData, format!("invalid blobby data: {:?}", e), ) })?; writer.write_all(hex::encode(blob).as_bytes())?; writer.write_all(b"\n")?; } Ok(res.len()) } fn main() -> Result<(), Box> { let args: Vec = env::args().skip(1).collect(); let is_encode = match args[0].as_str() { "encode" => true, "decode" => false, _ => Err("unknown mode")?, }; let in_path = args[1].as_str(); let out_path = args[2].as_str(); let in_file = BufReader::new(File::open(in_path)?); let out_file = BufWriter::new(File::create(out_path)?); let n = if is_encode { encode(in_file, out_file)? } else { decode(in_file, out_file)? }; println!("Processed {} record(s)", n); Ok(()) } blobby-0.3.1/src/lib.rs000064400000000000000000000273500072674642500130400ustar 00000000000000//! Iterators over a simple binary blob storage. //! //! # Storage format //! Storage format represents a sequence of binary blobs. The format uses //! git-flavored [variable-length quantity][0] (VLQ) for encoding unsigned //! numbers. //! //! File starts with a number of de-duplicated blobs `d`. It followed by `d` //! entries. Each entry starts with an integer `m`, immediately folowed by `m` //! bytes representing de-duplicated binary blob. //! //! Next follows unspecified number of entries representing sequence of stored //! blobs. Each entry starts with an unsigned integer `n`. The least significant //! bit of this integer is used as a flag. If the flag is equal to 0, then the //! number is followed by `n >> 1` bytes, representing a stored binary blob. //! Otherwise the entry references a de-duplicated entry number `n >> 1`. //! //! # Examples //! ``` //! let buf = b"\x02\x05hello\x06world!\x01\x02 \x00\x03\x06:::\x03\x01\x00"; //! let mut v = blobby::BlobIterator::new(buf).unwrap(); //! assert_eq!(v.next(), Some(Ok(&b"hello"[..]))); //! assert_eq!(v.next(), Some(Ok(&b" "[..]))); //! assert_eq!(v.next(), Some(Ok(&b""[..]))); //! assert_eq!(v.next(), Some(Ok(&b"world!"[..]))); //! assert_eq!(v.next(), Some(Ok(&b":::"[..]))); //! assert_eq!(v.next(), Some(Ok(&b"world!"[..]))); //! assert_eq!(v.next(), Some(Ok(&b"hello"[..]))); //! assert_eq!(v.next(), Some(Ok(&b""[..]))); //! assert_eq!(v.next(), None); //! //! let mut v = blobby::Blob2Iterator::new(buf).unwrap(); //! assert_eq!(v.next(), Some(Ok([&b"hello"[..], b" "]))); //! assert_eq!(v.next(), Some(Ok([&b""[..], b"world!"]))); //! assert_eq!(v.next(), Some(Ok([&b":::"[..], b"world!"]))); //! assert_eq!(v.next(), Some(Ok([&b"hello"[..], b""]))); //! assert_eq!(v.next(), None); //! //! let mut v = blobby::Blob4Iterator::new(buf).unwrap(); //! assert_eq!(v.next(), Some(Ok([&b"hello"[..], b" ", b"", b"world!"]))); //! assert_eq!(v.next(), Some(Ok([&b":::"[..], b"world!", b"hello", b""]))); //! assert_eq!(v.next(), None); //! ``` //! //! [0]: https://en.wikipedia.org/wiki/Variable-length_quantity #![no_std] #![doc( html_logo_url = "https://raw.githubusercontent.com/RustCrypto/media/6ee8e381/logo.svg", html_favicon_url = "https://raw.githubusercontent.com/RustCrypto/media/6ee8e381/logo.svg", html_root_url = "https://docs.rs/blobby/0.3.1" )] extern crate alloc; use alloc::{boxed::Box, collections::BTreeMap, vec, vec::Vec}; use core::iter::Iterator; /// Iterator over binary blobs pub struct BlobIterator<'a> { data: &'a [u8], dedup: Box<[&'a [u8]]>, pos: usize, } /// `blobby` error type #[derive(Debug, Eq, PartialEq, Copy, Clone)] pub enum Error { /// Decoded VLQ number is too big InvalidVlq, /// Invalid de-duplicated blob index InvalidIndex, /// Unexpected end of data UnexpectedEnd, /// Not enough elements for `BlobNIterator` NotEnoughElements, } const NEXT_MASK: u8 = 0b1000_0000; const VAL_MASK: u8 = 0b0111_1111; /// Read a git-flavoured VLQ value from `&data[*pos..]`. /// Increments `pos` to a number of read bytes. /// /// This function returns `None` if buffer does not contain enough bytes /// or if VLQ is bigger than 4 bytes. /// /// See the test submodule for example values. fn read_vlq(data: &[u8], pos: &mut usize) -> Result { let b = data.get(*pos).ok_or(Error::UnexpectedEnd)?; *pos += 1; let mut next = b & NEXT_MASK; let mut val = (b & VAL_MASK) as usize; macro_rules! step { () => { if next == 0 { return Ok(val); } let b = data.get(*pos).ok_or(Error::UnexpectedEnd)?; *pos += 1; next = b & NEXT_MASK; let t = (b & VAL_MASK) as usize; val = ((val + 1) << 7) + t; }; } step!(); step!(); step!(); if next != 0 { return Err(Error::InvalidVlq); } Ok(val) } /// Write a git-flavoured VLQ value into `buf`. /// /// Returns the slice within `buf` that holds the value. fn encode_vlq(mut val: usize, buf: &mut [u8; 4]) -> &[u8] { macro_rules! step { ($n:expr) => { buf[$n] = if $n == 3 { (val & (VAL_MASK as usize)) as u8 } else { val -= 1; NEXT_MASK | (val & (VAL_MASK as usize)) as u8 }; val >>= 7; if val == 0 { return &buf[$n..]; } }; } step!(3); step!(2); step!(1); step!(0); panic!("integer is too big") } /// Encode the given collection of binary blobs in .blb format into `writer`. /// Returns the encoded data together with a count of the number of blobs included in the index. /// /// The encoded file format is: /// - count of index entries=N /// - N x index entries, each encoded as: /// - size L of index entry (VLQ) /// - index blob contents (L bytes) /// - repeating encoded blobs, each encoded as: /// - VLQ value that is either: /// - (J << 1) & 0x01: indicates this blob is index entry J /// - (L << 1) & 0x00: indicates an explicit blob of len L /// - (in the latter case) explicit blob contents (L bytes) pub fn encode_blobs<'a, I, T: 'a>(blobs: &'a I) -> (Vec, usize) where &'a I: IntoIterator, T: AsRef<[u8]>, { let mut idx_map = BTreeMap::new(); blobs .into_iter() .map(|v| v.as_ref()) .filter(|blob| !blob.is_empty()) .for_each(|blob| { let v = idx_map.entry(blob.as_ref()).or_insert(0); *v += 1; }); let mut idx: Vec<&[u8]> = idx_map .iter() .filter(|(_, &v)| v > 1) .map(|(&k, _)| k) .collect(); idx.sort_by_key(|e| { let k = match e { [0] => 2, [1] => 1, _ => 0, }; (k, idx_map.get(e).unwrap()) }); idx.reverse(); let idx_len = idx.len(); let rev_idx: BTreeMap<&[u8], usize> = idx.iter().enumerate().map(|(i, &e)| (e, i)).collect(); let mut out_buf = Vec::new(); let mut buf = [0u8; 4]; out_buf.extend_from_slice(encode_vlq(idx.len(), &mut buf)); for e in idx { out_buf.extend_from_slice(encode_vlq(e.len(), &mut buf)); out_buf.extend_from_slice(e); } for blob in blobs.into_iter().map(|v| v.as_ref()) { if let Some(dup_pos) = rev_idx.get(blob) { let n = (dup_pos << 1) + 1usize; out_buf.extend_from_slice(encode_vlq(n, &mut buf)); } else { let n = blob.len() << 1; out_buf.extend_from_slice(encode_vlq(n, &mut buf)); out_buf.extend_from_slice(blob); } } (out_buf, idx_len) } impl<'a> BlobIterator<'a> { /// Create new `BlobIterator` for given `data`. pub fn new(data: &'a [u8]) -> Result { let mut pos = 0; let dedup_n = read_vlq(data, &mut pos)?; let mut dedup: Vec<&[u8]> = vec![&[]; dedup_n]; for entry in dedup.iter_mut() { let m = read_vlq(data, &mut pos).unwrap(); *entry = &data[pos..pos + m]; pos += m; } Ok(BlobIterator { data: &data[pos..], dedup: dedup.into_boxed_slice(), pos: 0, }) } fn read(&mut self) -> Result<&'a [u8], Error> { let val = read_vlq(self.data, &mut self.pos).unwrap(); // the least significant bit is used as a flag let is_ref = (val & 1) != 0; let val = val >> 1; if is_ref { if val >= self.dedup.len() { return Err(Error::InvalidIndex); } Ok(self.dedup[val]) } else { let s = self.pos; self.pos += val; Ok(self.data.get(s..self.pos).ok_or(Error::UnexpectedEnd)?) } } fn error_block(&mut self) { self.pos = self.data.len(); } } impl<'a> Iterator for BlobIterator<'a> { type Item = Result<&'a [u8], Error>; fn next(&mut self) -> Option { if self.pos < self.data.len() { let val = self.read(); if val.is_err() { self.error_block() } Some(val) } else { None } } } // TODO: use const generics on stabilization // docs are not generated due to https://github.com/rust-lang/rust/issues/52607 macro_rules! new_iter { ($name:ident, $n:expr) => { pub struct $name<'a> { inner: BlobIterator<'a>, } impl<'a> $name<'a> { pub fn new(data: &'a [u8]) -> Result { BlobIterator::new(data).map(|inner| Self { inner }) } } impl<'a> Iterator for $name<'a> { type Item = Result<[&'a [u8]; $n], Error>; fn next(&mut self) -> Option { let mut res: [&[u8]; $n] = Default::default(); for (i, v) in res.iter_mut().enumerate() { *v = match self.inner.next() { Some(Ok(val)) => val, Some(Err(e)) => return Some(Err(e)), None if i == 0 => return None, None => { self.inner.error_block(); return Some(Err(Error::NotEnoughElements)); } }; } Some(Ok(res)) } } }; } new_iter!(Blob2Iterator, 2); new_iter!(Blob3Iterator, 3); new_iter!(Blob4Iterator, 4); new_iter!(Blob5Iterator, 5); new_iter!(Blob6Iterator, 6); #[cfg(test)] mod tests { use super::{read_vlq, Error, NEXT_MASK, VAL_MASK}; fn encode_vlq(mut val: usize, buf: &mut [u8; 4]) -> &[u8] { macro_rules! step { ($n:expr) => { buf[$n] = if $n == 3 { (val & (VAL_MASK as usize)) as u8 } else { val -= 1; NEXT_MASK | (val & (VAL_MASK as usize)) as u8 }; val >>= 7; if val == 0 { return &buf[$n..]; } }; } step!(3); step!(2); step!(1); step!(0); panic!("integer is too big") } #[test] fn encode_decode() { let mut buf = [0u8; 4]; for val in 0..=270549119 { let res = encode_vlq(val, &mut buf); let val_res = read_vlq(res, &mut 0).unwrap(); assert_eq!(val, val_res); } } #[test] #[rustfmt::skip] fn test_vlq() { let mut pos = 0; let examples = [ 0b0000_0000, // 0 0b0000_0010, // 2 0b0111_1111, // 127 0b1000_0000, 0b0000_0000, // 128 0b1111_1111, 0b0111_1111, // 16511 0b1000_0000, 0b1000_0000, 0b0000_0000, // 16512 0b1111_1111, 0b1111_1111, 0b0111_1111, // 2113663 0b1000_0000, 0b1000_0000, 0b1000_0000, 0b0000_0000, // 2113664 0b1111_1111, 0b1111_1111, 0b1111_1111, 0b0111_1111, // 270549119 0b1111_1111, 0b1111_1111, 0b1111_1111, 0b1111_1111, 0b0111_1111, ]; let targets = [ (0, 1), (2, 1), (127, 1), (128, 2), (16511, 2), (16512, 3), (2113663, 3), (2113664, 4), (270549119, 4), ]; let mut buf = [0u8; 4]; for &(val, size) in targets.iter() { let prev_pos = pos; assert_eq!(read_vlq(&examples, &mut pos), Ok(val)); assert_eq!(pos - prev_pos, size); assert_eq!(encode_vlq(val, &mut buf), &examples[prev_pos..pos]); } // only VLQ values of up to 4 bytes are supported assert_eq!(read_vlq(&examples, &mut pos), Err(Error::InvalidVlq)); assert_eq!(pos, 25); } }