niffler-2.6.0/.cargo_vcs_info.json0000644000000001360000000000100124660ustar { "git": { "sha1": "7b62f586fd7f492b10a4afb2dca90681d679bfbd" }, "path_in_vcs": "" }niffler-2.6.0/.github/ISSUE_TEMPLATE/bug_report.md000064400000000000000000000011071046102023000174720ustar 00000000000000--- name: Bug report about: Create a report for Niffler title: '' labels: '' assignees: '' --- **Describe the bug** A clear and concise description of what the bug is. **Expected behavior** A clear and concise description of what you expected to happen. **Screenshots** If applicable, add screenshots to help explain your problem. **Desktop (please complete the following information):** - OS: [e.g. Ubuntu Linux] - OS version: [e.g. 20.04] - Rust version: [e.g. 1.54.0] - Niffler version: [e.g. 2.3.2] **Additional context** Add any other context about the problem here. niffler-2.6.0/.github/ISSUE_TEMPLATE/feature_request.md000064400000000000000000000011231046102023000205230ustar 00000000000000--- name: Feature request about: Suggest an idea for this project title: '' labels: '' assignees: '' --- **Is your feature request related to a problem? Please describe.** A clear and concise description of what the problem is. Ex. I'm always frustrated when [...] **Describe the solution you'd like** A clear and concise description of what you want to happen. **Describe alternatives you've considered** A clear and concise description of any alternative solutions or features you've considered. **Additional context** Add any other context or screenshots about the feature request here. niffler-2.6.0/.github/workflows/cd.yml000064400000000000000000000017131046102023000157660ustar 00000000000000name: Continuous Deployment on: push: tags: - "v*.*.*" jobs: crates: name: Publish to crates.io runs-on: ubuntu-latest steps: - name: Checkout sources uses: actions/checkout@v1 - name: Install stable toolchain uses: actions-rs/toolchain@v1 with: profile: minimal toolchain: stable override: true - name: Make sure we can publish the niffler crate uses: actions-rs/cargo@v1 with: command: publish args: --dry-run --manifest-path ./Cargo.toml # Login to crates.io on tags - name: login to crates.io uses: actions-rs/cargo@v1 with: command: login args: ${{ secrets.CRATES_IO_TOKEN }} # Publish to crates.io on tags - name: Publish to crates.io uses: actions-rs/cargo@v1 with: command: publish args: --manifest-path ./Cargo.toml niffler-2.6.0/.github/workflows/main.yml000064400000000000000000000103611046102023000163230ustar 00000000000000name: CI on: push: branches: [master] pull_request: branches: ["**"] jobs: check: name: Check runs-on: ubuntu-latest steps: - name: Checkout sources uses: actions/checkout@v1 - name: Install stable toolchain uses: actions-rs/toolchain@v1 with: profile: minimal toolchain: stable override: true - name: Run cargo check uses: actions-rs/cargo@v1 with: command: check test: runs-on: ${{ matrix.os }} strategy: fail-fast: false matrix: build: [beta, stable, windows, macos] include: - build: macos os: macos-latest rust: stable - build: windows os: windows-latest rust: stable - build: beta os: ubuntu-latest rust: beta - build: stable os: ubuntu-latest rust: stable steps: - uses: actions/checkout@v1 - uses: actions-rs/toolchain@v1 with: toolchain: ${{ matrix.rust }} override: true - name: Run tests uses: actions-rs/cargo@v1 with: command: test args: --no-fail-fast --locked test_all_feature_combinations: runs-on: ubuntu-latest steps: - uses: actions/checkout@v1 - uses: actions-rs/toolchain@v1 with: toolchain: stable override: true - uses: actions-rs/install@v0.1 with: crate: cargo-all-features version: latest use-tool-cache: true - name: Run tests for all feature combinations run: cargo test-all-features --no-fail-fast --all --locked coverage: runs-on: ubuntu-latest steps: - uses: actions/checkout@v1 - uses: actions-rs/toolchain@v1 with: toolchain: nightly override: true - name: Install cargo-tarpaulin uses: actions-rs/install@v0.1 with: crate: cargo-tarpaulin version: latest use-tool-cache: true - name: Run cargo-tarpaulin run: cargo tarpaulin --all-features --locked --timeout 600 --out Xml -- --test-threads 1 - name: Upload coverage to codecov uses: codecov/codecov-action@v4 env: CODECOV_TOKEN: ${{ secrets.CODECOV_TOKEN }} lints: name: Lints runs-on: ubuntu-latest steps: - name: Checkout sources uses: actions/checkout@v1 - name: Install stable toolchain uses: actions-rs/toolchain@v1 with: profile: minimal toolchain: stable override: true components: rustfmt, clippy - name: Run cargo fmt uses: actions-rs/cargo@v1 with: command: fmt args: --all -- --check - name: Run cargo clippy uses: actions-rs/cargo@v1 with: command: clippy args: -- -D warnings publish: name: Publish (dry-run) runs-on: ubuntu-latest steps: - name: Checkout sources uses: actions/checkout@v1 - name: Install stable toolchain uses: actions-rs/toolchain@v1 with: profile: minimal toolchain: stable override: true - name: Make sure we can publish the crate uses: actions-rs/cargo@v1 with: command: publish args: --dry-run minimum_rust_version: runs-on: ubuntu-latest steps: - uses: actions/checkout@v1 - uses: actions-rs/toolchain@v1 with: toolchain: 1.65.0 override: true - name: check if README matches MSRV defined here run: grep '1.65.0' README.md - name: Run tests uses: actions-rs/cargo@v1 with: command: test args: --all-features --no-fail-fast --locked wasm: runs-on: ubuntu-latest steps: - uses: actions/checkout@v1 - uses: actions-rs/toolchain@v1 with: toolchain: stable override: true target: wasm32-unknown-unknown - name: Build on wasm uses: actions-rs/cargo@v1 with: command: build args: --target wasm32-unknown-unknown --no-default-features --features gz niffler-2.6.0/.gitignore000064400000000000000000000000101046102023000132350ustar 00000000000000target/ niffler-2.6.0/CHANGELOG.md000064400000000000000000000057161046102023000131000ustar 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). ## [Unreleased] ### Added ### Changed ### Fixed ## 2.6.0 - 2024-06-08 ### Added ### Changed - Replace xz2 to liblzma - Bump MRSV to 1.65 - Support for multistream bzip2 files by default (#62) ### Fixed - Update bzip to 0.4.4 - Update bgzip to 0.3 - Update zstd 0.13 ## [2.5.0] - 2023-01-12 ### Added - Add support of zstd in send (#59) - Add continuous deployment workflow (#57) - Add features to allow user to select features of backend (#54) ### Changed - Bump MSRV to 1.57.0 (#59) - Bump MSRV to 1.56.1 (#54) ### Fixed - Deduplicate implementation of get_first_{bytes|five} functions (#52) ## [2.4.0] - 2021-12-25 ### Added - Zstd basic support (#44) - GitHub issues templates (#47) ### Changed - Bump MSRV to 1.51 (#48) ## [2.3.2] - 2021-05-27 ### Changed - Bump bgzip version to 0.2.0, removing dependency on failure ## [2.3.1] - 2020-12-08 ### Fixed - Maintain backward compatibility by re-exporting compression::Level ## [2.3.0] - 2020-12-08 ### Added - Support Seek and Send and prepare for future extension (#37) ## [2.2.0] - 2020-07-01 ### Changed - Make gz compression optional too, matching behavior of other compression formats (#29) ## [2.1.1] - 2020-06-30 ### Changed - Replace `GzDecoder` with `MultiGzDecoder` for gzip decompression (#28) ## [2.1.0] - 2020-06-06 ### Added - `sniff` function to detect compression format, and add benchmarks for most methods (#25) - More test on compression level conversion (#26) ## [2.0.1] - 2020-05-20 ### Added - Clone and Copy traits to pub enums [@schmidmt](https://github.com/schmidmt). ## [2.0.0] - 2020-04-27 ### Added - New functions: `get_reader`, `get_writer`, `from_path`, `to_path`, - Compression format and compression level enums - Documentation with examples - CI using GitHub Actions ### Changed - Replace failure with thiserror for error handling ### Fixed - Reorganize crate internal organization ### Removed - All previous functions and enums were renamed and reorganized. ## [1.0.0] - 2019-12-07 ### Added - Rename crate from `ocf` to `niffler` - Import codebase from sourmash repo (which copied it from the yacrd repo) [unreleased]: https://github.com/luizirber/niffler/compare/v2.4.0...HEAD [2.4.0]: https://github.com/luizirber/niffler/compare/v2.3.2..v2.4.0 [2.3.2]: https://github.com/luizirber/niffler/compare/v2.3.1..v2.3.2 [2.3.1]: https://github.com/luizirber/niffler/compare/v2.3.0..v2.3.1 [2.3.0]: https://github.com/luizirber/niffler/compare/v2.2.0..v2.3.0 [2.2.0]: https://github.com/luizirber/niffler/compare/v2.0.1..v2.2.0 [2.0.1]: https://github.com/luizirber/niffler/compare/v2.0.0..v2.0.1 [2.0.0]: https://github.com/luizirber/niffler/compare/v1.0.0..v2.0.0 [1.0.0]: https://github.com/luizirber/niffler/releases/tag/v1.0.0 niffler-2.6.0/Cargo.toml0000644000000045040000000000100104670ustar # 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 = "2021" rust-version = "1.65" name = "niffler" version = "2.6.0" authors = [ "Pierre Marijon ", "Luiz Irber ", ] description = "Simple and transparent support for compressed files" homepage = "https://github.com/luizirber/niffler" documentation = "https://docs.rs/niffler" readme = "README.md" license = "MIT/Apache-2.0" repository = "https://github.com/luizirber/niffler" [package.metadata.cargo-all-features] denylist = [ "bz2_tokio", "bz2_static", "lzma_tokio", "gz_zlib", "gz_zlib-ng-compat", "gz_cloudflare_zlib", "gz_rust_backend", "xz_tokio", "xz", ] skip_optional_dependencies = true [[bench]] name = "detect_format" harness = false [[bench]] name = "gzip" harness = false required-features = ["gz"] [[bench]] name = "bzip2" harness = false required-features = ["bz2"] [[bench]] name = "lzma" harness = false required-features = ["xz2"] [dependencies.bgzip] version = "0.3" features = ["rust_backend"] optional = true default-features = false [dependencies.bzip2] version = "0.4.4" optional = true [dependencies.cfg-if] version = "1.0" [dependencies.flate2] version = "1.0" optional = true [dependencies.liblzma] version = "0.3" optional = true [dependencies.thiserror] version = "1.0" [dependencies.zstd] version = "0.13" optional = true [dev-dependencies.criterion] version = "0.3" [dev-dependencies.tempfile] version = "3" [features] bgz = ["bgzip"] bz2 = ["bzip2"] bz2_static = ["bzip2/static"] bz2_tokio = ["bzip2/tokio"] default = [ "bz2", "lzma", "xz", "gz", "bgz", "zstd", ] gz = ["flate2"] gz_cloudflare_zlib = ["flate2/cloudflare_zlib"] gz_rust_backend = ["flate2/rust_backend"] gz_zlib = ["flate2/zlib"] gz_zlib-ng-compat = ["flate2/zlib-ng-compat"] lzma = ["liblzma"] lzma_tokio = ["liblzma/tokio"] xz = ["lzma"] xz_tokio = ["liblzma/tokio"] niffler-2.6.0/Cargo.toml.orig000064400000000000000000000037301046102023000141500ustar 00000000000000[package] name = "niffler" version = "2.6.0" authors = ["Pierre Marijon ", "Luiz Irber "] description = "Simple and transparent support for compressed files" license = "MIT/Apache-2.0" repository = "https://github.com/luizirber/niffler" homepage = "https://github.com/luizirber/niffler" readme = "README.md" documentation = "https://docs.rs/niffler" edition = "2021" rust-version = "1.65" [features] default = ["bz2", "lzma", "xz", "gz", "bgz", "zstd"] bz2 = ["bzip2"] lzma = ["liblzma"] gz = ["flate2"] bgz = ["bgzip"] xz = ["lzma"] # bzip2 feature transitivity bz2_tokio = ["bzip2/tokio"] bz2_static = ["bzip2/static"] # lzma feature transitivity lzma_tokio = ["liblzma/tokio"] # flate2 feature transitivity gz_zlib = ["flate2/zlib"] gz_zlib-ng-compat = ["flate2/zlib-ng-compat"] gz_cloudflare_zlib = ["flate2/cloudflare_zlib"] gz_rust_backend = ["flate2/rust_backend"] # xz feature transitivity xz_tokio = ["liblzma/tokio"] [dependencies] cfg-if = "1.0" thiserror = "1.0" bzip2 = { version = "0.4.4", optional = true} flate2 = { version = "1.0", optional = true } liblzma = { version = "0.3", optional = true } bgzip = { version = "0.3", optional = true, default-features = false, features = ["rust_backend"] } zstd = { version = "0.13", optional = true } [dev-dependencies] tempfile = "3" criterion = "0.3" [[bench]] name = "detect_format" harness = false [[bench]] name = "gzip" harness = false required-features = ["gz"] [[bench]] name = "bzip2" harness = false required-features = ["bz2"] [[bench]] name = "lzma" harness = false required-features = ["xz2"] [package.metadata.cargo-all-features] denylist = [ # bzip2 feature transitivity "bz2_tokio", "bz2_static", # lzma feature transitivity "lzma_tokio", # flate2 feature transitivity "gz_zlib", "gz_zlib-ng-compat", "gz_cloudflare_zlib", "gz_rust_backend", # xz feature transitivity "xz_tokio", # xz is an alias to lzma "xz", ] skip_optional_dependencies = trueniffler-2.6.0/LICENSE-APACHE000064400000000000000000000251201046102023000132020ustar 00000000000000 Apache License Version 2.0, January 2004 https://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 2018 Luiz Irber 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 https://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. niffler-2.6.0/LICENSE-MIT000064400000000000000000000020361046102023000127130ustar 00000000000000Copyright (c) 2018 Luiz Irber 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. niffler-2.6.0/Makefile000064400000000000000000000004521046102023000127170ustar 00000000000000all: check test test_benchmarks bench check: cargo fmt cargo test cargo clippy test: cargo test --all-features test_benchmarks: cargo test --benches --all-features bench: cargo bench --all-features semver: cargo +nightly semver # cargo +nightly semver -S niffler:1.0.0 -C niffler:2.0.0 niffler-2.6.0/README.md000064400000000000000000000057241046102023000125450ustar 00000000000000 # niffler Simple and transparent support for compressed files. This library provides two main features: - sniffs out compression formats from input files and returns a Read trait object ready for consumption. - Create a Writer initialized with compression ready for writing. The goal is to lower the barrier to open and use a file, especially in bioinformatics workflows. [![build-status]][github-actions] [![Crates.io](https://img.shields.io/crates/v/niffler.svg)](https://crates.io/crates/niffler) [![Documentation](https://docs.rs/niffler/badge.svg)](https://docs.rs/niffler/) [build-status]: https://github.com/luizirber/niffler/workflows/CI/badge.svg [github-actions]: https://github.com/luizirber/niffler/actions?query=workflow%3ACI ## Selecting compression formats By default all supported compression formats are enabled. If you're working on systems that don't support them you can disable default features and select the ones you want. For example, currently only `gz` is supported in Webassembly environments (because `niffler` depends on crates that have system dependencies for `bz2` and `lzma` compression), so you can use this in your `Cargo.toml` to select only the `gz` support: ``` niffler = { version = "2.2.0", default-features = false, features = ["gz"] } ``` You can still use `niffler::sniff()` to find what is the compression format, even if any feature is disabled. But if you try to use `niffler::get_reader` for a disabled feature, it will throw a runtime error. ## Minimum supported Rust version Currently the minimum supported Rust version is 1.65.0. ## Similar project Many similar projects exist in other languages: - C: [rbread](https://github.com/ocxtal/rbread) - Python: [xphyle](https://github.com/jdidion/xphyle), [xopen](https://github.com/marcelm/xopen) - Perl: [AnyUncompress](https://perldoc.perl.org/IO/Uncompress/AnyUncompress.html) - go: [Archiver](https://github.com/mholt/archiver) ## Development niffler development is open, and [pull requests](https://github.com/luizirber/niffler/pulls) are welcome! Before creating your pull request, please try to write a test and benchmark (if possible). Some commands we suggest running to help with these tasks: ``` cargo fmt cargo test cargo clippy ``` To run tests use: ``` cargo test --all-features ``` To test benchmark run: ``` cargo test --benches --all-features ``` To run all benchmark use: ``` cargo bench --all-features ``` As a shortcut, you can also run `make`, which will execute all these commands. ## License Licensed under either of these: * Apache License, Version 2.0 ([LICENSE-APACHE](LICENSE-APACHE) or https://www.apache.org/licenses/LICENSE-2.0) * MIT License ([LICENSE-MIT](LICENSE-MIT) or https://opensource.org/licenses/MIT) ### Contributing Unless you explicitly state otherwise, any contribution you intentionally submit for inclusion in the work, as defined in the Apache-2.0 license, shall be dual-licensed as above, without any additional terms or conditions. niffler-2.6.0/benches/bzip2.rs000064400000000000000000000070431046102023000142650ustar 00000000000000use std::io::Seek; use std::io::Write; mod share; use share::{read_all_stream, write_all_data, BASIC_FILE, BZIP_FILE}; use criterion::{criterion_group, criterion_main, Criterion}; fn read_in_ram(c: &mut Criterion) { let mut g = c.benchmark_group("Bzip reads"); g.bench_function("niffler", |b| { b.iter(|| read_all_stream(niffler::get_reader(Box::new(BZIP_FILE)).unwrap().0)) }); g.bench_function("bzip2", |b| { b.iter(|| read_all_stream(Box::new(bzip2::read::BzDecoder::new(BZIP_FILE)))) }); } fn write_in_ram(c: &mut Criterion) { let mut out = std::io::Cursor::new(Vec::new()); let mut g = c.benchmark_group("Bzip write"); g.bench_function("niffler", |b| { b.iter(|| { write_all_data( niffler::get_writer( Box::new(&mut out), niffler::compression::Format::Bzip, niffler::level::Level::One, ) .unwrap(), BASIC_FILE, ) }) }); g.bench_function("bzip2", |b| { b.iter(|| { write_all_data( Box::new(bzip2::write::BzEncoder::new( &mut out, bzip2::Compression::fast(), )), BASIC_FILE, ) }) }); } fn read_on_disk(c: &mut Criterion) { let mut compress_file = tempfile::NamedTempFile::new().unwrap(); // fill file { let wfile = compress_file.reopen().unwrap(); let mut writer = niffler::get_writer( Box::new(wfile), niffler::compression::Format::Bzip, niffler::level::Level::One, ) .unwrap(); for _ in 0..(8 * 1024) { writer.write(&[42]).unwrap(); } writer.flush().unwrap(); } let mut g = c.benchmark_group("Bzip reads on disk"); g.bench_function("niffler", |b| { b.iter(|| { compress_file.seek(std::io::SeekFrom::Start(0)).unwrap(); read_all_stream( niffler::get_reader(Box::new(compress_file.as_file())) .unwrap() .0, ); }) }); g.bench_function("bzip2", |b| { b.iter(|| { compress_file.seek(std::io::SeekFrom::Start(0)).unwrap(); read_all_stream(Box::new(bzip2::read::BzDecoder::new( compress_file.as_file(), ))); }) }); } fn write_on_disk(c: &mut Criterion) { let compress_file = tempfile::NamedTempFile::new().unwrap(); let mut g = c.benchmark_group("Bzip2 write on disk"); g.bench_function("niffler", |b| { b.iter(|| { let wfile = compress_file.reopen().unwrap(); let mut writer = niffler::get_writer( Box::new(wfile), niffler::compression::Format::Bzip, niffler::level::Level::One, ) .unwrap(); for _ in 0..(8 * 1024) { writer.write(&[42]).unwrap(); } }) }); g.bench_function("bzip2", |b| { b.iter(|| { let wfile = compress_file.reopen().unwrap(); let mut writer = bzip2::write::BzEncoder::new(wfile, bzip2::Compression::fast()); for _ in 0..(8 * 1024) { writer.write(&[42]).unwrap(); } }) }); } fn setup(c: &mut Criterion) { read_in_ram(c); write_in_ram(c); read_on_disk(c); write_on_disk(c); } criterion_group!(benches, setup); criterion_main!(benches); niffler-2.6.0/benches/detect_format.rs000064400000000000000000000017121046102023000160540ustar 00000000000000mod share; use share::{BASIC_FILE, BGZIP_FILE, BZIP_FILE, GZIP_FILE, LZMA_FILE}; use niffler; use criterion::{black_box, criterion_group, criterion_main, Criterion}; fn detect_format(c: &mut Criterion) { let mut g = c.benchmark_group("Format detection"); g.bench_function("unflate", |b| { b.iter(|| black_box(niffler::sniff(Box::new(BASIC_FILE)))) }); g.bench_function("gzip", |b| { b.iter(|| black_box(niffler::sniff(Box::new(GZIP_FILE)))) }); g.bench_function("bzip", |b| { b.iter(|| black_box(niffler::sniff(Box::new(BZIP_FILE)))) }); g.bench_function("lzma", |b| { b.iter(|| black_box(niffler::sniff(Box::new(LZMA_FILE)))) }); g.bench_function("bgzip", |b| { b.iter(|| { black_box(niffler::seek::sniff(Box::new(std::io::Cursor::new( BGZIP_FILE, )))) }) }); } criterion_group!(benches, detect_format); criterion_main!(benches); niffler-2.6.0/benches/gzip.rs000064400000000000000000000070661046102023000142150ustar 00000000000000use std::io::Seek; use std::io::Write; mod share; use share::{read_all_stream, write_all_data, BASIC_FILE, GZIP_FILE}; use criterion::{criterion_group, criterion_main, Criterion}; fn read_in_ram(c: &mut Criterion) { let mut g = c.benchmark_group("Gzip reads"); g.bench_function("niffler", |b| { b.iter(|| read_all_stream(niffler::get_reader(Box::new(GZIP_FILE)).unwrap().0)) }); g.bench_function("flate2", |b| { b.iter(|| read_all_stream(Box::new(flate2::read::MultiGzDecoder::new(GZIP_FILE)))) }); } fn write_in_ram(c: &mut Criterion) { let mut out = std::io::Cursor::new(Vec::new()); let mut g = c.benchmark_group("Gzip write"); g.bench_function("niffler", |b| { b.iter(|| { write_all_data( niffler::get_writer( Box::new(&mut out), niffler::compression::Format::Gzip, niffler::level::Level::One, ) .unwrap(), BASIC_FILE, ) }) }); g.bench_function("flate2", |b| { b.iter(|| { write_all_data( Box::new(flate2::write::GzEncoder::new( &mut out, flate2::Compression::fast(), )), BASIC_FILE, ) }) }); } fn read_on_disk(c: &mut Criterion) { let mut compress_file = tempfile::NamedTempFile::new().unwrap(); // fill file { let wfile = compress_file.reopen().unwrap(); let mut writer = niffler::get_writer( Box::new(wfile), niffler::compression::Format::Gzip, niffler::level::Level::One, ) .unwrap(); for _ in 0..(8 * 1024) { writer.write(&[42]).unwrap(); } writer.flush().unwrap(); } let mut g = c.benchmark_group("Gzip reads on disk"); g.bench_function("niffler", |b| { b.iter(|| { compress_file.seek(std::io::SeekFrom::Start(0)).unwrap(); read_all_stream( niffler::get_reader(Box::new(compress_file.as_file())) .unwrap() .0, ); }) }); g.bench_function("flate2", |b| { b.iter(|| { compress_file.seek(std::io::SeekFrom::Start(0)).unwrap(); read_all_stream(Box::new(flate2::read::MultiGzDecoder::new( compress_file.as_file(), ))); }) }); } fn write_on_disk(c: &mut Criterion) { let compress_file = tempfile::NamedTempFile::new().unwrap(); let mut g = c.benchmark_group("Gzip write on disk"); g.bench_function("niffler", |b| { b.iter(|| { let wfile = compress_file.reopen().unwrap(); let mut writer = niffler::get_writer( Box::new(wfile), niffler::compression::Format::Gzip, niffler::level::Level::One, ) .unwrap(); for _ in 0..(8 * 1024) { writer.write(&[42]).unwrap(); } }) }); g.bench_function("flate2", |b| { b.iter(|| { let wfile = compress_file.reopen().unwrap(); let mut writer = flate2::write::GzEncoder::new(wfile, flate2::Compression::new(1)); for _ in 0..(8 * 1024) { writer.write(&[42]).unwrap(); } }) }); } fn setup(c: &mut Criterion) { read_in_ram(c); write_in_ram(c); read_on_disk(c); write_on_disk(c); } criterion_group!(benches, setup); criterion_main!(benches); niffler-2.6.0/benches/lzma.rs000064400000000000000000000066651046102023000142130ustar 00000000000000use std::io::Seek; use std::io::Write; mod share; use share::{read_all_stream, write_all_data, BASIC_FILE, LZMA_FILE}; use criterion::{criterion_group, criterion_main, Criterion}; fn read_in_ram(c: &mut Criterion) { let mut g = c.benchmark_group("Lzma reads"); g.bench_function("niffler", |b| { b.iter(|| read_all_stream(niffler::get_reader(Box::new(LZMA_FILE)).unwrap().0)) }); g.bench_function("xz2", |b| { b.iter(|| read_all_stream(Box::new(liblzma::read::XzDecoder::new(LZMA_FILE)))) }); } fn write_in_ram(c: &mut Criterion) { let mut out = std::io::Cursor::new(Vec::new()); let mut g = c.benchmark_group("Lzma write"); g.bench_function("niffler", |b| { b.iter(|| { write_all_data( niffler::get_writer( Box::new(&mut out), niffler::compression::Format::Lzma, niffler::level::Level::One, ) .unwrap(), BASIC_FILE, ) }) }); g.bench_function("xz2", |b| { b.iter(|| { write_all_data( Box::new(liblzma::write::XzEncoder::new(&mut out, 1)), BASIC_FILE, ) }) }); } fn read_on_disk(c: &mut Criterion) { let mut compress_file = tempfile::NamedTempFile::new().unwrap(); // fill file { let wfile = compress_file.reopen().unwrap(); let mut writer = niffler::get_writer( Box::new(wfile), niffler::compression::Format::Lzma, niffler::level::Level::One, ) .unwrap(); for _ in 0..(8 * 1024) { writer.write(&[42]).unwrap(); } writer.flush().unwrap(); } let mut g = c.benchmark_group("Lzma reads on disk"); g.bench_function("niffler", |b| { b.iter(|| { compress_file.seek(std::io::SeekFrom::Start(0)).unwrap(); read_all_stream( niffler::get_reader(Box::new(compress_file.as_file())) .unwrap() .0, ); }) }); g.bench_function("xz2", |b| { b.iter(|| { compress_file.seek(std::io::SeekFrom::Start(0)).unwrap(); read_all_stream(Box::new(liblzma::read::XzDecoder::new( compress_file.as_file(), ))); }) }); } fn write_on_disk(c: &mut Criterion) { let compress_file = tempfile::NamedTempFile::new().unwrap(); let mut g = c.benchmark_group("Lzma write on disk"); g.bench_function("niffler", |b| { b.iter(|| { let wfile = compress_file.reopen().unwrap(); let mut writer = niffler::get_writer( Box::new(wfile), niffler::compression::Format::Lzma, niffler::level::Level::One, ) .unwrap(); for _ in 0..(8 * 1024) { writer.write(&[42]).unwrap(); } }) }); g.bench_function("xz2", |b| { b.iter(|| { let wfile = compress_file.reopen().unwrap(); let mut writer = liblzma::write::XzEncoder::new(wfile, 1); for _ in 0..(8 * 1024) { writer.write(&[42]).unwrap(); } }) }); } fn setup(c: &mut Criterion) { read_in_ram(c); write_in_ram(c); read_on_disk(c); write_on_disk(c); } criterion_group!(benches, setup); criterion_main!(benches); niffler-2.6.0/benches/share.rs000064400000000000000000000050021046102023000143320ustar 00000000000000use std::io::Read; use std::io::Write; #[allow(dead_code)] pub const BASIC_FILE: &'static [u8] = b"I'm not compressed"; #[allow(dead_code)] pub const GZIP_FILE: &'static [u8] = &[ 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x03, 0xf3, 0x54, 0xcf, 0x55, 0x48, 0xce, 0xcf, 0x2d, 0x28, 0x4a, 0x2d, 0x2e, 0x56, 0xc8, 0xcc, 0x53, 0x48, 0xaf, 0xca, 0x2c, 0xe0, 0x02, 0x00, 0x45, 0x7c, 0xf4, 0x10, 0x15, 0x00, 0x00, 0x00, ]; #[allow(dead_code)] pub const BZIP_FILE: &'static [u8] = &[ 0x42, 0x5A, 0x68, 0x39, 0x31, 0x41, 0x59, 0x26, 0x53, 0x59, 0xCC, 0x51, 0x35, 0x90, 0x00, 0x00, 0x03, 0x5D, 0x80, 0x00, 0x10, 0x40, 0x80, 0x10, 0x00, 0x00, 0x20, 0x1A, 0x23, 0xD8, 0x10, 0x20, 0x00, 0x22, 0x9A, 0x32, 0x68, 0xF4, 0x8F, 0x28, 0x53, 0x00, 0x04, 0xD3, 0x20, 0x19, 0xF6, 0xA6, 0xC5, 0x90, 0x48, 0xB5, 0x72, 0x92, 0xF8, 0xBB, 0x92, 0x29, 0xC2, 0x84, 0x86, 0x62, 0x89, 0xAC, 0x80, ]; #[allow(dead_code)] pub const LZMA_FILE: &'static [u8] = &[ 0xfd, 0x37, 0x7a, 0x58, 0x5a, 0x00, 0x00, 0x04, 0xe6, 0xd6, 0xb4, 0x46, 0x02, 0x00, 0x21, 0x01, 0x16, 0x00, 0x00, 0x00, 0x74, 0x2f, 0xe5, 0xa3, 0x01, 0x00, 0x14, 0x49, 0x27, 0x6d, 0x20, 0x63, 0x6f, 0x6d, 0x70, 0x72, 0x65, 0x73, 0x73, 0x20, 0x69, 0x6e, 0x20, 0x6c, 0x7a, 0x6d, 0x61, 0x0a, 0x00, 0x00, 0x00, 0x00, 0x4d, 0x4e, 0x36, 0xfd, 0xff, 0x2e, 0x12, 0xc6, 0x00, 0x01, 0x2d, 0x15, 0x2f, 0x0b, 0x71, 0x6d, 0x1f, 0xb6, 0xf3, 0x7d, 0x01, 0x00, 0x00, 0x00, 0x00, 0x04, 0x59, 0x5a, ]; #[allow(dead_code)] pub const BGZIP_FILE: &'static [u8] = &[ 0x1f, 0x8b, 0x08, 0x04, 0x00, 0x00, 0x00, 0x00, 0x00, 0xff, 0x06, 0x00, 0x42, 0x43, 0x02, 0x00, 0x50, 0x00, 0x05, 0x40, 0xc1, 0x09, 0xc0, 0x20, 0x0c, 0xfc, 0x77, 0x8a, 0x1b, 0xa0, 0x74, 0x92, 0x2e, 0x21, 0x31, 0xc8, 0x81, 0x31, 0x92, 0xc4, 0xfd, 0x05, 0xbf, 0x87, 0x1a, 0xb8, 0xf3, 0x18, 0xba, 0x4f, 0x0f, 0x24, 0x0b, 0xcd, 0xb4, 0x5e, 0x88, 0xaf, 0x54, 0x29, 0xad, 0x13, 0x68, 0x9d, 0x9b, 0x29, 0x5c, 0x03, 0x3a, 0x59, 0xdf, 0x73, 0x01, 0x56, 0x88, 0x8b, 0x0f, 0x3a, 0x00, 0x00, 0x00, 0x1f, 0x8b, 0x08, 0x04, 0x00, 0x00, 0x00, 0x00, 0x00, 0xff, 0x06, 0x00, 0x42, 0x43, 0x02, 0x00, 0x1b, 0x00, 0x03, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, ]; #[allow(dead_code)] pub fn read_all_stream<'a>(stream: Box) { for b in stream.bytes() { criterion::black_box(b).unwrap(); } } #[allow(dead_code)] pub fn write_all_data<'a>(mut stream: Box, data: &[u8]) { criterion::black_box(stream.write(data)).unwrap(); } niffler-2.6.0/src/basic/compression.rs000064400000000000000000000110351046102023000160350ustar 00000000000000#![allow(clippy::unnecessary_wraps)] /* standard use */ use std::io; /* crates use */ use cfg_if::cfg_if; /* project use */ use crate::error::Error; /* backward compatibility, can remove on 3.x */ pub use crate::level::Level; /* Format detection enum */ /// `Format` represent a compression format of a file. Currently Gzip, Bzip, Lzma or No are supported. #[derive(Debug, Eq, PartialEq, Clone, Copy)] pub enum Format { Gzip, Bzip, Lzma, Zstd, No, } impl Format { #[allow(non_upper_case_globals)] pub const Xz: Format = Format::Lzma; } pub(crate) fn bytes2type(bytes: [u8; 5]) -> Format { match bytes { [0x1f, 0x8b, ..] => Format::Gzip, [0x42, 0x5a, ..] => Format::Bzip, [0x28, 0xb5, 0x2f, 0xfd, ..] => Format::Zstd, [0xfd, 0x37, 0x7a, 0x58, 0x5a] => Format::Lzma, _ => Format::No, } } cfg_if! { if #[cfg(feature = "gz")] { pub(crate) fn new_gz_encoder<'a>(out: Box, level: Level) -> Result, Error> { Ok(Box::new(flate2::write::GzEncoder::new( out, level.into(), ))) } pub(crate) fn new_gz_decoder<'a>( inp: Box, ) -> Result<(Box, Format), Error> { Ok(( Box::new(flate2::read::MultiGzDecoder::new(inp)), Format::Gzip, )) } } else { pub(crate) fn new_gz_encoder<'a>(_: Box, _: Level) -> Result, Error> { Err(Error::FeatureDisabled) } pub(crate) fn new_gz_decoder<'a>(_: Box) -> Result<(Box, Format), Error> { Err(Error::FeatureDisabled) } } } cfg_if! { if #[cfg(feature = "bz2")] { pub(crate) fn new_bz2_encoder<'a>(out: Box, level: Level) -> Result, Error> { Ok(Box::new(bzip2::write::BzEncoder::new( out, level.into(), ))) } pub(crate) fn new_bz2_decoder<'a>( inp: Box, ) -> Result<(Box, Format), Error> { Ok(( Box::new(bzip2::read::MultiBzDecoder::new(inp)), Format::Bzip, )) } } else { pub(crate) fn new_bz2_encoder<'a>(_: Box, _: Level) -> Result, Error> { Err(Error::FeatureDisabled) } pub(crate) fn new_bz2_decoder<'a>(_: Box) -> Result<(Box, Format), Error> { Err(Error::FeatureDisabled) } } } cfg_if! { if #[cfg(feature = "lzma")] { pub(crate) fn new_lzma_encoder<'a>(out: Box, level: Level) -> Result, Error> { Ok(Box::new(liblzma::write::XzEncoder::new(out, level.into()))) } pub(crate) fn new_lzma_decoder<'a>( inp: Box, ) -> Result<(Box, Format), Error> { Ok(( Box::new(liblzma::read::XzDecoder::new(inp)), Format::Lzma, )) } } else { pub(crate) fn new_lzma_encoder<'a>(_: Box, _: Level) -> Result, Error> { Err(Error::FeatureDisabled) } pub(crate) fn new_lzma_decoder<'a>(_: Box) -> Result<(Box, Format), Error> { Err(Error::FeatureDisabled) } } } cfg_if! { if #[cfg(feature = "zstd")] { pub(crate) fn new_zstd_encoder<'a>(out: Box, level: Level) -> Result, Error> { Ok(Box::new(zstd::stream::write::Encoder::new( out, level.into(), )?.auto_finish())) } pub(crate) fn new_zstd_decoder<'a>( inp: Box, ) -> Result<(Box, Format), Error> { Ok((Box::new(zstd::stream::read::Decoder::new(inp)?), Format::Zstd, )) } } else { pub(crate) fn new_zstd_encoder<'a>(_: Box, _: Level) -> Result, Error> { Err(Error::FeatureDisabled) } pub(crate) fn new_zstd_decoder<'a>(_: Box) -> Result<(Box, Format), Error> { Err(Error::FeatureDisabled) } } } niffler-2.6.0/src/basic/mod.rs000064400000000000000000000430001046102023000142500ustar 00000000000000pub mod compression; /* standard use */ use std::io; use std::io::Read; use std::path::Path; /* project use */ use crate::error::Error; use crate::level::Level; /// Finds out what is the compression format for a stream based on magic numbers /// (the first few bytes of the stream). /// /// Return the stream and the compression format detected. /// /// # Example /// ``` /// # fn main() -> Result<(), niffler::Error> { /// /// let data = vec![ /// 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x03, 0xf3, 0x54, 0xcf, 0x55, /// 0x48, 0xce, 0xcf, 0x2d, 0x28, 0x4a, 0x2d, 0x2e, 0x56, 0xc8, 0xcc, 0x53, 0x48, 0xaf, /// 0xca, 0x2c, 0xe0, 0x02, 0x00, 0x45, 0x7c, 0xf4, 0x10, 0x15, 0x00, 0x00, 0x00 /// ]; /// /// let (mut reader, compression) = niffler::sniff(Box::new(&data[..]))?; /// /// let mut contents = Vec::new(); /// reader.read_to_end(&mut contents).expect("Error durring file reading"); /// /// assert_eq!(compression, niffler::compression::Format::Gzip); /// assert_eq!(contents, data); /// # Ok(()) /// # } /// ``` pub fn sniff<'a>( in_stream: Box, ) -> Result<(Box, compression::Format), Error> { let (first_bytes, in_stream) = crate::utils::get_first_five(in_stream)?; let cursor = io::Cursor::new(first_bytes); match compression::bytes2type(first_bytes) { e @ compression::Format::Gzip | e @ compression::Format::Bzip | e @ compression::Format::Lzma | e @ compression::Format::Zstd => Ok((Box::new(cursor.chain(in_stream)), e)), _ => Ok((Box::new(cursor.chain(in_stream)), compression::Format::No)), } } /// Create a readable stream that can be read transparently even if the original stream is compress. /// Also returns the compression type of the original stream. /// /// # Example /// ``` /// use niffler::{Error, get_reader}; /// # fn main() -> Result<(), Error> { /// /// let probably_compress_stream = std::io::Cursor::new(vec![ /// 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x03, 0xf3, 0x54, 0xcf, 0x55, /// 0x48, 0xce, 0xcf, 0x2d, 0x28, 0x4a, 0x2d, 0x2e, 0x56, 0xc8, 0xcc, 0x53, 0x48, 0xaf, /// 0xca, 0x2c, 0xe0, 0x02, 0x00, 0x45, 0x7c, 0xf4, 0x10, 0x15, 0x00, 0x00, 0x00 /// ]); /// /// # #[cfg(feature = "gz")] { /// let (mut reader, compression) = niffler::get_reader(Box::new(probably_compress_stream))?; /// /// let mut contents = String::new(); /// reader.read_to_string(&mut contents).expect("Error durring file reading"); /// /// assert_eq!(compression, niffler::compression::Format::Gzip); /// assert_eq!(contents, "I'm compress in gzip\n"); /// # } /// # Ok(()) /// # } /// ``` pub fn get_reader<'a>( in_stream: Box, ) -> Result<(Box, compression::Format), Error> { // check compression let (in_stream, compression) = sniff(in_stream)?; // return readable and compression status match compression { compression::Format::Gzip => compression::new_gz_decoder(in_stream), compression::Format::Bzip => compression::new_bz2_decoder(in_stream), compression::Format::Lzma => compression::new_lzma_decoder(in_stream), compression::Format::Zstd => compression::new_zstd_decoder(in_stream), compression::Format::No => Ok((in_stream, compression::Format::No)), } } /// Create a new writable stream with the given compression format and level. /// /// # Example /// ``` /// use std::io::Read; /// use niffler::{Error, get_writer, compression}; /// # fn main() -> Result<(), Error> { /// /// # #[cfg(feature = "gz")] { /// let mut buffer = vec![]; /// { /// let mut writer = niffler::get_writer(Box::new(&mut buffer), compression::Format::Gzip, niffler::Level::One)?; /// writer.write_all("I'm compress in gzip\n".as_bytes())? /// } /// /// let mut contents = Vec::new(); /// buffer.as_slice().read_to_end(&mut contents)?; /// /// assert_eq!(contents, vec![ /// 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x04, 0xff, 0xf3, 0x54, 0xcf, 0x55, /// 0x48, 0xce, 0xcf, 0x2d, 0x28, 0x4a, 0x2d, 0x2e, 0x56, 0xc8, 0xcc, 0x53, 0x48, 0xaf, /// 0xca, 0x2c, 0xe0, 0x02, 0x00, 0x45, 0x7c, 0xf4, 0x10, 0x15, 0x00, 0x00, 0x00 /// ]); /// # } /// # Ok(()) /// # } /// ``` pub fn get_writer<'a>( out_stream: Box, format: compression::Format, level: Level, ) -> Result, Error> { match format { compression::Format::Gzip => compression::new_gz_encoder(out_stream, level), compression::Format::Bzip => compression::new_bz2_encoder(out_stream, level), compression::Format::Lzma => compression::new_lzma_encoder(out_stream, level), compression::Format::Zstd => compression::new_zstd_encoder(out_stream, level), compression::Format::No => Ok(Box::new(out_stream)), } } /// Open a possibly compressed file and decompress it transparently. /// ``` /// use niffler::{Error, compression}; /// # fn main() -> Result<(), Error> { /// /// # #[cfg(feature = "gz")] { /// # let file = tempfile::NamedTempFile::new()?; /// /// # { /// # let mut writer = niffler::to_path(file.path(), compression::Format::Gzip, niffler::Level::Nine)?; /// # writer.write_all(b"hello")?; /// # } /// /// let (mut reader, format) = niffler::from_path(file.path())?; /// /// let mut contents = vec![]; /// reader.read_to_end(&mut contents); /// # assert_eq!(&contents, b"hello"); /// /// # } /// # Ok(()) /// # } /// ``` pub fn from_path<'a, P: AsRef>( path: P, ) -> Result<(Box, compression::Format), Error> { let readable = io::BufReader::new(std::fs::File::open(path)?); get_reader(Box::new(readable)) } /// Create a file with specific compression format. /// ``` /// use niffler::{Error, compression}; /// # fn main() -> Result<(), Error> { /// /// # #[cfg(feature = "gz")] { /// # let file = tempfile::NamedTempFile::new()?; /// /// # { /// let mut writer = niffler::to_path(file.path(), compression::Format::Gzip, niffler::Level::Nine)?; /// writer.write_all(b"hello")?; /// # } /// /// # let (mut reader, format) = niffler::from_path(&file.path())?; /// # let mut contents = vec![]; /// # reader.read_to_end(&mut contents)?; /// # assert_eq!(&contents, b"hello"); /// # } /// # Ok(()) /// # } /// ``` pub fn to_path<'a, P: AsRef>( path: P, format: compression::Format, level: Level, ) -> Result, Error> { let writable = io::BufWriter::new(std::fs::File::create(path)?); get_writer(Box::new(writable), format, level) } #[cfg(test)] mod test { use super::*; use tempfile::NamedTempFile; pub(crate) const SHORT_FILE: &'static [u8] = &[0o037, 0o213, 0o0, 0o0]; pub(crate) const GZIP_FILE: &'static [u8] = &[0o037, 0o213, 0o0, 0o0, 0o0]; pub(crate) const BZIP_FILE: &'static [u8] = &[0o102, 0o132, 0o0, 0o0, 0o0]; pub(crate) const LZMA_FILE: &'static [u8] = &[0o375, 0o067, 0o172, 0o130, 0o132]; pub(crate) const ZSTD_FILE: &'static [u8] = &[0x28, 0xb5, 0x2f, 0xfd, 0]; pub(crate) const LOREM_IPSUM: &'static [u8] = b"Lorem ipsum dolor sit amet, consectetur adipiscing elit. Ut ultricies scelerisque diam, a scelerisque enim sagittis at."; mod compress_uncompress { use super::*; #[test] fn no_compression() { let ofile = NamedTempFile::new().expect("Can't create tmpfile"); { let wfile = ofile.reopen().expect("Can't create tmpfile"); let mut writer = get_writer(Box::new(wfile), compression::Format::No, Level::One).unwrap(); writer .write_all(LOREM_IPSUM) .expect("Error during write of data"); } let rfile = ofile.reopen().expect("Can't create tmpfile"); let (mut reader, compression) = get_reader(Box::new(rfile)).expect("Error reading from tmpfile"); assert_eq!(compression, compression::Format::No); let mut buffer = Vec::new(); reader .read_to_end(&mut buffer) .expect("Error during reading"); assert_eq!(LOREM_IPSUM, buffer.as_slice()); } #[cfg(feature = "gz")] #[test] fn gzip() { let ofile = NamedTempFile::new().expect("Can't create tmpfile"); { let wfile = ofile.reopen().expect("Can't create tmpfile"); let mut writer = get_writer(Box::new(wfile), compression::Format::Gzip, Level::Six).unwrap(); writer .write_all(LOREM_IPSUM) .expect("Error during write of data"); } let rfile = ofile.reopen().expect("Can't create tmpfile"); let (mut reader, compression) = get_reader(Box::new(rfile)).expect("Error reading from tmpfile"); assert_eq!(compression, compression::Format::Gzip); let mut buffer = Vec::new(); reader .read_to_end(&mut buffer) .expect("Error during reading"); assert_eq!(LOREM_IPSUM, buffer.as_slice()); } #[test] #[cfg(not(feature = "bz2"))] fn no_bzip2_feature() { assert!( get_writer(Box::new(vec![]), compression::Format::Bzip, Level::Six).is_err(), "bz2 disabled, this assertion should fail" ); assert!( get_reader(Box::new(&BZIP_FILE[..])).is_err(), "bz2 disabled, this assertion should fail" ); } #[cfg(feature = "bz2")] #[test] fn bzip() { let ofile = NamedTempFile::new().expect("Can't create tmpfile"); { let wfile = ofile.reopen().expect("Can't create tmpfile"); let mut writer = get_writer(Box::new(wfile), compression::Format::Bzip, Level::Six).unwrap(); writer .write_all(LOREM_IPSUM) .expect("Error during write of data"); } let rfile = ofile.reopen().expect("Can't create tmpfile"); let (mut reader, compression) = get_reader(Box::new(rfile)).expect("Error reading from tmpfile"); assert_eq!(compression, compression::Format::Bzip); let mut buffer = Vec::new(); reader .read_to_end(&mut buffer) .expect("Error during reading"); assert_eq!(LOREM_IPSUM, buffer.as_slice()); } #[cfg(feature = "bz2")] #[test] fn bzip_multidecoder() { let mut buf: Vec = vec![]; { let mut writer = get_writer(Box::new(&mut buf), compression::Format::Bzip, Level::Six).unwrap(); writer .write_all(LOREM_IPSUM) .expect("Error during write of data"); } let ofile = NamedTempFile::new().expect("Can't create tmpfile"); { use std::io::Write; let mut wfile = ofile.reopen().expect("Can't create tmpfile"); wfile .write_all(buf.as_slice()) .expect("Error during write of data"); wfile .write_all(buf.as_slice()) .expect("Error during write of data"); } let rfile = ofile.reopen().expect("Can't create tmpfile"); let (mut reader, compression) = get_reader(Box::new(rfile)).expect("Error reading from tmpfile"); assert_eq!(compression, compression::Format::Bzip); let mut buffer = Vec::new(); reader .read_to_end(&mut buffer) .expect("Error during reading"); let mut result: Vec = LOREM_IPSUM.into(); result.extend(LOREM_IPSUM); assert_eq!(result, buffer.as_slice()); } #[test] #[cfg(not(feature = "lzma"))] fn no_lzma_feature() { assert!( get_writer(Box::new(vec![]), compression::Format::Lzma, Level::Six).is_err(), "lzma disabled, this assertion should fail" ); assert!( get_reader(Box::new(&LZMA_FILE[..])).is_err(), "lzma disabled, this assertion should fail" ); } #[cfg(feature = "lzma")] #[test] fn lzma() { let ofile = NamedTempFile::new().expect("Can't create tmpfile"); { let wfile = ofile.reopen().expect("Can't create tmpfile"); let mut writer = get_writer(Box::new(wfile), compression::Format::Lzma, Level::Six).unwrap(); writer .write_all(LOREM_IPSUM) .expect("Error during write of data"); } let rfile = ofile.reopen().expect("Can't create tmpfile"); let (mut reader, compression) = get_reader(Box::new(rfile)).expect("Error reading from tmpfile"); assert_eq!(compression, compression::Format::Lzma); let mut buffer = Vec::new(); reader .read_to_end(&mut buffer) .expect("Error during reading"); assert_eq!(LOREM_IPSUM, buffer.as_slice()); } #[test] #[cfg(all(not(feature = "xz"), not(feature = "lzma")))] fn no_xz_feature() { assert!( get_writer(Box::new(vec![]), compression::Format::Xz, Level::Six).is_err(), "xz disabled, this assertion should fail" ); assert!( get_reader(Box::new(&LZMA_FILE[..])).is_err(), "xz disabled, this assertion should fail" ); } #[cfg(feature = "xz")] #[test] fn xz() { let ofile = NamedTempFile::new().expect("Can't create tmpfile"); { let wfile = ofile.reopen().expect("Can't create tmpfile"); let mut writer = get_writer(Box::new(wfile), compression::Format::Xz, Level::Six).unwrap(); writer .write_all(LOREM_IPSUM) .expect("Error during write of data"); } let rfile = ofile.reopen().expect("Can't create tmpfile"); let (mut reader, compression) = get_reader(Box::new(rfile)).expect("Error reading from tmpfile"); assert_eq!(compression, compression::Format::Xz); let mut buffer = Vec::new(); reader .read_to_end(&mut buffer) .expect("Error during reading"); assert_eq!(LOREM_IPSUM, buffer.as_slice()); } #[test] #[cfg(not(feature = "zstd"))] fn no_zstd_feature() { assert!( get_writer(Box::new(vec![]), compression::Format::Zstd, Level::Six).is_err(), "zstd disabled, this assertion should fail" ); assert!( get_reader(Box::new(&ZSTD_FILE[..])).is_err(), "zstd disabled, this assertion should fail" ); } #[cfg(feature = "zstd")] #[test] fn zstd() { let ofile = NamedTempFile::new().expect("Can't create tmpfile"); { let wfile = ofile.reopen().expect("Can't create tmpfile"); let mut writer = get_writer(Box::new(wfile), compression::Format::Zstd, Level::Six).unwrap(); writer .write_all(LOREM_IPSUM) .expect("Error during write of data"); } let rfile = ofile.reopen().expect("Can't create tmpfile"); let (mut reader, compression) = get_reader(Box::new(rfile)).expect("Error reading from tmpfile"); assert_eq!(compression, compression::Format::Zstd); let mut buffer = Vec::new(); reader .read_to_end(&mut buffer) .expect("Error during reading"); assert_eq!(LOREM_IPSUM, buffer.as_slice()); } } mod compression_format_detection { use super::*; #[test] fn gzip() { let (_, compression) = sniff(Box::new(GZIP_FILE)).expect("Error in read file"); assert_eq!(compression, compression::Format::Gzip); } #[test] fn bzip() { let (_, compression) = sniff(Box::new(BZIP_FILE)).expect("Error in read file"); assert_eq!(compression, compression::Format::Bzip); } #[test] fn lzma() { let (_, compression) = sniff(Box::new(LZMA_FILE)).expect("Error in read file"); assert_eq!(compression, compression::Format::Lzma); } #[test] fn xz() { let (_, compression) = sniff(Box::new(LZMA_FILE)).expect("Error in read file"); assert_eq!(compression, compression::Format::Xz); } #[test] fn zstd() { let (_, compression) = sniff(Box::new(ZSTD_FILE)).expect("Error in read file"); assert_eq!(compression, compression::Format::Zstd); } #[test] fn too_short() { let result = sniff(Box::new(SHORT_FILE)); assert!(result.is_err()); } #[test] fn no_compression() { let (_, compression) = sniff(Box::new(LOREM_IPSUM)).expect("Error in read file"); assert_eq!(compression, compression::Format::No); } } } niffler-2.6.0/src/error.rs000064400000000000000000000010511046102023000135410ustar 00000000000000use thiserror::Error; /// Errors that can be generated by niffler #[allow(clippy::upper_case_acronyms)] #[derive(Debug, Error)] pub enum Error { /// This feature is disabled, you can enable it in cargo dependencies sections. #[error("Feature disabled, enabled it during compilation")] FeatureDisabled, /// This file is shorter than five bytes, it's probably not a compression file or corrupted. #[error("File is too short, less than five bytes")] FileTooShort, #[error("I/O error")] IOError(#[from] std::io::Error), } niffler-2.6.0/src/level.rs000064400000000000000000000266451046102023000135370ustar 00000000000000/// `Level` represent the compression level this value is include between 1 to 9. /// 1 optimize the compression time, /// 9 optimize the size of the output. /// /// For bzip2: /// - `One` is convert in `bzip2::Compression::Fastest`, /// - `Nine` in `bzip2::Compression::Best` /// and other value is convert in `bzip2::Compression::Default. #[derive(Debug, PartialEq, Eq, Clone, Copy)] pub enum Level { Zero, One, Two, Three, Four, Five, Six, Seven, Eight, Nine, Ten, Eleven, Twelve, Thirteen, Fourteen, Fifteen, Sixteen, Seventeen, Eighteen, Nineteen, Twenty, TwentyOne, } impl From for u32 { fn from(level: Level) -> Self { match level { Level::Zero => 0, Level::One => 1, Level::Two => 2, Level::Three => 3, Level::Four => 4, Level::Five => 5, Level::Six => 6, Level::Seven => 7, Level::Eight => 8, Level::Nine => 9, Level::Ten => 10, Level::Eleven => 11, Level::Twelve => 12, Level::Thirteen => 13, Level::Fourteen => 14, Level::Fifteen => 15, Level::Sixteen => 16, Level::Seventeen => 17, Level::Eighteen => 18, Level::Nineteen => 19, Level::Twenty => 20, Level::TwentyOne => 21, } } } impl From for i32 { fn from(level: Level) -> Self { match level { Level::Zero => 0, Level::One => 1, Level::Two => 2, Level::Three => 3, Level::Four => 4, Level::Five => 5, Level::Six => 6, Level::Seven => 7, Level::Eight => 8, Level::Nine => 9, Level::Ten => 10, Level::Eleven => 11, Level::Twelve => 12, Level::Thirteen => 13, Level::Fourteen => 14, Level::Fifteen => 15, Level::Sixteen => 16, Level::Seventeen => 17, Level::Eighteen => 18, Level::Nineteen => 19, Level::Twenty => 20, Level::TwentyOne => 21, } } } #[cfg(feature = "gz")] impl From for flate2::Compression { fn from(level: Level) -> Self { match level { Level::Zero => flate2::Compression::new(0), Level::One => flate2::Compression::new(1), Level::Two => flate2::Compression::new(2), Level::Three => flate2::Compression::new(3), Level::Four => flate2::Compression::new(4), Level::Five => flate2::Compression::new(5), Level::Six => flate2::Compression::new(6), Level::Seven => flate2::Compression::new(7), Level::Eight => flate2::Compression::new(8), Level::Nine => flate2::Compression::new(9), _ => flate2::Compression::new(9), } } } #[cfg(feature = "bz2")] impl From for bzip2::Compression { fn from(level: Level) -> Self { match level { Level::Zero => bzip2::Compression::new(0), Level::One => bzip2::Compression::new(1), Level::Two => bzip2::Compression::new(2), Level::Three => bzip2::Compression::new(3), Level::Four => bzip2::Compression::new(4), Level::Five => bzip2::Compression::new(5), Level::Six => bzip2::Compression::new(6), Level::Seven => bzip2::Compression::new(7), Level::Eight => bzip2::Compression::new(8), Level::Nine => bzip2::Compression::new(9), _ => bzip2::Compression::new(9), } } } #[cfg(test)] mod test { use super::*; #[test] fn level2u32() { let mut tmp: u32 = Level::One.into(); assert_eq!(tmp, 1); tmp = Level::Two.into(); assert_eq!(tmp, 2); tmp = Level::Three.into(); assert_eq!(tmp, 3); tmp = Level::Four.into(); assert_eq!(tmp, 4); tmp = Level::Five.into(); assert_eq!(tmp, 5); tmp = Level::Six.into(); assert_eq!(tmp, 6); tmp = Level::Seven.into(); assert_eq!(tmp, 7); tmp = Level::Eight.into(); assert_eq!(tmp, 8); tmp = Level::Nine.into(); assert_eq!(tmp, 9); tmp = Level::Ten.into(); assert_eq!(tmp, 10); tmp = Level::Eleven.into(); assert_eq!(tmp, 11); tmp = Level::Twelve.into(); assert_eq!(tmp, 12); tmp = Level::Thirteen.into(); assert_eq!(tmp, 13); tmp = Level::Fourteen.into(); assert_eq!(tmp, 14); tmp = Level::Fifteen.into(); assert_eq!(tmp, 15); tmp = Level::Sixteen.into(); assert_eq!(tmp, 16); tmp = Level::Seventeen.into(); assert_eq!(tmp, 17); tmp = Level::Eighteen.into(); assert_eq!(tmp, 18); tmp = Level::Nineteen.into(); assert_eq!(tmp, 19); tmp = Level::Twenty.into(); assert_eq!(tmp, 20); tmp = Level::TwentyOne.into(); assert_eq!(tmp, 21); } #[test] fn level2i32() { let mut tmp: i32 = Level::One.into(); assert_eq!(tmp, 1); tmp = Level::Two.into(); assert_eq!(tmp, 2); tmp = Level::Three.into(); assert_eq!(tmp, 3); tmp = Level::Four.into(); assert_eq!(tmp, 4); tmp = Level::Five.into(); assert_eq!(tmp, 5); tmp = Level::Six.into(); assert_eq!(tmp, 6); tmp = Level::Seven.into(); assert_eq!(tmp, 7); tmp = Level::Eight.into(); assert_eq!(tmp, 8); tmp = Level::Nine.into(); assert_eq!(tmp, 9); tmp = Level::Ten.into(); assert_eq!(tmp, 10); tmp = Level::Eleven.into(); assert_eq!(tmp, 11); tmp = Level::Twelve.into(); assert_eq!(tmp, 12); tmp = Level::Thirteen.into(); assert_eq!(tmp, 13); tmp = Level::Fourteen.into(); assert_eq!(tmp, 14); tmp = Level::Fifteen.into(); assert_eq!(tmp, 15); tmp = Level::Sixteen.into(); assert_eq!(tmp, 16); tmp = Level::Seventeen.into(); assert_eq!(tmp, 17); tmp = Level::Eighteen.into(); assert_eq!(tmp, 18); tmp = Level::Nineteen.into(); assert_eq!(tmp, 19); tmp = Level::Twenty.into(); assert_eq!(tmp, 20); tmp = Level::TwentyOne.into(); assert_eq!(tmp, 21); } #[cfg(feature = "gz")] #[test] fn level2flate2() { let mut tmp: flate2::Compression = Level::Zero.into(); assert_eq!(tmp, flate2::Compression::new(0)); tmp = Level::One.into(); assert_eq!(tmp, flate2::Compression::new(1)); tmp = Level::Two.into(); assert_eq!(tmp, flate2::Compression::new(2)); tmp = Level::Three.into(); assert_eq!(tmp, flate2::Compression::new(3)); tmp = Level::Four.into(); assert_eq!(tmp, flate2::Compression::new(4)); tmp = Level::Five.into(); assert_eq!(tmp, flate2::Compression::new(5)); tmp = Level::Six.into(); assert_eq!(tmp, flate2::Compression::new(6)); tmp = Level::Seven.into(); assert_eq!(tmp, flate2::Compression::new(7)); tmp = Level::Eight.into(); assert_eq!(tmp, flate2::Compression::new(8)); tmp = Level::Nine.into(); assert_eq!(tmp, flate2::Compression::new(9)); tmp = Level::Ten.into(); assert_eq!(tmp, flate2::Compression::new(9)); tmp = Level::Eleven.into(); assert_eq!(tmp, flate2::Compression::new(9)); tmp = Level::Twelve.into(); assert_eq!(tmp, flate2::Compression::new(9)); tmp = Level::Thirteen.into(); assert_eq!(tmp, flate2::Compression::new(9)); tmp = Level::Fourteen.into(); assert_eq!(tmp, flate2::Compression::new(9)); tmp = Level::Fifteen.into(); assert_eq!(tmp, flate2::Compression::new(9)); tmp = Level::Sixteen.into(); assert_eq!(tmp, flate2::Compression::new(9)); tmp = Level::Seventeen.into(); assert_eq!(tmp, flate2::Compression::new(9)); tmp = Level::Eighteen.into(); assert_eq!(tmp, flate2::Compression::new(9)); tmp = Level::Nineteen.into(); assert_eq!(tmp, flate2::Compression::new(9)); tmp = Level::Twenty.into(); assert_eq!(tmp, flate2::Compression::new(9)); tmp = Level::TwentyOne.into(); assert_eq!(tmp, flate2::Compression::new(9)); } #[test] #[cfg(feature = "bz2")] fn level2bzip2() { let tmp: bzip2::Compression = Level::Zero.into(); assert_eq!(tmp.level(), bzip2::Compression::new(0).level()); let tmp: bzip2::Compression = Level::One.into(); assert_eq!(tmp.level(), bzip2::Compression::new(1).level()); let tmp: bzip2::Compression = Level::Two.into(); assert_eq!(tmp.level(), bzip2::Compression::new(2).level()); let tmp: bzip2::Compression = Level::Three.into(); assert_eq!(tmp.level(), bzip2::Compression::new(3).level()); let tmp: bzip2::Compression = Level::Four.into(); assert_eq!(tmp.level(), bzip2::Compression::new(4).level()); let tmp: bzip2::Compression = Level::Five.into(); assert_eq!(tmp.level(), bzip2::Compression::new(5).level()); let tmp: bzip2::Compression = Level::Six.into(); assert_eq!(tmp.level(), bzip2::Compression::new(6).level()); let tmp: bzip2::Compression = Level::Seven.into(); assert_eq!(tmp.level(), bzip2::Compression::new(7).level()); let tmp: bzip2::Compression = Level::Eight.into(); assert_eq!(tmp.level(), bzip2::Compression::new(8).level()); let tmp: bzip2::Compression = Level::Nine.into(); assert_eq!(tmp.level(), bzip2::Compression::new(9).level()); let tmp: bzip2::Compression = Level::Ten.into(); assert_eq!(tmp.level(), bzip2::Compression::new(9).level()); let tmp: bzip2::Compression = Level::Eleven.into(); assert_eq!(tmp.level(), bzip2::Compression::new(9).level()); let tmp: bzip2::Compression = Level::Twelve.into(); assert_eq!(tmp.level(), bzip2::Compression::new(9).level()); let tmp: bzip2::Compression = Level::Thirteen.into(); assert_eq!(tmp.level(), bzip2::Compression::new(9).level()); let tmp: bzip2::Compression = Level::Fourteen.into(); assert_eq!(tmp.level(), bzip2::Compression::new(9).level()); let tmp: bzip2::Compression = Level::Fifteen.into(); assert_eq!(tmp.level(), bzip2::Compression::new(9).level()); let tmp: bzip2::Compression = Level::Sixteen.into(); assert_eq!(tmp.level(), bzip2::Compression::new(9).level()); let tmp: bzip2::Compression = Level::Seventeen.into(); assert_eq!(tmp.level(), bzip2::Compression::new(9).level()); let tmp: bzip2::Compression = Level::Eighteen.into(); assert_eq!(tmp.level(), bzip2::Compression::new(9).level()); let tmp: bzip2::Compression = Level::Nineteen.into(); assert_eq!(tmp.level(), bzip2::Compression::new(9).level()); let tmp: bzip2::Compression = Level::Twenty.into(); assert_eq!(tmp.level(), bzip2::Compression::new(9).level()); let tmp: bzip2::Compression = Level::TwentyOne.into(); assert_eq!(tmp.level(), bzip2::Compression::new(9).level()); } } niffler-2.6.0/src/lib.rs000064400000000000000000000055301046102023000131640ustar 00000000000000//! # niffler //! Simple and transparent support for compressed files. //! //! This library provides two main features: //! - sniffs out compression formats from input files and return a //! Read trait object ready for consumption. //! - Create a Writer initialized with compression ready for writing. //! //! The goal is to lower the barrier to open and use a file, especially in //! bioinformatics workflows. //! //! # Example //! //! ```rust //! use niffler::{Error, compression}; //! # fn main() -> Result<(), Error> { //! # #[cfg(feature = "gz")] { //! let mut buffer = Vec::new(); //! //! { //! let mut writer = niffler::get_writer(Box::new(&mut buffer), compression::Format::Gzip, niffler::Level::Nine)?; //! writer.write_all(b"hello")?; //! } //! //! # assert_eq!(&buffer, &[0x1f, 0x8b, 8, 0, 0, 0, 0, 0, 2, 255, 203, 72, 205, 201, 201, 7, 0, 134, 166, 16, 54, 5, 0, 0, 0]); //! //! let (mut reader, compression) = niffler::get_reader(Box::new(&buffer[..]))?; //! //! let mut contents = String::new(); //! reader.read_to_string(&mut contents)?; //! //! assert_eq!(compression, niffler::compression::Format::Gzip); //! assert_eq!(contents, "hello"); //! # } //! # Ok(()) //! # } //! ``` //! //! ## Selecting compression formats //! //! By default all supported compression formats are enabled. //! If you're working on systems that don't support them you can disable default //! features and select the ones you want. //! For example, //! currently only `gz` is supported in Webassembly environments //! (because `niffler` depends on crates that have system dependencies for `bz2` and `lzma` compression), //! so you can use this in your `Cargo.toml` to select only the `gz` support: //! ```toml //! niffler = { version = "2.2.0", default-features = false, features = ["gz"] } //! ``` //! //! You can still use `niffler::sniff()` to find what is the compression format, //! even if any feature is disabled. //! But if you try to use `niffler::get_reader` for a disabled feature, //! it will throw a runtime error. //! //! ## Backends features //! //! The libraries that are used for decompression provide a number of features that can have a significant impact on performance. //! Here is the list of features available with corresponding backend crates and features name in backend crates: //! - bz2_tokio -> bzip2 tokio //! - bz2_static -> bzip2 static //! - lzma_tokio -> lzma tokio //! - gz_zlib -> flate2 zlib //! - gz_zlib-ng-compat -> flate2 zlib-ng-compat //! - gz_cloudflare_zlib -> flate2 cloudflare_zlib //! - gz_rust_backend -> flate2 rust_backend //! - xz_tokio -> xz2 tokio /* declare mod */ pub mod basic; pub mod error; pub mod level; pub mod seek; pub mod seeksend; pub mod send; pub(crate) mod utils; /* reexport for convinent usage of niffler */ pub use crate::basic::compression::Format; pub use crate::basic::*; pub use crate::error::Error; pub use crate::level::Level; niffler-2.6.0/src/seek/compression.rs000064400000000000000000000012511046102023000157020ustar 00000000000000/* standard use */ use std::io; /* Some trait definition */ pub trait ReadSeek: io::Read + io::Seek {} impl ReadSeek for T where T: io::Read + io::Seek {} pub trait WriteSeek: io::Write + io::Seek {} impl WriteSeek for T where T: io::Write + io::Seek {} /// `Format` represent a compression format of a file. Currently BGzip are supported. #[derive(Debug, PartialEq, Eq, Clone, Copy)] pub enum Format { BGzip, No, } pub(crate) fn bytes2type(bytes: [u8; 17]) -> Format { match bytes { [0x1F, 0x8B, 0x8, 0x4, 0x0, 0x0, 0x0, 0x0, 0x0, 0xFF, 0x6, 0x0, 0x42, 0x43, 0x2, 0x0, 0x0] => { Format::BGzip } _ => Format::No, } } niffler-2.6.0/src/seek/mod.rs000064400000000000000000000102341046102023000141210ustar 00000000000000/* declare mod */ pub mod compression; /* standard use */ use std::io; use std::path::Path; /* project use */ use crate::error::Error; use crate::level::Level; /// Similar as [sniff](crate::sniff) but from seekable format /// /// Only [compression::Format] are support pub fn sniff<'a>( mut in_stream: Box, ) -> Result<(Box, compression::Format), Error> { let first_bytes = crate::utils::get_first_bytes(&mut in_stream)?; match compression::bytes2type(first_bytes) { e @ compression::Format::BGzip => Ok((in_stream, e)), _ => Ok((in_stream, compression::Format::No)), } } /// Similar as [get_reader](crate::sniff) but from seekable format /// /// Warning actualy this function work only for not compressed file pub fn get_reader<'a>( in_stream: Box, ) -> Result<(Box, compression::Format), Error> { // check compression let (in_stream, compression) = sniff(in_stream)?; // return readable and compression status match compression { compression::Format::No => Ok((in_stream, compression::Format::No)), _ => Err(Error::FeatureDisabled), } } /// Similar as [get_writer](crate::get_writer) but from seekable format /// /// Warning actualy this function work only for not compressed file pub fn get_writer<'a>( out_stream: Box, format: compression::Format, _level: Level, ) -> Result, Error> { match format { compression::Format::No => Ok(Box::new(out_stream)), _ => Err(Error::FeatureDisabled), } } /// Similar as [from_path](crate::from_path) but from seekable format /// /// Warning actualy this function work only for not compressed file pub fn from_path<'a, P: AsRef>( path: P, ) -> Result<(Box, compression::Format), Error> { let readable = io::BufReader::new(std::fs::File::open(path)?); get_reader(Box::new(readable)) } /// Similar as [to_path](crate::to_path) but from seekable format /// /// Warning actualy this function work only for not compressed file pub fn to_path<'a, P: AsRef>( path: P, format: compression::Format, level: Level, ) -> Result, Error> { let writable = io::BufWriter::new(std::fs::File::create(path)?); get_writer(Box::new(writable), format, level) } #[cfg(test)] mod test { use super::*; use tempfile::NamedTempFile; pub(crate) const SHORT_FILE: &'static [u8] = &[0o037, 0o213, 0o0, 0o0]; pub(crate) const BGZIP_FILE: &'static [u8] = &[ 0x1F, 0x8B, 0x8, 0x4, 0x0, 0x0, 0x0, 0x0, 0x0, 0xFF, 0x6, 0x0, 0x42, 0x43, 0x2, 0x0, 0x0, ]; pub(crate) const LOREM_IPSUM: &'static [u8] = b"Lorem ipsum dolor sit amet, consectetur adipiscing elit. Ut ultricies scelerisque diam, a scelerisque enim sagittis at."; mod compression_format_detection { use super::*; use std::io::Write; #[test] fn bgzip() { let mut ofile = NamedTempFile::new().expect("Can't create tmpfile"); ofile.write_all(BGZIP_FILE).unwrap(); let rfile = ofile.reopen().expect("Can't create tmpfile"); let (_, compression) = sniff(Box::new(rfile)).expect("Error in read file"); assert_eq!(compression, compression::Format::BGzip); } #[test] fn too_short() { let mut ofile = NamedTempFile::new().expect("Can't create tmpfile"); ofile.write_all(SHORT_FILE).unwrap(); let rfile = ofile.reopen().expect("Can't create tmpfile"); let result = sniff(Box::new(rfile)); assert!(result.is_err()); } #[test] fn no_compression() { let mut ofile = NamedTempFile::new().expect("Can't create tmpfile"); ofile.write_all(LOREM_IPSUM).unwrap(); let rfile = ofile.reopen().expect("Can't create tmpfile"); let (_, compression) = sniff(Box::new(rfile)).expect("Error in read file"); assert_eq!(compression, compression::Format::No); } } } niffler-2.6.0/src/seeksend/compression.rs000064400000000000000000000006401046102023000165550ustar 00000000000000/// `Format` represent a compression format of a file. Currently BGzip are supported. #[derive(Debug, PartialEq, Eq, Clone, Copy)] pub enum Format { BGzip, No, } pub(crate) fn bytes2type(bytes: [u8; 17]) -> Format { match bytes { [0x1F, 0x8B, 0x8, 0x4, 0x0, 0x0, 0x0, 0x0, 0x0, 0xFF, 0x6, 0x0, 0x42, 0x43, 0x2, 0x0, 0x0] => { Format::BGzip } _ => Format::No, } } niffler-2.6.0/src/seeksend/mod.rs000064400000000000000000000077261046102023000150070ustar 00000000000000/* declare mod */ pub mod compression; /* standard use */ use std::io; use std::path::Path; /* project use */ use crate::error::Error; use crate::level::Level; use crate::seek::compression::{ReadSeek, WriteSeek}; /// Similar to [seek::sniff](crate::sniff) but readble seekable object is now sendable pub fn sniff<'a>( mut in_stream: Box, ) -> Result<(Box, compression::Format), Error> { let first_bytes = crate::utils::get_first_bytes(&mut in_stream)?; match compression::bytes2type(first_bytes) { e @ compression::Format::BGzip => Ok((in_stream, e)), _ => Ok((in_stream, compression::Format::No)), } } /// Similar to [seek::get_reader](crate::get_reader) but readble seekable object is now sendable pub fn get_reader<'a>( in_stream: Box, ) -> Result<(Box, compression::Format), Error> { // check compression let (in_stream, compression) = sniff(in_stream)?; // return readable and compression status match compression { compression::Format::No => Ok((in_stream, compression::Format::No)), _ => Err(Error::FeatureDisabled), } } /// Similar to [seek::get_writer](crate::get_writer) but writable seekable object is now sendable pub fn get_writer<'a>( out_stream: Box, format: compression::Format, _level: Level, ) -> Result, Error> { match format { compression::Format::No => Ok(Box::new(out_stream)), _ => Err(Error::FeatureDisabled), } } /// Similar to [seek::from_path](crate::from_path) but readble seekable object is now sendable pub fn from_path<'a, P: AsRef>( path: P, ) -> Result<(Box, compression::Format), Error> { let readable = io::BufReader::new(std::fs::File::open(path)?); get_reader(Box::new(readable)) } /// Similar to [seek::to_path](crate::to_path) but writable seekable object is now sendable pub fn to_path<'a, P: AsRef>( path: P, format: compression::Format, level: Level, ) -> Result, Error> { let writable = io::BufWriter::new(std::fs::File::create(path)?); get_writer(Box::new(writable), format, level) } #[cfg(test)] mod test { use super::*; use tempfile::NamedTempFile; pub(crate) const SHORT_FILE: &'static [u8] = &[0o037, 0o213, 0o0, 0o0]; pub(crate) const BGZIP_FILE: &'static [u8] = &[ 0x1F, 0x8B, 0x8, 0x4, 0x0, 0x0, 0x0, 0x0, 0x0, 0xFF, 0x6, 0x0, 0x42, 0x43, 0x2, 0x0, 0x0, ]; pub(crate) const LOREM_IPSUM: &'static [u8] = b"Lorem ipsum dolor sit amet, consectetur adipiscing elit. Ut ultricies scelerisque diam, a scelerisque enim sagittis at."; mod compression_format_detection { use super::*; use std::io::Write; #[test] fn bgzip() { let mut ofile = NamedTempFile::new().expect("Can't create tmpfile"); ofile.write_all(BGZIP_FILE).unwrap(); let rfile = ofile.reopen().expect("Can't create tmpfile"); let (_, compression) = sniff(Box::new(rfile)).expect("Error in read file"); assert_eq!(compression, compression::Format::BGzip); } #[test] fn too_short() { let mut ofile = NamedTempFile::new().expect("Can't create tmpfile"); ofile.write_all(SHORT_FILE).unwrap(); let rfile = ofile.reopen().expect("Can't create tmpfile"); let result = sniff(Box::new(rfile)); assert!(result.is_err()); } #[test] fn no_compression() { let mut ofile = NamedTempFile::new().expect("Can't create tmpfile"); ofile.write_all(LOREM_IPSUM).unwrap(); let rfile = ofile.reopen().expect("Can't create tmpfile"); let (_, compression) = sniff(Box::new(rfile)).expect("Error in read file"); assert_eq!(compression, compression::Format::No); } } } niffler-2.6.0/src/send/compression.rs000064400000000000000000000113231046102023000157050ustar 00000000000000#![allow(clippy::unnecessary_wraps)] /* standard use */ use std::io; /* crates use */ use cfg_if::cfg_if; /* project use */ use crate::error::Error; use crate::level::Level; /* Format detection enum */ /// `Format` represent a compression format of a file. Currently Gzip, Bzip, Lzma or No are supported. #[derive(Debug, PartialEq, Eq, Clone, Copy)] pub enum Format { Gzip, Bzip, Lzma, Zstd, No, } impl Format { /// An alias for Lzma, Format::Lzma == Format::Xz #[allow(non_upper_case_globals)] pub const Xz: Format = Format::Lzma; } pub(crate) fn bytes2type(bytes: [u8; 5]) -> Format { match bytes { [0x1f, 0x8b, ..] => Format::Gzip, [0x42, 0x5a, ..] => Format::Bzip, [0xfd, 0x37, 0x7a, 0x58, 0x5a] => Format::Lzma, [0x28, 0xb5, 0x2f, 0xfd, ..] => Format::Zstd, _ => Format::No, } } cfg_if! { if #[cfg(feature = "gz")] { pub(crate) fn new_gz_encoder<'a>(out: Box, level: Level) -> Result, Error> { Ok(Box::new(flate2::write::GzEncoder::new( out, level.into(), ))) } pub(crate) fn new_gz_decoder<'a>( inp: Box, ) -> Result<(Box, Format), Error> { Ok(( Box::new(flate2::read::MultiGzDecoder::new(inp)), Format::Gzip, )) } } else { pub(crate) fn new_gz_encoder<'a>(_: Box, _: Level) -> Result, Error> { Err(Error::FeatureDisabled) } pub(crate) fn new_gz_decoder<'a>(_: Box) -> Result<(Box, Format), Error> { Err(Error::FeatureDisabled) } } } cfg_if! { if #[cfg(feature = "bz2")] { pub(crate) fn new_bz2_encoder<'a>(out: Box, level: Level) -> Result, Error> { Ok(Box::new(bzip2::write::BzEncoder::new( out, level.into(), ))) } pub(crate) fn new_bz2_decoder<'a>( inp: Box, ) -> Result<(Box, Format), Error> { Ok(( Box::new(bzip2::read::BzDecoder::new(inp)), Format::Bzip, )) } } else { pub(crate) fn new_bz2_encoder<'a>(_: Box, _: Level) -> Result, Error> { Err(Error::FeatureDisabled) } pub(crate) fn new_bz2_decoder<'a>(_: Box) -> Result<(Box, Format), Error> { Err(Error::FeatureDisabled) } } } cfg_if! { if #[cfg(feature = "lzma")] { pub(crate) fn new_lzma_encoder<'a>(out: Box, level: Level) -> Result, Error> { Ok(Box::new(liblzma::write::XzEncoder::new(out, level.into()))) } pub(crate) fn new_lzma_decoder<'a>( inp: Box, ) -> Result<(Box, Format), Error> { Ok(( Box::new(liblzma::read::XzDecoder::new(inp)), Format::Lzma, )) } } else { pub(crate) fn new_lzma_encoder<'a>(_: Box, _: Level) -> Result, Error> { Err(Error::FeatureDisabled) } pub(crate) fn new_lzma_decoder<'a>(_: Box) -> Result<(Box, Format), Error> { Err(Error::FeatureDisabled) } } } cfg_if! { if #[cfg(feature = "zstd")] { pub(crate) fn new_zstd_encoder<'a>(out: Box, level: Level) -> Result, Error> { Ok(Box::new(zstd::stream::write::Encoder::new( out, level.into(), )?.auto_finish())) } pub(crate) fn new_zstd_decoder<'a>( inp: Box, ) -> Result<(Box, Format), Error> { Ok((Box::new(zstd::stream::read::Decoder::new(inp)?), Format::Zstd, )) } } else { pub(crate) fn new_zstd_encoder<'a>(_: Box, _: Level) -> Result, Error> { Err(Error::FeatureDisabled) } pub(crate) fn new_zstd_decoder<'a>(_: Box) -> Result<(Box, Format), Error> { Err(Error::FeatureDisabled) } } } niffler-2.6.0/src/send/mod.rs000064400000000000000000000310171046102023000141250ustar 00000000000000pub mod compression; /* standard use */ use std::io; use std::io::Read; use std::path::Path; /* project use */ use crate::error::Error; use crate::level::Level; /// Similar to [sniff](crate::sniff) but readable stream is now sendable pub fn sniff<'a>( in_stream: Box, ) -> Result<(Box, compression::Format), Error> { let (first_bytes, in_stream) = crate::utils::get_first_five(in_stream)?; let cursor = io::Cursor::new(first_bytes); match compression::bytes2type(first_bytes) { e @ compression::Format::Gzip | e @ compression::Format::Bzip | e @ compression::Format::Lzma | e @ compression::Format::Zstd => Ok((Box::new(cursor.chain(in_stream)), e)), _ => Ok((Box::new(cursor.chain(in_stream)), compression::Format::No)), } } /// Similar to [get_reader](crate::get_reader) but readable stream is now sendable pub fn get_reader<'a>( in_stream: Box, ) -> Result<(Box, compression::Format), Error> { // check compression let (in_stream, compression) = sniff(in_stream)?; // return readable and compression status match compression { compression::Format::Gzip => compression::new_gz_decoder(in_stream), compression::Format::Bzip => compression::new_bz2_decoder(in_stream), compression::Format::Lzma => compression::new_lzma_decoder(in_stream), compression::Format::Zstd => compression::new_zstd_decoder(in_stream), compression::Format::No => Ok((in_stream, compression::Format::No)), } } /// Similar to [get_writer](crate::get_writer) but writable stream is now sendable pub fn get_writer<'a>( out_stream: Box, format: compression::Format, level: Level, ) -> Result, Error> { match format { compression::Format::Gzip => compression::new_gz_encoder(out_stream, level), compression::Format::Bzip => compression::new_bz2_encoder(out_stream, level), compression::Format::Lzma => compression::new_lzma_encoder(out_stream, level), compression::Format::Zstd => compression::new_zstd_encoder(out_stream, level), compression::Format::No => Ok(Box::new(out_stream)), } } /// Similar to [from_path](crate::from_path) but readable stream is now sendable pub fn from_path<'a, P: AsRef>( path: P, ) -> Result<(Box, compression::Format), Error> { let readable = io::BufReader::new(std::fs::File::open(path)?); get_reader(Box::new(readable)) } /// Similar to [to_path](crate::to_path) but writable stream is now sendable pub fn to_path<'a, P: AsRef>( path: P, format: compression::Format, level: Level, ) -> Result, Error> { let writable = io::BufWriter::new(std::fs::File::create(path)?); get_writer(Box::new(writable), format, level) } #[cfg(test)] mod test { use super::*; use tempfile::NamedTempFile; pub(crate) const SHORT_FILE: &'static [u8] = &[0o037, 0o213, 0o0, 0o0]; pub(crate) const GZIP_FILE: &'static [u8] = &[0o037, 0o213, 0o0, 0o0, 0o0]; pub(crate) const BZIP_FILE: &'static [u8] = &[0o102, 0o132, 0o0, 0o0, 0o0]; pub(crate) const LZMA_FILE: &'static [u8] = &[0o375, 0o067, 0o172, 0o130, 0o132]; pub(crate) const LOREM_IPSUM: &'static [u8] = b"Lorem ipsum dolor sit amet, consectetur adipiscing elit. Ut ultricies scelerisque diam, a scelerisque enim sagittis at."; pub(crate) const ZSTD_FILE: &'static [u8] = &[0x28, 0xb5, 0x2f, 0xfd, 0]; mod compress_uncompress { use super::*; #[test] fn no_compression() { let ofile = NamedTempFile::new().expect("Can't create tmpfile"); { let wfile = ofile.reopen().expect("Can't create tmpfile"); let mut writer = get_writer(Box::new(wfile), compression::Format::No, Level::One).unwrap(); writer .write_all(LOREM_IPSUM) .expect("Error during write of data"); } let rfile = ofile.reopen().expect("Can't create tmpfile"); let (mut reader, compression) = get_reader(Box::new(rfile)).expect("Error reading from tmpfile"); assert_eq!(compression, compression::Format::No); let mut buffer = Vec::new(); reader .read_to_end(&mut buffer) .expect("Error during reading"); assert_eq!(LOREM_IPSUM, buffer.as_slice()); } #[cfg(feature = "gz")] #[test] fn gzip() { let ofile = NamedTempFile::new().expect("Can't create tmpfile"); { let wfile = ofile.reopen().expect("Can't create tmpfile"); let mut writer = get_writer(Box::new(wfile), compression::Format::Gzip, Level::Six).unwrap(); writer .write_all(LOREM_IPSUM) .expect("Error during write of data"); } let rfile = ofile.reopen().expect("Can't create tmpfile"); let (mut reader, compression) = get_reader(Box::new(rfile)).expect("Error reading from tmpfile"); assert_eq!(compression, compression::Format::Gzip); let mut buffer = Vec::new(); reader .read_to_end(&mut buffer) .expect("Error during reading"); assert_eq!(LOREM_IPSUM, buffer.as_slice()); } #[test] #[cfg(not(feature = "bz2"))] fn no_bzip2_feature() { assert!( get_writer(Box::new(vec![]), compression::Format::Bzip, Level::Six).is_err(), "bz2 disabled, this assertion should fail" ); assert!( get_reader(Box::new(&BZIP_FILE[..])).is_err(), "bz2 disabled, this assertion should fail" ); } #[cfg(feature = "bz2")] #[test] fn bzip() { let ofile = NamedTempFile::new().expect("Can't create tmpfile"); { let wfile = ofile.reopen().expect("Can't create tmpfile"); let mut writer = get_writer(Box::new(wfile), compression::Format::Bzip, Level::Six).unwrap(); writer .write_all(LOREM_IPSUM) .expect("Error during write of data"); } let rfile = ofile.reopen().expect("Can't create tmpfile"); let (mut reader, compression) = get_reader(Box::new(rfile)).expect("Error reading from tmpfile"); assert_eq!(compression, compression::Format::Bzip); let mut buffer = Vec::new(); reader .read_to_end(&mut buffer) .expect("Error during reading"); assert_eq!(LOREM_IPSUM, buffer.as_slice()); } #[test] #[cfg(not(feature = "lzma"))] fn no_lzma_feature() { assert!( get_writer(Box::new(vec![]), compression::Format::Lzma, Level::Six).is_err(), "lzma disabled, this assertion should fail" ); assert!( get_reader(Box::new(&LZMA_FILE[..])).is_err(), "lzma disabled, this assertion should fail" ); } #[cfg(feature = "lzma")] #[test] fn lzma() { let ofile = NamedTempFile::new().expect("Can't create tmpfile"); { let wfile = ofile.reopen().expect("Can't create tmpfile"); let mut writer = get_writer(Box::new(wfile), compression::Format::Lzma, Level::Six).unwrap(); writer .write_all(LOREM_IPSUM) .expect("Error during write of data"); } let rfile = ofile.reopen().expect("Can't create tmpfile"); let (mut reader, compression) = get_reader(Box::new(rfile)).expect("Error reading from tmpfile"); assert_eq!(compression, compression::Format::Lzma); let mut buffer = Vec::new(); reader .read_to_end(&mut buffer) .expect("Error during reading"); assert_eq!(LOREM_IPSUM, buffer.as_slice()); } #[test] #[cfg(all(not(feature = "xz"), not(feature = "lzma")))] fn no_xz_feature() { assert!( get_writer(Box::new(vec![]), compression::Format::Xz, Level::Six).is_err(), "xz disabled, this assertion should fail" ); assert!( get_reader(Box::new(&LZMA_FILE[..])).is_err(), "lzma disabled, this assertion should fail" ); } #[cfg(feature = "xz")] #[test] fn xz() { let ofile = NamedTempFile::new().expect("Can't create tmpfile"); { let wfile = ofile.reopen().expect("Can't create tmpfile"); let mut writer = get_writer(Box::new(wfile), compression::Format::Xz, Level::Six).unwrap(); writer .write_all(LOREM_IPSUM) .expect("Error during write of data"); } let rfile = ofile.reopen().expect("Can't create tmpfile"); let (mut reader, compression) = get_reader(Box::new(rfile)).expect("Error reading from tmpfile"); assert_eq!(compression, compression::Format::Xz); let mut buffer = Vec::new(); reader .read_to_end(&mut buffer) .expect("Error during reading"); assert_eq!(LOREM_IPSUM, buffer.as_slice()); } #[test] #[cfg(not(feature = "zstd"))] fn no_zstd_feature() { assert!( get_writer(Box::new(vec![]), compression::Format::Zstd, Level::Six).is_err(), "zstd disabled, this assertion should fail" ); assert!( get_reader(Box::new(&ZSTD_FILE[..])).is_err(), "zstd disabled, this assertion should fail" ); } #[cfg(feature = "zstd")] #[test] fn zstd() { let ofile = NamedTempFile::new().expect("Can't create tmpfile"); { let wfile = ofile.reopen().expect("Can't create tmpfile"); let mut writer = get_writer(Box::new(wfile), compression::Format::Zstd, Level::Six).unwrap(); writer .write_all(LOREM_IPSUM) .expect("Error during write of data"); } let rfile = ofile.reopen().expect("Can't create tmpfile"); let (mut reader, compression) = get_reader(Box::new(rfile)).expect("Error reading from tmpfile"); assert_eq!(compression, compression::Format::Zstd); let mut buffer = Vec::new(); reader .read_to_end(&mut buffer) .expect("Error during reading"); assert_eq!(LOREM_IPSUM, buffer.as_slice()); } } mod compression_format_detection { use super::*; #[test] fn gzip() { let (_, compression) = sniff(Box::new(GZIP_FILE)).expect("Error in read file"); assert_eq!(compression, compression::Format::Gzip); } #[test] fn bzip() { let (_, compression) = sniff(Box::new(BZIP_FILE)).expect("Error in read file"); assert_eq!(compression, compression::Format::Bzip); } #[test] fn lzma() { let (_, compression) = sniff(Box::new(LZMA_FILE)).expect("Error in read file"); assert_eq!(compression, compression::Format::Lzma); } #[test] fn xz() { let (_, compression) = sniff(Box::new(LZMA_FILE)).expect("Error in read file"); assert_eq!(compression, compression::Format::Xz); } #[test] fn zstd() { let (_, compression) = sniff(Box::new(ZSTD_FILE)).expect("Error in read file"); assert_eq!(compression, compression::Format::Zstd); } #[test] fn too_short() { let result = sniff(Box::new(SHORT_FILE)); assert!(result.is_err()); } #[test] fn no_compression() { let (_, compression) = sniff(Box::new(LOREM_IPSUM)).expect("Error in read file"); assert_eq!(compression, compression::Format::No); } } } niffler-2.6.0/src/utils.rs000064400000000000000000000013231046102023000135520ustar 00000000000000/* standard use */ use std::io; /* project use */ use crate::error::Error; use crate::seek::compression::ReadSeek; pub fn get_first_five<'a, T>(mut in_stream: T) -> Result<([u8; 5], T), Error> where T: io::Read + 'a, { let mut buf = [0u8; 5]; match in_stream.read_exact(&mut buf) { Ok(()) => Ok((buf, in_stream)), Err(_) => Err(Error::FileTooShort), } } pub fn get_first_bytes<'a, T>(in_stream: &mut T) -> Result<[u8; 17], Error> where T: ReadSeek + 'a, { let mut buf = [0u8; 17]; match in_stream.read_exact(&mut buf) { Ok(()) => { in_stream.seek(io::SeekFrom::Start(0))?; Ok(buf) } Err(_) => Err(Error::FileTooShort), } }