blobby-0.4.0/.cargo_vcs_info.json0000644000000001440000000000100123050ustar { "git": { "sha1": "c210dd6c674fdb039e3d19ad4bec818be1faeafe" }, "path_in_vcs": "blobby" }blobby-0.4.0/CHANGELOG.md000064400000000000000000000021721046102023000127110ustar 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.4.0 (2025-10-08) ### Changed - Edition changed to 2024 and MSRV bumped to 1.85 ([#1149]) - Replaced iterators with `const fn` parsing ([#1187]) - Format of the file. File header now contains total number of stored blobs. ([#1207]) [#1149]: https://github.com/RustCrypto/utils/pull/1149 [#1187]: https://github.com/RustCrypto/utils/pull/1187 [#1207]: https://github.com/RustCrypto/utils/pull/1207 ## 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.4.0/Cargo.lock0000644000000002260000000000100102610ustar # This file is automatically @generated by Cargo. # It is not intended for manual editing. version = 4 [[package]] name = "blobby" version = "0.4.0" blobby-0.4.0/Cargo.toml0000644000000021530000000000100103050ustar # 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 = "2024" rust-version = "1.85" name = "blobby" version = "0.4.0" authors = ["RustCrypto Developers"] build = false autolib = false autobins = false autoexamples = false autotests = false autobenches = false description = "Iterator over simple binary blob storage" documentation = "https://docs.rs/blobby" readme = "README.md" categories = ["no-std"] license = "MIT OR Apache-2.0" repository = "https://github.com/RustCrypto/utils" [features] alloc = [] [lib] name = "blobby" path = "src/lib.rs" [[bin]] name = "decode" path = "src/bin/decode.rs" [[bin]] name = "encode" path = "src/bin/encode.rs" [[test]] name = "mod" path = "tests/mod.rs" blobby-0.4.0/Cargo.toml.orig000064400000000000000000000005561046102023000137730ustar 00000000000000[package] name = "blobby" version = "0.4.0" authors = ["RustCrypto Developers"] edition = "2024" rust-version = "1.85" documentation = "https://docs.rs/blobby" readme = "README.md" repository = "https://github.com/RustCrypto/utils" license = "MIT OR Apache-2.0" categories = ["no-std"] description = "Iterator over simple binary blob storage" [features] alloc = [] blobby-0.4.0/LICENSE-APACHE000064400000000000000000000251411046102023000130250ustar 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.4.0/LICENSE-MIT000064400000000000000000000020721046102023000125330ustar 00000000000000Copyright (c) 2018-2025 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.4.0/README.md000064400000000000000000000114311046102023000123550ustar 00000000000000# [RustCrypto]: Blobby [![crate][crate-image]][crate-link] [![Docs][docs-image]][docs-link] [![Build Status][build-image]][build-link] ![Apache2/MIT licensed][license-image] ![Rust Version][rustc-image] [![Project Chat][chat-image]][chat-link] An encoding and decoding library for the Blobby (`blb`) file format, which serves as a simple, deduplicated storage format for a sequence of binary blobs. ## Examples ```rust // We recommend to save blobby data into separate files and // use the `include_bytes!` macro static BLOBBY_DATA: &[u8; 27] = b"\x08\x02\x05hello\x06world!\x01\x02 \x00\x03\x06:::\x03\x01\x00"; static SLICE: &[&[u8]] = blobby::parse_into_slice!(BLOBBY_DATA); assert_eq!(SLICE[0], b"hello".as_slice()); assert_eq!(SLICE[1], b" ".as_slice()); assert_eq!(SLICE[2], b"".as_slice()); assert_eq!(SLICE[3], b"world!".as_slice()); assert_eq!(SLICE[4], b":::".as_slice()); assert_eq!(SLICE[5], b"world!".as_slice()); assert_eq!(SLICE[6], b"hello".as_slice()); assert_eq!(SLICE[7], b"".as_slice()); assert_eq!(SLICE.len(), 8); blobby::parse_into_structs!( BLOBBY_DATA; #[define_struct] static ITEMS: &[Item { a, b, c, d }]; ); assert_eq!( ITEMS[0], Item { a: b"hello", b: b" ", c: b"", d: b"world!", }, ); assert_eq!( ITEMS[1], Item { a: b":::", b: b"world!", c: b"hello", d: b"", }, ); assert_eq!(ITEMS.len(), 2); ``` ## Encoding and decoding utilities This crate provides encoding and decoding utilities for converting between the blobby format and text file with hex-encoded strings. Let's say we have the following test vectors for a 64-bit hash function: ```text COUNT = 0 INPUT = 0123456789ABCDEF0123456789ABCDEF OUTPUT = 217777950848CECD COUNT = 1 INPUT = OUTPUT = F7CD1446C9161C0A COUNT = 2 INPUT = FFFEFD OUTPUT = 80081C35AA43F640 ``` To transform it into the Blobby format you first have to modify it to the following format: ```text 0123456789ABCDEF0123456789ABCDEF 217777950848CECD F7CD1446C9161C0A FFFEFD 80081C35AA43F640 ``` The first, third, and fifth lines are hex-encoded hash inputs, while the second, fourth, and sixth lines are hex-encoded hash outputs for input on the previous line. Note that the file should contain a trailing empty line (i.e. every data line should end with `\n`). This file can be converted to the Blobby format by running the following command: ```sh cargo run --release --features alloc --bin encode -- /path/to/input.txt /path/to/output.blb ``` To inspect contents of an existing Blobby file you can use the following command: ```sh cargo run --release --features alloc --bin decode -- /path/to/input.blb /path/to/output.txt ``` The output file will contain a sequence of hex-encoded byte strings stored in the input file. ## Storage format Storage format represents a sequence of binary blobs. The format uses git-flavored [variable-length quantity][VLQ] (VLQ) for encoding unsigned numbers. Blobby files start with two numbers: total number of blobs in the file `n` and number of de-duplicated blobs `d`. The numbers are followed by `d` entries. Each entry starts with an integer `m`, immediately followed by `m` bytes representing de-duplicated binary blob. Next, follows `n` entries representing sequence of stored blobs. Each entry starts with an unsigned integer `l`. 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` which should be smaller than `d`. [VLQ]: https://en.wikipedia.org/wiki/Variable-length_quantity ## License Licensed under either of: * [Apache License, Version 2.0](http://www.apache.org/licenses/LICENSE-2.0) * [MIT license](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. [//]: # (badges) [crate-image]: https://img.shields.io/crates/v/blobby.svg [crate-link]: https://crates.io/crates/blobby [docs-image]: https://docs.rs/blobby/badge.svg [docs-link]: https://docs.rs/blobby/ [license-image]: https://img.shields.io/badge/license-Apache2.0/MIT-blue.svg [rustc-image]: https://img.shields.io/badge/rustc-1.85+-blue.svg [chat-image]: https://img.shields.io/badge/zulip-join_chat-blue.svg [chat-link]: https://rustcrypto.zulipchat.com/#narrow/stream/260052-utils [build-image]: https://github.com/RustCrypto/utils/actions/workflows/blobby.yml/badge.svg?branch=master [build-link]: https://github.com/RustCrypto/utils/actions/workflows/blobby.yml?query=branch:master [//]: # (general links) [RustCrypto]: https://github.com/rustcrypto blobby-0.4.0/src/bin/decode.rs000064400000000000000000000032161046102023000142300ustar 00000000000000//! Encoding utility use std::error::Error; #[cfg(not(feature = "alloc"))] fn main() -> Result<(), Box> { Err("The decode binary should be compiled with enabled `alloc` feature!".into()) } #[cfg(feature = "alloc")] fn main() -> Result<(), Box> { use std::io::{self, BufRead, BufReader, BufWriter, Write}; use std::{env, fs::File}; fn encode_hex(data: &[u8]) -> String { let mut res = String::with_capacity(2 * data.len()); for &byte in data { res.push_str(&format!("{byte:02X}")); } res } fn decode(mut reader: R, mut writer: W) -> io::Result { let mut data = Vec::new(); reader.read_to_end(&mut data)?; let res = blobby::parse_into_vec(&data).map_err(|e| { io::Error::new( io::ErrorKind::InvalidData, format!("invalid blobby data: {e:?}"), ) })?; let len = res.len(); for blob in res { writer.write_all(encode_hex(blob).as_bytes())?; writer.write_all(b"\n")?; } Ok(len) } let args: Vec = env::args().skip(1).collect(); if args.is_empty() { println!( "Blobby decoding utility.\n\ Usage: decode " ); return Ok(()); } let in_path = args[0].as_str(); let out_path = args[1].as_str(); let in_file = BufReader::new(File::open(in_path)?); let out_file = BufWriter::new(File::create(out_path)?); let n = decode(in_file, out_file)?; println!("Processed {n} record(s)"); Ok(()) } blobby-0.4.0/src/bin/encode.rs000064400000000000000000000042751046102023000142500ustar 00000000000000//! Encoding utility use std::error::Error; #[cfg(not(feature = "alloc"))] fn main() -> Result<(), Box> { Err("The encode binary should be compiled with enabled `alloc` feature!".into()) } #[cfg(feature = "alloc")] fn main() -> Result<(), Box> { use blobby::encode_blobs; use std::io::{self, BufRead, BufReader, BufWriter, Write}; use std::{env, fs::File}; fn decode_hex_char(b: u8) -> io::Result { let res = match b { b'0'..=b'9' => b - b'0', b'a'..=b'f' => b - b'a' + 10, b'A'..=b'F' => b - b'A' + 10, _ => { let msg = "Invalid hex string: invalid byte {b}"; return Err(io::Error::new(io::ErrorKind::InvalidData, msg)); } }; Ok(res) } fn decode_hex(data: &str) -> io::Result> { if data.len() % 2 != 0 { let msg = "Invalid hex string: length is not even"; return Err(io::Error::new(io::ErrorKind::InvalidData, msg)); } data.as_bytes() .chunks_exact(2) .map(|chunk| { let a = decode_hex_char(chunk[0])?; let b = decode_hex_char(chunk[1])?; Ok((a << 4) | b) }) .collect() } fn encode(reader: impl BufRead, mut writer: impl Write) -> io::Result { let mut blobs = Vec::new(); for line in reader.lines() { let blob = decode_hex(&line?)?; blobs.push(blob); } let (data, idx_len) = encode_blobs(&blobs); println!("Index len: {idx_len:?}"); writer.write_all(&data)?; Ok(blobs.len()) } let args: Vec = env::args().skip(1).collect(); if args.is_empty() { println!( "Blobby encoding utility.\n\ Usage: encode " ); return Ok(()); } let in_path = args[0].as_str(); let out_path = args[1].as_str(); let in_file = BufReader::new(File::open(in_path)?); let out_file = BufWriter::new(File::create(out_path)?); let n = encode(in_file, out_file)?; println!("Processed {n} record(s)"); Ok(()) } blobby-0.4.0/src/decode.rs000064400000000000000000000157761046102023000134760ustar 00000000000000use super::{Error, NEXT_MASK, VAL_MASK}; pub(crate) const fn read_vlq(data: &mut &[u8]) -> Result { let b = match data.split_first() { Some((&b, rest)) => { *data = rest; b } None => return Err(Error::UnexpectedEnd), }; 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 = match data.split_first() { Some((&b, rest)) => { *data = rest; b } None => return Err(Error::UnexpectedEnd), }; 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) } macro_rules! try_read_vlq { ($data:expr) => { match read_vlq(&mut $data) { Ok(v) => v, Err(err) => return Err(err), } }; } /// Blobby file header pub struct Header { /// Number of blobs stored in the file pub items_len: usize, /// Number of deduplicated blobs pub dedup_len: usize, } impl Header { /// Parse blobby header pub const fn parse(data: &mut &[u8]) -> Result { match (read_vlq(data), read_vlq(data)) { (Ok(items_len), Ok(dedup_len)) => Ok(Header { items_len, dedup_len, }), (Err(err), _) | (Ok(_), Err(err)) => Err(err), } } } /// Parse blobby data into an array. pub const fn parse_into_array( mut data: &[u8], ) -> Result<[&[u8]; ITEMS_LEN], Error> { match Header::parse(&mut data) { Ok(header) => { if header.items_len != ITEMS_LEN || header.dedup_len != DEDUP_LEN { return Err(Error::BadArrayLen); } } Err(err) => return Err(err), } let mut dedup_index: [&[u8]; DEDUP_LEN] = [&[]; DEDUP_LEN]; let mut i = 0; while i < dedup_index.len() { let m = try_read_vlq!(data); let split = data.split_at(m); dedup_index[i] = split.0; data = split.1; i += 1; } let mut res: [&[u8]; ITEMS_LEN] = [&[]; ITEMS_LEN]; let mut i = 0; while i < res.len() { let val = try_read_vlq!(data); // the least significant bit is used as a flag let is_ref = (val & 1) != 0; let val = val >> 1; res[i] = if is_ref { if val >= dedup_index.len() { return Err(Error::InvalidIndex); } dedup_index[val] } else { if val > data.len() { return Err(Error::UnexpectedEnd); } let split = data.split_at(val); data = split.1; split.0 }; i += 1; } if data.is_empty() { Ok(res) } else { Err(Error::BadArrayLen) } } /// Parse blobby data into a vector of slices. #[cfg(feature = "alloc")] pub fn parse_into_vec(mut data: &[u8]) -> Result, Error> { use alloc::{vec, vec::Vec}; let Header { items_len, dedup_len, } = Header::parse(&mut data)?; let mut dedup_index: Vec<&[u8]> = vec![&[]; dedup_len]; let mut i = 0; while i < dedup_index.len() { let m = try_read_vlq!(data); let split = data.split_at(m); dedup_index[i] = split.0; data = split.1; i += 1; } let mut res: Vec<&[u8]> = vec![&[]; items_len]; let mut i = 0; while i < res.len() { let val = try_read_vlq!(data); // the least significant bit is used as a flag let is_ref = (val & 1) != 0; let val = val >> 1; res[i] = if is_ref { if val >= dedup_index.len() { return Err(Error::InvalidIndex); } dedup_index[val] } else { if val > data.len() { return Err(Error::UnexpectedEnd); } let split = data.split_at(val); data = split.1; split.0 }; i += 1; } assert!(data.is_empty()); Ok(res) } #[macro_export] macro_rules! parse_into_slice { ($data:expr) => {{ const HEADER: $crate::Header = { let mut data: &[u8] = $data; match $crate::Header::parse(&mut data) { Ok(v) => v, Err(_) => panic!("Failed to parse items len"), } }; const ITEMS: [&[u8]; { HEADER.items_len }] = { match $crate::parse_into_array::<{ HEADER.items_len }, { HEADER.dedup_len }>($data) { Ok(v) => v, Err(_) => panic!("Failed to parse items"), } }; ITEMS.as_slice() }}; } #[macro_export] macro_rules! parse_into_structs { ( $data:expr; #[define_struct] $static_vis:vis static $items_name:ident: &[ $ty_vis:vis $item:ident { $($field:ident),* $(,)? } ]; ) => { #[derive(Debug, Clone, Copy, Eq, PartialEq)] $ty_vis struct $item { pub $($field : &'static [u8]),* } $crate::parse_into_structs!( $data; $static_vis static $items_name: &[ $item { $($field),* } ]; ); }; ( $data:expr; $static_vis:vis static $items_name:ident: &[ $item:ident { $($field:ident),* $(,)? } ]; ) => { $static_vis static $items_name: &[$item] = { const RAW_ITEMS: &[&[u8]] = $crate::parse_into_slice!($data); const fn get_struct(items: &mut &[&'static [u8]]) -> $item { $item { $($field: { match items.split_first() { Some((first, rest)) => { *items = rest; first } None => unreachable!(), } }),* } } const ITEM_FIELDS: usize = 0 $( + { let $field: (); let _ = $field; 1 })*; const ITEMS_LEN: usize = if RAW_ITEMS.len() % ITEM_FIELDS == 0 { RAW_ITEMS.len() / ITEM_FIELDS } else { panic!("Number of raw items is not multiple of number of fields in the struct"); }; const ITEMS: [$item; ITEMS_LEN] = { let mut res = [$item { $($field : &[]),* }; ITEMS_LEN]; let mut raw_items = RAW_ITEMS; let mut i = 0; while i < res.len() { res[i] = get_struct(&mut raw_items); i += 1; } res }; ITEMS.as_slice() }; }; } blobby-0.4.0/src/encode.rs000064400000000000000000000126051046102023000134740ustar 00000000000000use super::{NEXT_MASK, VAL_MASK}; /// 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: /// - number of blobs in the file = N /// - number of deduplicated index entries = M /// - M x index entries encoded as: /// - size L of index entry (VLQ) /// - index blob contents (L bytes) /// - N x blobs 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(blobs: &[T]) -> (alloc::vec::Vec, usize) where T: AsRef<[u8]>, { use alloc::{collections::BTreeMap, vec::Vec}; let mut dedup_map = BTreeMap::new(); blobs .iter() .map(|v| v.as_ref()) .filter(|blob| !blob.is_empty()) .for_each(|blob| { let v = dedup_map.entry(blob.as_ref()).or_insert(0); *v += 1; }); let mut dedup_list: Vec<&[u8]> = dedup_map .iter() .filter(|&(_, &v)| v > 1) .map(|(&k, _)| k) .collect(); dedup_list.sort_by_key(|e| { let k = match e { [0] => 2, [1] => 1, _ => 0, }; (k, dedup_map.get(e).unwrap()) }); dedup_list.reverse(); let idx_len = dedup_list.len(); let rev_idx: BTreeMap<&[u8], usize> = dedup_list .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(blobs.len(), &mut buf)); out_buf.extend_from_slice(encode_vlq(dedup_list.len(), &mut buf)); for e in dedup_list { out_buf.extend_from_slice(encode_vlq(e.len(), &mut buf)); out_buf.extend_from_slice(e); } for blob in blobs.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) } #[cfg(test)] mod tests { use crate::{Error, NEXT_MASK, VAL_MASK, decode::read_vlq}; 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 mut res = encode_vlq(val, &mut buf); let val_res = read_vlq(&mut res).unwrap(); assert_eq!(val, val_res); assert!(res.is_empty()); } } #[test] #[rustfmt::skip] fn test_vlq() { let mut example_buf: &[u8] = &[ 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]; let mut rem_len = example_buf.len(); for (target_val, target_size) in targets { assert_eq!(encode_vlq(target_val, &mut buf), &example_buf[..target_size]); let val = read_vlq(&mut example_buf).unwrap(); assert_eq!(val, target_val); rem_len -= target_size; assert_eq!(example_buf.len(), rem_len); } // Only VLQ values of up to 4 bytes are supported assert_eq!(read_vlq(&mut example_buf), Err(Error::InvalidVlq)); } } blobby-0.4.0/src/lib.rs000064400000000000000000000020501046102023000127760ustar 00000000000000#![no_std] #![doc = include_str!("../README.md")] #![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" )] #![cfg_attr(docsrs, feature(doc_cfg))] #![deny(unsafe_code)] #[cfg(feature = "alloc")] extern crate alloc; pub(crate) mod decode; #[cfg(feature = "alloc")] pub use decode::parse_into_vec; pub use decode::{Header, parse_into_array}; #[cfg(feature = "alloc")] mod encode; #[cfg(feature = "alloc")] pub use encode::encode_blobs; /// Error type used by `blobby` functions #[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, /// Bad array length was provided to [`parse_as_array`] BadArrayLen, } const NEXT_MASK: u8 = 0b1000_0000; const VAL_MASK: u8 = 0b0111_1111; blobby-0.4.0/tests/mod.rs000064400000000000000000000013651046102023000133720ustar 00000000000000#![cfg(feature = "alloc")] const ITEMS_LEN: usize = 10; const DEDUP_LEN: usize = 3; const TEST_BLOBS: &[&[u8]; ITEMS_LEN] = &[ b"1", b"12", b"1", b"1", b"123", &[42; 100_000], &[42; 100_000], &[13; 7_000], &[13; 7_000], &[13; 5_000], ]; #[test] fn blobby_rondtrip_test() -> Result<(), blobby::Error> { let (blobby_data, dedup_len) = blobby::encode_blobs(TEST_BLOBS); assert_eq!(dedup_len, DEDUP_LEN); assert_eq!(blobby_data.len(), 112_025); let decoded_blobs = blobby::parse_into_array::(&blobby_data)?; assert_eq!(decoded_blobs, TEST_BLOBS[..]); let decoded_blobs = blobby::parse_into_vec(&blobby_data)?; assert_eq!(decoded_blobs, TEST_BLOBS[..]); Ok(()) }