Vendor dependencies

This commit is contained in:
2026-08-01 16:11:49 +03:00
parent 7f139a0241
commit 6b5e7f0f8b
29706 changed files with 9575646 additions and 0 deletions
+1
View File
@@ -0,0 +1 @@
{"$comment":"This file only protects against accidental modifications. It is not a security mechanism and does not protect against malicious changes.","files":{".cargo_vcs_info.json":"6cd045dc97de4190a4069381ac9c51d9e791667579c737a24f7724df740d772b","Cargo.lock":"41a2ade31d797bb10b56628570bcf3c972a1497a3f84922afde5000c4ff09d43","Cargo.toml":"5af4c418d6b293b6f1892fc7ba92b4586f96829abf133be1519818ea42dce159","Cargo.toml.orig":"ae762fb67f59ecc40075f26ebfa69e7a5a106bf5ac9223a2616307721b6344ad","LICENSE":"a77b7cfeaf911ed410ffbe76f0cb2b24ad8a4d94e7ead5727e914425c416cc63","LICENSE.Apache-2.0":"0d542e0c8804e39aa7f37eb00da5a762149dc682d7829451287e11b938e94594","LICENSE.Mit":"129e8edef29e9abcd2ebabe252f4ef1b1289cdca356bf0040284a2fbccfb96c8","Readme.md":"db2e504468fe11556528df4949f492a2a91377ba6a71967732a3e460b7ae4941","build.rs":"2342e59833e2ebca2980884d4f242a6bf1b0143037c212e05514626ad5213505","src/constants.rs":"1804193790b251ed2f87acb0da25a3bbda1def0e4c4f5bfa110963d61654b3c3","src/constants_experimental.rs":"3a878cfb0cfb8fdf900c0218122524701d7b79ccc1c21ee0cb1f4325e45c3fe1","src/constants_seekable.rs":"c4ccecf0b16946f930122ea5f7600d1239f804998897d62285f2f3a01162dd6c","src/lib.rs":"9540a20cd098c75cef3fe0fb0c90e96796959f24f80f655dc3c3d58037f1905e","src/seekable.rs":"c4bc04f2538f37944d7277b7b66096d6d24f3dd30b224d7115c653f1f50d6a84","src/tests.rs":"c25e20883c85f58e39abc04b92d3c6673e6f1d3888f3350663533962a0eb1512"},"package":"8f49c4d5f0abb602a93fb8736af2a4f4dd9512e36f7f570d66e65ff867ed3b9d"}
+6
View File
@@ -0,0 +1,6 @@
{
"git": {
"sha1": "229054099aa73f7e861762f687d7e07cac1d9b3b"
},
"path_in_vcs": "zstd-safe"
}
+305
View File
@@ -0,0 +1,305 @@
# This file is automatically @generated by Cargo.
# It is not intended for manual editing.
version = 3
[[package]]
name = "aho-corasick"
version = "1.1.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "8e60d3430d3a69478ad0993f19238d2df97c507009a52b3c10addcd7f6bcb916"
dependencies = [
"memchr",
]
[[package]]
name = "bindgen"
version = "0.71.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "5f58bf3d7db68cfbac37cfc485a8d711e87e064c3d0fe0435b92f7a407f9d6b3"
dependencies = [
"bitflags",
"cexpr",
"clang-sys",
"itertools",
"proc-macro2",
"quote",
"regex",
"rustc-hash",
"shlex",
"syn",
]
[[package]]
name = "bitflags"
version = "2.8.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "8f68f53c83ab957f72c32642f3868eec03eb974d1fb82e453128456482613d36"
[[package]]
name = "cc"
version = "1.2.15"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "c736e259eea577f443d5c86c304f9f4ae0295c43f3ba05c21f1d66b5f06001af"
dependencies = [
"jobserver",
"libc",
"shlex",
]
[[package]]
name = "cexpr"
version = "0.6.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "6fac387a98bb7c37292057cffc56d62ecb629900026402633ae9160df93a8766"
dependencies = [
"nom",
]
[[package]]
name = "cfg-if"
version = "1.0.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "baf1de4339761588bc0619e3cbc0120ee582ebb74b53b4efbf79117bd2da40fd"
[[package]]
name = "clang-sys"
version = "1.8.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "0b023947811758c97c59bf9d1c188fd619ad4718dcaa767947df1cadb14f39f4"
dependencies = [
"glob",
"libc",
"libloading",
]
[[package]]
name = "either"
version = "1.13.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "60b1af1c220855b6ceac025d3f6ecdd2b7c4894bfe9cd9bda4fbb4bc7c0d4cf0"
[[package]]
name = "glob"
version = "0.3.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "a8d1add55171497b4705a648c6b583acafb01d58050a51727785f0b2c8e0a2b2"
[[package]]
name = "itertools"
version = "0.13.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "413ee7dfc52ee1a4949ceeb7dbc8a33f2d6c088194d9f922fb8318faf1f01186"
dependencies = [
"either",
]
[[package]]
name = "jobserver"
version = "0.1.32"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "48d1dbcbbeb6a7fec7e059840aa538bd62aaccf972c7346c4d9d2059312853d0"
dependencies = [
"libc",
]
[[package]]
name = "libc"
version = "0.2.169"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "b5aba8db14291edd000dfcc4d620c7ebfb122c613afb886ca8803fa4e128a20a"
[[package]]
name = "libloading"
version = "0.8.6"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "fc2f4eb4bc735547cfed7c0a4922cbd04a4655978c09b54f1f7b228750664c34"
dependencies = [
"cfg-if",
"windows-targets",
]
[[package]]
name = "memchr"
version = "2.7.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "78ca9ab1a0babb1e7d5695e3530886289c18cf2f87ec19a575a0abdce112e3a3"
[[package]]
name = "minimal-lexical"
version = "0.2.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "68354c5c6bd36d73ff3feceb05efa59b6acb7626617f4962be322a825e61f79a"
[[package]]
name = "nom"
version = "7.1.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "d273983c5a657a70a3e8f2a01329822f3b8c8172b73826411a55751e404a0a4a"
dependencies = [
"memchr",
"minimal-lexical",
]
[[package]]
name = "pkg-config"
version = "0.3.31"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "953ec861398dccce10c670dfeaf3ec4911ca479e9c02154b3a215178c5f566f2"
[[package]]
name = "proc-macro2"
version = "1.0.93"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "60946a68e5f9d28b0dc1c21bb8a97ee7d018a8b322fa57838ba31cc878e22d99"
dependencies = [
"unicode-ident",
]
[[package]]
name = "quote"
version = "1.0.38"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "0e4dccaaaf89514f546c693ddc140f729f958c247918a13380cccc6078391acc"
dependencies = [
"proc-macro2",
]
[[package]]
name = "regex"
version = "1.11.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "b544ef1b4eac5dc2db33ea63606ae9ffcfac26c1416a2806ae0bf5f56b201191"
dependencies = [
"aho-corasick",
"memchr",
"regex-automata",
"regex-syntax",
]
[[package]]
name = "regex-automata"
version = "0.4.9"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "809e8dc61f6de73b46c85f4c96486310fe304c434cfa43669d7b40f711150908"
dependencies = [
"aho-corasick",
"memchr",
"regex-syntax",
]
[[package]]
name = "regex-syntax"
version = "0.8.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "2b15c43186be67a4fd63bee50d0303afffcef381492ebe2c5d87f324e1b8815c"
[[package]]
name = "rustc-hash"
version = "2.1.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "357703d41365b4b27c590e3ed91eabb1b663f07c4c084095e60cbed4362dff0d"
[[package]]
name = "shlex"
version = "1.3.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "0fda2ff0d084019ba4d7c6f371c95d8fd75ce3524c3cb8fb653a3023f6323e64"
[[package]]
name = "syn"
version = "2.0.98"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "36147f1a48ae0ec2b5b3bc5b537d267457555a10dc06f3dbc8cb11ba3006d3b1"
dependencies = [
"proc-macro2",
"quote",
"unicode-ident",
]
[[package]]
name = "unicode-ident"
version = "1.0.17"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "00e2473a93778eb0bad35909dff6a10d28e63f792f16ed15e404fca9d5eeedbe"
[[package]]
name = "windows-targets"
version = "0.52.6"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "9b724f72796e036ab90c1021d4780d4d3d648aca59e491e6b98e725b84e99973"
dependencies = [
"windows_aarch64_gnullvm",
"windows_aarch64_msvc",
"windows_i686_gnu",
"windows_i686_gnullvm",
"windows_i686_msvc",
"windows_x86_64_gnu",
"windows_x86_64_gnullvm",
"windows_x86_64_msvc",
]
[[package]]
name = "windows_aarch64_gnullvm"
version = "0.52.6"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "32a4622180e7a0ec044bb555404c800bc9fd9ec262ec147edd5989ccd0c02cd3"
[[package]]
name = "windows_aarch64_msvc"
version = "0.52.6"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "09ec2a7bb152e2252b53fa7803150007879548bc709c039df7627cabbd05d469"
[[package]]
name = "windows_i686_gnu"
version = "0.52.6"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "8e9b5ad5ab802e97eb8e295ac6720e509ee4c243f69d781394014ebfe8bbfa0b"
[[package]]
name = "windows_i686_gnullvm"
version = "0.52.6"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "0eee52d38c090b3caa76c563b86c3a4bd71ef1a819287c19d586d7334ae8ed66"
[[package]]
name = "windows_i686_msvc"
version = "0.52.6"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "240948bc05c5e7c6dabba28bf89d89ffce3e303022809e73deaefe4f6ec56c66"
[[package]]
name = "windows_x86_64_gnu"
version = "0.52.6"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "147a5c80aabfbf0c7d901cb5895d1de30ef2907eb21fbbab29ca94c5b08b1a78"
[[package]]
name = "windows_x86_64_gnullvm"
version = "0.52.6"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "24d5b23dc417412679681396f2b49f3de8c1473deb516bd34410872eff51ed0d"
[[package]]
name = "windows_x86_64_msvc"
version = "0.52.6"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "589f6da84c646204747d1270a2a5661ea66ed1cced2631d546fdfb155959f9ec"
[[package]]
name = "zstd-safe"
version = "7.2.4"
dependencies = [
"zstd-sys",
]
[[package]]
name = "zstd-sys"
version = "2.0.15+zstd.1.5.7"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "eb81183ddd97d0c74cedf1d50d85c8d08c1b8b68ee863bdee9e706eedba1a237"
dependencies = [
"bindgen",
"cc",
"pkg-config",
]
+79
View File
@@ -0,0 +1,79 @@
# THIS FILE IS AUTOMATICALLY GENERATED BY CARGO
#
# When uploading crates to the registry Cargo will automatically
# "normalize" Cargo.toml files for maximal compatibility
# with all versions of Cargo and also rewrite `path` dependencies
# to registry (e.g., crates.io) dependencies.
#
# If you are reading this file be aware that the original Cargo.toml
# will likely look very different (and much more reasonable).
# See Cargo.toml.orig for the original contents.
[package]
edition = "2018"
rust-version = "1.64"
name = "zstd-safe"
version = "7.2.4"
authors = ["Alexandre Bury <alexandre.bury@gmail.com>"]
build = "build.rs"
exclude = ["update_consts.sh"]
autolib = false
autobins = false
autoexamples = false
autotests = false
autobenches = false
description = "Safe low-level bindings for the zstd compression library."
readme = "Readme.md"
keywords = [
"zstd",
"zstandard",
"compression",
]
categories = [
"api-bindings",
"compression",
]
license = "MIT OR Apache-2.0"
repository = "https://github.com/gyscos/zstd-rs"
[package.metadata.docs.rs]
features = [
"experimental",
"arrays",
"std",
"zdict_builder",
"doc-cfg",
]
[features]
arrays = []
bindgen = ["zstd-sys/bindgen"]
debug = ["zstd-sys/debug"]
default = [
"legacy",
"arrays",
"zdict_builder",
]
doc-cfg = []
experimental = ["zstd-sys/experimental"]
fat-lto = ["zstd-sys/fat-lto"]
legacy = ["zstd-sys/legacy"]
no_asm = ["zstd-sys/no_asm"]
pkg-config = ["zstd-sys/pkg-config"]
seekable = ["zstd-sys/seekable"]
std = ["zstd-sys/std"]
thin = ["zstd-sys/thin"]
thin-lto = ["zstd-sys/thin-lto"]
zdict_builder = ["zstd-sys/zdict_builder"]
zstdmt = ["zstd-sys/zstdmt"]
[lib]
name = "zstd_safe"
path = "src/lib.rs"
[dependencies.zstd-sys]
version = "2.0.15"
default-features = false
[lints.rust]
non_upper_case_globals = "allow"
+45
View File
@@ -0,0 +1,45 @@
[package]
authors = ["Alexandre Bury <alexandre.bury@gmail.com>"]
name = "zstd-safe"
build = "build.rs"
version = "7.2.4"
description = "Safe low-level bindings for the zstd compression library."
keywords = ["zstd", "zstandard", "compression"]
categories = ["api-bindings", "compression"]
repository = "https://github.com/gyscos/zstd-rs"
license = "MIT OR Apache-2.0"
readme = "Readme.md"
edition = "2018"
rust-version = "1.64"
exclude = ["update_consts.sh"]
[package.metadata.docs.rs]
features = ["experimental", "arrays", "std", "zdict_builder", "doc-cfg"]
[dependencies]
zstd-sys = { path = "zstd-sys", version = "2.0.15", default-features = false }
[features]
default = ["legacy", "arrays", "zdict_builder"]
bindgen = ["zstd-sys/bindgen"]
debug = ["zstd-sys/debug"]
experimental = ["zstd-sys/experimental"]
legacy = ["zstd-sys/legacy"]
pkg-config = ["zstd-sys/pkg-config"]
std = ["zstd-sys/std"] # Implements WriteBuf for std types like Cursor and Vec.
zstdmt = ["zstd-sys/zstdmt"]
thin = ["zstd-sys/thin"]
arrays = []
no_asm = ["zstd-sys/no_asm"]
doc-cfg = []
zdict_builder = ["zstd-sys/zdict_builder"]
seekable = ["zstd-sys/seekable"]
# These two are for cross-language LTO.
# Will only work if `clang` is used to build the C library.
fat-lto = ["zstd-sys/fat-lto"]
thin-lto = ["zstd-sys/thin-lto"]
[lints.rust]
non_upper_case_globals = "allow"
+1
View File
@@ -0,0 +1 @@
MIT or Apache-2.0
+177
View File
@@ -0,0 +1,177 @@
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
+8
View File
@@ -0,0 +1,8 @@
The MIT License (MIT)
Copyright (c) 2016 Alexandre Bury
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.
+10
View File
@@ -0,0 +1,10 @@
# zstd-safe
This is a thin, no-std, safe abstraction built on top of the bindings from [zstd-sys].
It is close to a 1-for-1 mapping to the C functions, but uses rust types like slices instead of pointers and lengths.
For a more comfortable higher-level library (with `Read`/`Write` implementations), see [zstd-rs].
[zstd-rs]: https://github.com/gyscos/zstd-rs/tree/main/zstd-safe/zstd-sys
[zstd-rs]: https://github.com/gyscos/zstd-rs
+10
View File
@@ -0,0 +1,10 @@
fn main() {
// Force the `std` feature in some cases
let target_arch =
std::env::var("CARGO_CFG_TARGET_ARCH").unwrap_or_default();
let target_os = std::env::var("CARGO_CFG_TARGET_OS").unwrap_or_default();
if target_arch == "wasm32" || target_os == "hermit" {
println!("cargo:rustc-cfg=feature=\"std\"");
}
}
+14
View File
@@ -0,0 +1,14 @@
// This file has been generated by ./update_consts.sh
pub const BLOCKSIZELOG_MAX: u32 = zstd_sys::ZSTD_BLOCKSIZELOG_MAX;
pub const BLOCKSIZE_MAX: u32 = zstd_sys::ZSTD_BLOCKSIZE_MAX;
pub const CLEVEL_DEFAULT: CompressionLevel = zstd_sys::ZSTD_CLEVEL_DEFAULT as CompressionLevel;
pub const CONTENTSIZE_ERROR: u64 = zstd_sys::ZSTD_CONTENTSIZE_ERROR as u64;
pub const CONTENTSIZE_UNKNOWN: u64 = zstd_sys::ZSTD_CONTENTSIZE_UNKNOWN as u64;
pub const MAGIC_DICTIONARY: u32 = zstd_sys::ZSTD_MAGIC_DICTIONARY;
pub const MAGICNUMBER: u32 = zstd_sys::ZSTD_MAGICNUMBER;
pub const MAGIC_SKIPPABLE_MASK: u32 = zstd_sys::ZSTD_MAGIC_SKIPPABLE_MASK;
pub const MAGIC_SKIPPABLE_START: u32 = zstd_sys::ZSTD_MAGIC_SKIPPABLE_START;
pub const VERSION_MAJOR: u32 = zstd_sys::ZSTD_VERSION_MAJOR;
pub const VERSION_MINOR: u32 = zstd_sys::ZSTD_VERSION_MINOR;
pub const VERSION_NUMBER: u32 = zstd_sys::ZSTD_VERSION_NUMBER;
pub const VERSION_RELEASE: u32 = zstd_sys::ZSTD_VERSION_RELEASE;
@@ -0,0 +1,29 @@
// This file has been generated by ./update_consts.sh
pub const BLOCKSIZE_MAX_MIN: u32 = zstd_sys::ZSTD_BLOCKSIZE_MAX_MIN;
pub const BLOCKSPLITTER_LEVEL_MAX: u32 = zstd_sys::ZSTD_BLOCKSPLITTER_LEVEL_MAX;
pub const CHAINLOG_MAX_32: u32 = zstd_sys::ZSTD_CHAINLOG_MAX_32;
pub const CHAINLOG_MAX_64: u32 = zstd_sys::ZSTD_CHAINLOG_MAX_64;
pub const CHAINLOG_MIN: u32 = zstd_sys::ZSTD_CHAINLOG_MIN;
pub const FRAMEHEADERSIZE_MAX: u32 = zstd_sys::ZSTD_FRAMEHEADERSIZE_MAX;
pub const HASHLOG_MIN: u32 = zstd_sys::ZSTD_HASHLOG_MIN;
pub const LDM_BUCKETSIZELOG_MAX: u32 = zstd_sys::ZSTD_LDM_BUCKETSIZELOG_MAX;
pub const LDM_BUCKETSIZELOG_MIN: u32 = zstd_sys::ZSTD_LDM_BUCKETSIZELOG_MIN;
pub const LDM_HASHLOG_MIN: u32 = zstd_sys::ZSTD_LDM_HASHLOG_MIN;
pub const LDM_HASHRATELOG_MIN: u32 = zstd_sys::ZSTD_LDM_HASHRATELOG_MIN;
pub const LDM_MINMATCH_MAX: u32 = zstd_sys::ZSTD_LDM_MINMATCH_MAX;
pub const LDM_MINMATCH_MIN: u32 = zstd_sys::ZSTD_LDM_MINMATCH_MIN;
pub const MINMATCH_MAX: u32 = zstd_sys::ZSTD_MINMATCH_MAX;
pub const MINMATCH_MIN: u32 = zstd_sys::ZSTD_MINMATCH_MIN;
pub const OVERLAPLOG_MAX: u32 = zstd_sys::ZSTD_OVERLAPLOG_MAX;
pub const OVERLAPLOG_MIN: u32 = zstd_sys::ZSTD_OVERLAPLOG_MIN;
pub const SEARCHLOG_MIN: u32 = zstd_sys::ZSTD_SEARCHLOG_MIN;
pub const SKIPPABLEHEADERSIZE: u32 = zstd_sys::ZSTD_SKIPPABLEHEADERSIZE;
pub const SRCSIZEHINT_MIN: u32 = zstd_sys::ZSTD_SRCSIZEHINT_MIN;
pub const TARGETCBLOCKSIZE_MAX: u32 = zstd_sys::ZSTD_TARGETCBLOCKSIZE_MAX;
pub const TARGETCBLOCKSIZE_MIN: u32 = zstd_sys::ZSTD_TARGETCBLOCKSIZE_MIN;
pub const TARGETLENGTH_MAX: u32 = zstd_sys::ZSTD_TARGETLENGTH_MAX;
pub const TARGETLENGTH_MIN: u32 = zstd_sys::ZSTD_TARGETLENGTH_MIN;
pub const WINDOWLOG_LIMIT_DEFAULT: u32 = zstd_sys::ZSTD_WINDOWLOG_LIMIT_DEFAULT;
pub const WINDOWLOG_MAX_32: u32 = zstd_sys::ZSTD_WINDOWLOG_MAX_32;
pub const WINDOWLOG_MAX_64: u32 = zstd_sys::ZSTD_WINDOWLOG_MAX_64;
pub const WINDOWLOG_MIN: u32 = zstd_sys::ZSTD_WINDOWLOG_MIN;
@@ -0,0 +1,6 @@
// This file has been generated by ./update_consts.sh
pub const SEEKABLE_FRAMEINDEX_TOOLARGE: u64 = zstd_sys::ZSTD_SEEKABLE_FRAMEINDEX_TOOLARGE as u64;
pub const SEEKABLE_MAGICNUMBER: u32 = zstd_sys::ZSTD_SEEKABLE_MAGICNUMBER;
pub const SEEKABLE_MAX_FRAME_DECOMPRESSED_SIZE: u32 = zstd_sys::ZSTD_SEEKABLE_MAX_FRAME_DECOMPRESSED_SIZE;
pub const SEEKABLE_MAXFRAMES: u32 = zstd_sys::ZSTD_SEEKABLE_MAXFRAMES;
pub const seekTableFooterSize: u32 = zstd_sys::ZSTD_seekTableFooterSize;
File diff suppressed because it is too large Load Diff
+717
View File
@@ -0,0 +1,717 @@
//! The seekable format splits the compressed data into a series of "frames",
//! each compressed individually so that decompression of a section in the
//! middle of an archive only requires zstd to decompress at most a frame's
//! worth of extra data, instead of the entire archive.
use core::{marker::PhantomData, ptr::NonNull};
use crate::{
parse_code, ptr_mut, ptr_void, CompressionLevel, InBuffer, OutBuffer,
SafeResult, WriteBuf, SEEKABLE_FRAMEINDEX_TOOLARGE,
};
/// Indicates that the passed frame index is too large.
///
/// This happens when `frame_index > num_frames()`.
#[derive(Debug, PartialEq)]
pub struct FrameIndexTooLargeError;
impl core::fmt::Display for FrameIndexTooLargeError {
fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
f.write_str("Frame index too large")
}
}
/// Required to tracking streaming operation.
///
/// Streaming objects are reusable to avoid allocation and deallocation,
/// to start a new compression operation call `init()`.
pub struct SeekableCStream(NonNull<zstd_sys::ZSTD_seekable_CStream>);
unsafe impl Send for SeekableCStream {}
unsafe impl Sync for SeekableCStream {}
impl Default for SeekableCStream {
fn default() -> Self {
SeekableCStream::create()
}
}
impl SeekableCStream {
/// Tries to create a new `SeekableCStream`.
///
/// Returns `None` if zstd returns a NULL pointer - may happen if allocation fails.
pub fn try_create() -> Option<Self> {
// Safety: Just FFI
Some(SeekableCStream(NonNull::new(unsafe {
zstd_sys::ZSTD_seekable_createCStream()
})?))
}
/// Creates a new `SeekableCStream`.
///
/// # Panics
///
/// If zstd returns a NULL pointer.
pub fn create() -> Self {
Self::try_create()
.expect("zstd returned null pointer when creating new seekable compression stream")
}
/// Wraps the `ZSTD_seekable_initCStream()` function.
///
/// Call this to initialize a `SeekableCStream` object for a new compression operation.
/// - `max_frame_size` indicates the size at which to automatically start a new seekable
/// frame. `max_frame_size == 0` implies the default maximum size. Smaller frame sizes allow
/// faster decompression of small segments, since retrieving a single byte requires
/// decompression of the full frame where the byte belongs. In general, size the frames
/// to roughly correspond to the access granularity (when it's known). But small sizes
/// also reduce compression ratio. Avoid really tiny frame sizes (< 1 KB), that would
/// hurt compression ratio considerably.
/// - `checksum_flag` indicates whether or not the seek table should include frame
/// checksums on the uncompressed data for verification.
///
/// Returns a size hint for input to provide for compression, or an error code.
pub fn init(
&mut self,
compression_level: CompressionLevel,
checksum_flag: bool,
max_frame_size: u32,
) -> SafeResult {
// Safety: Just FFI
let code = unsafe {
zstd_sys::ZSTD_seekable_initCStream(
self.0.as_ptr(),
compression_level,
checksum_flag as i32,
max_frame_size,
)
};
parse_code(code)
}
/// Wraps the `ZSTD_seekable_compressStream()` function.
///
/// Call this repetitively to consume input stream. The function will automatically
/// update both `pos` fields. Note that it may not consume the entire input, in which
/// case `pos < size`, and it's up to the caller to present again remaining data.
///
/// Returns a size hint, preferred number of bytes to use as input for the next call
/// or an error code. Note that it's just a hint, to help latency a little, any other
/// value will work fine.
pub fn compress_stream<C: WriteBuf + ?Sized>(
&mut self,
output: &mut OutBuffer<'_, C>,
input: &mut InBuffer<'_>,
) -> SafeResult {
let mut output = output.wrap();
let mut input = input.wrap();
// Safety: Just FFI
let code = unsafe {
zstd_sys::ZSTD_seekable_compressStream(
self.0.as_ptr(),
ptr_mut(&mut output),
ptr_mut(&mut input),
)
};
parse_code(code)
}
/// Wraps the `ZSTD_seekable_endFrame()` function.
///
/// Call this any time to end the current frame and start a new one.
pub fn end_frame<C: WriteBuf + ?Sized>(
&mut self,
output: &mut OutBuffer<'_, C>,
) -> SafeResult {
let mut output = output.wrap();
// Safety: Just FFI
let code = unsafe {
zstd_sys::ZSTD_seekable_endFrame(
self.0.as_ptr(),
ptr_mut(&mut output),
)
};
parse_code(code)
}
/// Wraps the `ZSTD_seekable_endStream()` function.
///
/// This will end the current frame, and then write the seek table so that
/// decompressors can efficiently find compressed frames.
///
/// Returns a number > 0 if it was unable to flush all the necessary data to `output`.
/// In this case, it should be called again until all remaining data is flushed out and
/// 0 is returned.
pub fn end_stream<C: WriteBuf + ?Sized>(
&mut self,
output: &mut OutBuffer<'_, C>,
) -> SafeResult {
let mut output = output.wrap();
// Safety: Just FFI
let code = unsafe {
zstd_sys::ZSTD_seekable_endStream(
self.0.as_ptr(),
ptr_mut(&mut output),
)
};
parse_code(code)
}
}
impl Drop for SeekableCStream {
fn drop(&mut self) {
// Safety: Just FFI
unsafe {
zstd_sys::ZSTD_seekable_freeCStream(self.0.as_ptr());
}
}
}
/// Allows for the seek table to be constructed directly.
///
/// This table can then be appended to a file of concatenated frames. This allows the
/// frames to be compressed independently, even in parallel, and compiled together
/// afterward into a seekable archive.
pub struct FrameLog(NonNull<zstd_sys::ZSTD_frameLog>);
unsafe impl Send for FrameLog {}
unsafe impl Sync for FrameLog {}
impl FrameLog {
/// Tries to create a new `FrameLog`.
///
/// Returns `None` if zstd returns a NULL pointer - may happen if allocation fails.
pub fn try_create(checksum_flag: bool) -> Option<Self> {
Some(FrameLog(
// Safety: Just FFI
NonNull::new(unsafe {
zstd_sys::ZSTD_seekable_createFrameLog(checksum_flag as i32)
})?,
))
}
/// Creates a new `FrameLog`.
///
/// # Panics
///
/// If zstd returns a NULL pointer.
pub fn create(checksum_flag: bool) -> Self {
Self::try_create(checksum_flag)
.expect("Zstd returned null pointer when creating new frame log")
}
/// Needs to be called once for each frame in the archive.
///
/// If the `FrameLog` was created with `checksum_flag == false`, the `checksum` may be none
/// and any value assigned to it will be ignored. If the `FrameLog` was created with
/// `checksum_flag == true`, it should be the least significant 32 bits of the XXH64
/// hash of the uncompressed data.
pub fn log_frame(
&mut self,
compressed_size: u32,
decompressed_size: u32,
checksum: Option<u32>,
) -> SafeResult {
// Safety: Just FFI
let code = unsafe {
zstd_sys::ZSTD_seekable_logFrame(
self.0.as_ptr(),
compressed_size,
decompressed_size,
checksum.unwrap_or_default(),
)
};
parse_code(code)
}
/// Writes the seek table to `output`.
///
/// Returns 0 if the entire table was written. Otherwise, it will be equal to the number
/// of bytes left to write.
pub fn write_seek_table<C: WriteBuf + ?Sized>(
&mut self,
output: &mut OutBuffer<'_, C>,
) -> SafeResult {
let mut output = output.wrap();
// Safety: Just FFI
let code = unsafe {
zstd_sys::ZSTD_seekable_writeSeekTable(
self.0.as_ptr(),
ptr_mut(&mut output),
)
};
parse_code(code)
}
}
impl Drop for FrameLog {
fn drop(&mut self) {
// Safety: Just FFI
unsafe {
zstd_sys::ZSTD_seekable_freeFrameLog(self.0.as_ptr());
}
}
}
/// A seekable decompression object.
///
/// The lifetime references the potential buffer that holds the data of this seekable.
pub struct Seekable<'a>(NonNull<zstd_sys::ZSTD_seekable>, PhantomData<&'a ()>);
unsafe impl Send for Seekable<'_> {}
unsafe impl Sync for Seekable<'_> {}
impl Default for Seekable<'_> {
fn default() -> Self {
Seekable::create()
}
}
impl<'a> Seekable<'a> {
/// Tries to create a new `Seekable`.
///
/// Returns `None` if zstd returns a NULL pointer - may happen if allocation fails.
pub fn try_create() -> Option<Self> {
// Safety: Just FFI
Some(Seekable(
NonNull::new(unsafe { zstd_sys::ZSTD_seekable_create() })?,
PhantomData,
))
}
/// Creates a new `Seekable`.
///
/// # Panics
///
/// If zstd returns a NULL pointer.
pub fn create() -> Self {
Self::try_create()
.expect("Zstd returned null pointer when creating new seekable")
}
/// Initializes this `Seekable` with the the seek table provided in `src`.
///
/// The data contained in `src` should be the entire seekable file, including the seek table.
/// Consider using `init_advanced()`, if it not feasible to have the entire seekable file in
/// memory.
pub fn init_buff(&mut self, src: &'a [u8]) -> SafeResult {
// Safety: Just FFI
let code = unsafe {
zstd_sys::ZSTD_seekable_initBuff(
self.0.as_ptr(),
ptr_void(src),
src.len(),
)
};
parse_code(code)
}
/// Decompresses the length of `dst` at decompressed offset `offset`.
///
/// May have to decompress the entire prefix of the frame before the desired data if it has
/// not already processed this section. If this is called multiple times for a consecutive
/// range of data, it will efficiently retain the decompressor object and avoid
/// redecompressing frame prefixes.
///
/// Returns the number of bytes decompressed, or an error code.
pub fn decompress<C: WriteBuf + ?Sized>(
&mut self,
dst: &mut C,
offset: u64,
) -> SafeResult {
unsafe {
dst.write_from(|buffer, capacity| {
parse_code(zstd_sys::ZSTD_seekable_decompress(
self.0.as_ptr(),
buffer,
capacity,
offset,
))
})
}
}
/// Decompresses the frame with index `frame_index` into `dst`.
///
/// Returns an error if `frame_index` is larger than the value returned by `num_frames()`.
pub fn decompress_frame<C: WriteBuf + ?Sized>(
&mut self,
dst: &mut C,
frame_index: u32,
) -> SafeResult {
unsafe {
dst.write_from(|buffer, capacity| {
parse_code(zstd_sys::ZSTD_seekable_decompressFrame(
self.0.as_ptr(),
buffer,
capacity,
frame_index,
))
})
}
}
/// Get the number of frames of this seekable object.
///
/// Returns `0` if the seekable is not initialized.
pub fn num_frames(&self) -> u32 {
unsafe { zstd_sys::ZSTD_seekable_getNumFrames(self.0.as_ptr()) }
}
/// Get the offset of the compressed frame.
///
/// Returns an error if `frame_index` is out of range.
pub fn frame_compressed_offset(
&self,
frame_index: u32,
) -> Result<u64, FrameIndexTooLargeError> {
let offset = unsafe {
zstd_sys::ZSTD_seekable_getFrameCompressedOffset(
self.0.as_ptr(),
frame_index,
)
};
if offset == SEEKABLE_FRAMEINDEX_TOOLARGE {
return Err(FrameIndexTooLargeError);
}
Ok(offset)
}
/// Get the offset of the decompressed frame.
///
/// Returns an error if `frame_index` is out of range.
pub fn frame_decompressed_offset(
&self,
frame_index: u32,
) -> Result<u64, FrameIndexTooLargeError> {
let offset = unsafe {
zstd_sys::ZSTD_seekable_getFrameDecompressedOffset(
self.0.as_ptr(),
frame_index,
)
};
if offset == SEEKABLE_FRAMEINDEX_TOOLARGE {
return Err(FrameIndexTooLargeError);
}
Ok(offset)
}
/// Get the size of the compressed frame.
///
/// Returns an error if `frame_index` is out of range.
pub fn frame_compressed_size(&self, frame_index: u32) -> SafeResult {
let code = unsafe {
zstd_sys::ZSTD_seekable_getFrameCompressedSize(
self.0.as_ptr(),
frame_index,
)
};
parse_code(code)
}
/// Get the size of the decompressed frame.
///
/// Returns an error if `frame_index` is out of range.
pub fn frame_decompressed_size(&self, frame_index: u32) -> SafeResult {
let code = unsafe {
zstd_sys::ZSTD_seekable_getFrameDecompressedSize(
self.0.as_ptr(),
frame_index,
)
};
parse_code(code)
}
/// Get the frame at the given offset.
pub fn offset_to_frame_index(&self, offset: u64) -> u32 {
unsafe {
zstd_sys::ZSTD_seekable_offsetToFrameIndex(self.0.as_ptr(), offset)
}
}
}
impl<'a> Drop for Seekable<'a> {
fn drop(&mut self) {
// Safety: Just FFI
unsafe {
zstd_sys::ZSTD_seekable_free(self.0.as_ptr());
}
}
}
#[cfg(feature = "std")]
pub struct AdvancedSeekable<'a, F> {
inner: Seekable<'a>,
// We can't use Box<F> since it'd break rust aliasing rules when calling
// advanced_read/advanced_seek through the C code.
src: *mut F,
}
#[cfg(feature = "std")]
unsafe impl<F> Send for AdvancedSeekable<'_, F> where F: Send {}
#[cfg(feature = "std")]
unsafe impl<F> Sync for AdvancedSeekable<'_, F> where F: Sync {}
#[cfg(feature = "std")]
impl<'a, F> core::ops::Deref for AdvancedSeekable<'a, F> {
type Target = Seekable<'a>;
fn deref(&self) -> &Self::Target {
&self.inner
}
}
#[cfg(feature = "std")]
impl<'a, F> core::ops::DerefMut for AdvancedSeekable<'a, F> {
fn deref_mut(&mut self) -> &mut Self::Target {
&mut self.inner
}
}
#[cfg(feature = "std")]
impl<'a, F> Drop for AdvancedSeekable<'a, F> {
fn drop(&mut self) {
use std::boxed::Box;
// this drops the box
let _: Box<F> = unsafe { Box::from_raw(self.src) };
}
}
impl<'a> Seekable<'a> {
/// A general API allowing the client to provide its own read and seek implementations.
///
/// Initializes this seekable without having the complete compressed data in memory,
/// but seeks and reads `src` as required. Use this function if you are looking for
/// an alternative to the `ZSTD_seekable_initFile()` function.
#[cfg(feature = "std")]
#[cfg_attr(feature = "doc-cfg", doc(cfg(feature = "std")))]
pub fn init_advanced<F>(
self,
src: std::boxed::Box<F>,
) -> Result<AdvancedSeekable<'a, F>, crate::ErrorCode>
where
F: std::io::Read + std::io::Seek,
{
let opaque = std::boxed::Box::into_raw(src) as *mut F;
let custom_file = zstd_sys::ZSTD_seekable_customFile {
opaque: opaque as *mut core::ffi::c_void,
read: Some(advanced_read::<F>),
seek: Some(advanced_seek::<F>),
};
// Safety: Just FFI
let code = unsafe {
zstd_sys::ZSTD_seekable_initAdvanced(self.0.as_ptr(), custom_file)
};
if crate::is_error(code) {
return Err(code);
}
Ok(AdvancedSeekable {
inner: self,
src: opaque,
})
}
}
/// Seeks the read head to `offset` from `origin`, where origin is either `SEEK_SET`
/// (beginning of file), `SEEK_CUR` (current position) or `SEEK_END` (end of file),
/// as defined in `stdio.h`.
///
/// Returns a non-negative value in case of success, and a negative value in case of failure.
#[cfg(feature = "std")]
unsafe extern "C" fn advanced_seek<S: std::io::Seek>(
opaque: *mut core::ffi::c_void,
offset: ::core::ffi::c_longlong,
origin: ::core::ffi::c_int,
) -> ::core::ffi::c_int {
use core::convert::TryFrom;
use std::io::SeekFrom;
// as defined in stdio.h
const SEEK_SET: i32 = 0;
const SEEK_CUR: i32 = 1;
const SEEK_END: i32 = 2;
// Safety: The trait boundaries in `init_advanced()` ensure that `opaque` points to an S
let seeker: &mut S = std::mem::transmute(opaque);
let pos = match origin {
SEEK_SET => {
let Ok(offset) = u64::try_from(offset) else {
return -1;
};
SeekFrom::Start(offset)
}
SEEK_CUR => SeekFrom::Current(offset),
SEEK_END => SeekFrom::End(offset),
// not possible
_ => return -1,
};
if seeker.seek(pos).is_err() {
return -1;
}
0
}
/// Reads exactly `n` bytes into `buffer`.
///
/// Returns a non-negative value in case of success, and a negative value in case of failure.
#[cfg(feature = "std")]
unsafe extern "C" fn advanced_read<R: std::io::Read>(
opaque: *mut core::ffi::c_void,
buffer: *mut core::ffi::c_void,
n: usize,
) -> ::core::ffi::c_int {
// Safety: The trait boundaries in `init_advanced()` ensure that `opaque` points to a R
let reader: &mut R = std::mem::transmute(opaque);
// Safety: zstd ensures the buffer is allocated and safe to use
let mut buf = std::slice::from_raw_parts_mut(buffer as *mut u8, n);
if reader.read_exact(&mut buf).is_err() {
return -1;
}
0
}
/// Indicates that the seek table could not be created.
#[derive(Debug, PartialEq)]
pub struct SeekTableCreateError;
impl core::fmt::Display for SeekTableCreateError {
fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
f.write_str("Zstd returned null pointer when creating new seektable from seekable")
}
}
pub struct SeekTable(NonNull<zstd_sys::ZSTD_seekTable>);
unsafe impl Send for SeekTable {}
unsafe impl Sync for SeekTable {}
impl SeekTable {
/// Try to create a `SeekTable` from a `Seekable`.
///
/// Memory constrained use cases that manage multiple archives benefit from retaining
/// multiple archive seek tables without retaining a `Seekable` instance for each.
pub fn try_from_seekable<'a>(
value: &Seekable<'a>,
) -> Result<Self, SeekTableCreateError> {
// Safety: Just FFI
let ptr = unsafe {
zstd_sys::ZSTD_seekTable_create_fromSeekable(value.0.as_ptr())
};
let ptr = NonNull::new(ptr).ok_or(SeekTableCreateError)?;
Ok(Self(ptr))
}
/// Get the number of frames of the underlying seekable object.
pub fn num_frames(&self) -> u32 {
// Safety: Just FFI
unsafe { zstd_sys::ZSTD_seekTable_getNumFrames(self.0.as_ptr()) }
}
/// Get the offset of the compressed frame.
///
/// Returns an error if `frame_index` is out of range.
pub fn frame_compressed_offset(
&self,
frame_index: u32,
) -> Result<u64, FrameIndexTooLargeError> {
// Safety: Just FFI
let offset = unsafe {
zstd_sys::ZSTD_seekTable_getFrameCompressedOffset(
self.0.as_ptr(),
frame_index,
)
};
if offset == SEEKABLE_FRAMEINDEX_TOOLARGE {
return Err(FrameIndexTooLargeError);
}
Ok(offset)
}
/// Get the offset of the decompressed frame.
///
/// Returns an error if `frame_index` is out of range.
pub fn frame_decompressed_offset(
&self,
frame_index: u32,
) -> Result<u64, FrameIndexTooLargeError> {
// Safety: Just FFI
let offset = unsafe {
zstd_sys::ZSTD_seekTable_getFrameDecompressedOffset(
self.0.as_ptr(),
frame_index,
)
};
if offset == SEEKABLE_FRAMEINDEX_TOOLARGE {
return Err(FrameIndexTooLargeError);
}
Ok(offset)
}
/// Get the size of the compressed frame.
///
/// Returns an error if `frame_index` is out of range.
pub fn frame_compressed_size(&self, frame_index: u32) -> SafeResult {
// Safety: Just FFI
let code = unsafe {
zstd_sys::ZSTD_seekTable_getFrameCompressedSize(
self.0.as_ptr(),
frame_index,
)
};
parse_code(code)
}
/// Get the size of the decompressed frame.
///
/// Returns an error if `frame_index` is out of range.
pub fn frame_decompressed_size(&self, frame_index: u32) -> SafeResult {
// Safety: Just FFI
let code = unsafe {
zstd_sys::ZSTD_seekTable_getFrameDecompressedSize(
self.0.as_ptr(),
frame_index,
)
};
parse_code(code)
}
/// Get the frame at the given offset.
pub fn offset_to_frame_index(&self, offset: u64) -> u32 {
// Safety: Just FFI
unsafe {
zstd_sys::ZSTD_seekTable_offsetToFrameIndex(
self.0.as_ptr(),
offset,
)
}
}
}
impl Drop for SeekTable {
fn drop(&mut self) {
// Safety: Just FFI
unsafe {
zstd_sys::ZSTD_seekTable_free(self.0.as_ptr());
}
}
}
+332
View File
@@ -0,0 +1,332 @@
extern crate std;
use crate as zstd_safe;
use self::std::vec::Vec;
const INPUT: &[u8] = b"Rust is a multi-paradigm system programming language focused on safety, especially safe concurrency. Rust is syntactically similar to C++, but is designed to provide better memory safety while maintaining high performance.";
const LONG_CONTENT: &str = include_str!("lib.rs");
#[cfg(feature = "std")]
#[test]
fn test_writebuf() {
use zstd_safe::WriteBuf;
let mut data = Vec::with_capacity(10);
unsafe {
data.write_from(|ptr, n| {
assert!(n >= 4);
let ptr = ptr as *mut u8;
ptr.write(0);
ptr.add(1).write(1);
ptr.add(2).write(2);
ptr.add(3).write(3);
Ok(4)
})
}
.unwrap();
assert_eq!(data.as_slice(), &[0, 1, 2, 3]);
let mut cursor = std::io::Cursor::new(&mut data);
// Here we use a position larger than the actual data.
// So expect the data to be zero-filled.
cursor.set_position(6);
unsafe {
cursor.write_from(|ptr, n| {
assert!(n >= 4);
let ptr = ptr as *mut u8;
ptr.write(4);
ptr.add(1).write(5);
ptr.add(2).write(6);
ptr.add(3).write(7);
Ok(4)
})
}
.unwrap();
assert_eq!(data.as_slice(), &[0, 1, 2, 3, 0, 0, 4, 5, 6, 7]);
}
#[cfg(feature = "std")]
#[test]
fn test_simple_cycle() {
let mut buffer = std::vec![0u8; 256];
let written = zstd_safe::compress(&mut buffer, INPUT, 3).unwrap();
let compressed = &buffer[..written];
let mut buffer = std::vec![0u8; 256];
let written = zstd_safe::decompress(&mut buffer, compressed).unwrap();
let decompressed = &buffer[..written];
assert_eq!(INPUT, decompressed);
}
#[test]
fn test_cctx_cycle() {
let mut buffer = std::vec![0u8; 256];
let mut cctx = zstd_safe::CCtx::default();
let written = cctx.compress(&mut buffer[..], INPUT, 1).unwrap();
let compressed = &buffer[..written];
let mut dctx = zstd_safe::DCtx::default();
let mut buffer = std::vec![0u8; 256];
let written = dctx.decompress(&mut buffer[..], compressed).unwrap();
let decompressed = &buffer[..written];
assert_eq!(INPUT, decompressed);
}
#[test]
fn test_dictionary() {
// Prepare some content to train the dictionary.
let bytes = LONG_CONTENT.as_bytes();
let line_sizes: Vec<usize> =
LONG_CONTENT.lines().map(|line| line.len() + 1).collect();
// Train the dictionary
let mut dict_buffer = std::vec![0u8; 100_000];
let written =
zstd_safe::train_from_buffer(&mut dict_buffer[..], bytes, &line_sizes)
.unwrap();
let dict_buffer = &dict_buffer[..written];
// Create pre-hashed dictionaries for (de)compression
let cdict = zstd_safe::create_cdict(dict_buffer, 3);
let ddict = zstd_safe::create_ddict(dict_buffer);
// Compress data
let mut cctx = zstd_safe::CCtx::default();
cctx.ref_cdict(&cdict).unwrap();
let mut buffer = std::vec![0u8; 1024 * 1024];
// First, try to compress without a dict
let big_written = zstd_safe::compress(&mut buffer[..], bytes, 3).unwrap();
let written = cctx
.compress2(&mut buffer[..], bytes)
.map_err(zstd_safe::get_error_name)
.unwrap();
assert!(big_written > written);
let compressed = &buffer[..written];
// Decompress data
let mut dctx = zstd_safe::DCtx::default();
dctx.ref_ddict(&ddict).unwrap();
let mut buffer = std::vec![0u8; 1024 * 1024];
let written = dctx
.decompress(&mut buffer[..], compressed)
.map_err(zstd_safe::get_error_name)
.unwrap();
let decompressed = &buffer[..written];
// Profit!
assert_eq!(bytes, decompressed);
}
#[test]
fn test_checksum() {
let mut buffer = std::vec![0u8; 256];
let mut cctx = zstd_safe::CCtx::default();
cctx.set_parameter(zstd_safe::CParameter::ChecksumFlag(true))
.unwrap();
let written = cctx.compress2(&mut buffer[..], INPUT).unwrap();
let compressed = &mut buffer[..written];
let mut dctx = zstd_safe::DCtx::default();
let mut buffer = std::vec![0u8; 1024*1024];
let written = dctx
.decompress(&mut buffer[..], compressed)
.map_err(zstd_safe::get_error_name)
.unwrap();
let decompressed = &buffer[..written];
assert_eq!(INPUT, decompressed);
// Now try again with some corruption
// TODO: Find a mutation that _wouldn't_ be detected without checksums.
// (Most naive changes already trigger a "corrupt block" error.)
if let Some(last) = compressed.last_mut() {
*last = last.saturating_sub(1);
}
let err = dctx
.decompress(&mut buffer[..], compressed)
.map_err(zstd_safe::get_error_name)
.err()
.unwrap();
// The error message will complain about the checksum.
assert!(err.contains("checksum"));
}
#[cfg(all(feature = "experimental", feature = "std"))]
#[test]
fn test_upper_bound() {
let mut buffer = std::vec![0u8; 256];
assert!(zstd_safe::decompress_bound(&buffer).is_err());
let written = zstd_safe::compress(&mut buffer, INPUT, 3).unwrap();
let compressed = &buffer[..written];
assert_eq!(
zstd_safe::decompress_bound(&compressed),
Ok(INPUT.len() as u64)
);
}
#[cfg(feature = "seekable")]
#[test]
fn test_seekable_cycle() {
let seekable_archive = new_seekable_archive(INPUT);
let mut seekable = crate::seekable::Seekable::create();
seekable
.init_buff(&seekable_archive)
.map_err(zstd_safe::get_error_name)
.unwrap();
decompress_seekable(&mut seekable);
// Check that the archive can also be decompressed by a regular function
let mut buffer = std::vec![0u8; 256];
let written = zstd_safe::decompress(&mut buffer[..], &seekable_archive)
.map_err(zstd_safe::get_error_name)
.unwrap();
let decompressed = &buffer[..written];
assert_eq!(INPUT, decompressed);
// Trigger FrameIndexTooLargeError
let frame_index = seekable.num_frames() + 1;
assert_eq!(
seekable.frame_compressed_offset(frame_index).unwrap_err(),
crate::seekable::FrameIndexTooLargeError
);
}
#[cfg(feature = "seekable")]
#[test]
fn test_seekable_seek_table() {
use crate::seekable::{FrameIndexTooLargeError, SeekTable, Seekable};
let seekable_archive = new_seekable_archive(INPUT);
let mut seekable = Seekable::create();
// Assert that creating a SeekTable from an uninitialized seekable errors.
// This led to segfaults with zstd versions prior v1.5.7
assert!(SeekTable::try_from_seekable(&seekable).is_err());
seekable
.init_buff(&seekable_archive)
.map_err(zstd_safe::get_error_name)
.unwrap();
// Try to create a seek table from the seekable
let seek_table =
{ SeekTable::try_from_seekable(&seekable).unwrap() };
// Seekable and seek table should return the same results
assert_eq!(seekable.num_frames(), seek_table.num_frames());
assert_eq!(
seekable.frame_compressed_offset(2).unwrap(),
seek_table.frame_compressed_offset(2).unwrap()
);
assert_eq!(
seekable.frame_decompressed_offset(2).unwrap(),
seek_table.frame_decompressed_offset(2).unwrap()
);
assert_eq!(
seekable.frame_compressed_size(2).unwrap(),
seek_table.frame_compressed_size(2).unwrap()
);
assert_eq!(
seekable.frame_decompressed_size(2).unwrap(),
seek_table.frame_decompressed_size(2).unwrap()
);
// Trigger FrameIndexTooLargeError
let frame_index = seekable.num_frames() + 1;
assert_eq!(
seek_table.frame_compressed_offset(frame_index).unwrap_err(),
FrameIndexTooLargeError
);
}
#[cfg(all(feature = "std", feature = "seekable"))]
#[test]
fn test_seekable_advanced_cycle() {
use crate::seekable::Seekable;
use std::{boxed::Box, io::Cursor};
// Wrap the archive in a cursor that implements Read and Seek,
// a file would also work
let seekable_archive = Cursor::new(new_seekable_archive(INPUT));
let mut seekable = Seekable::create()
.init_advanced(Box::new(seekable_archive))
.map_err(zstd_safe::get_error_name)
.unwrap();
decompress_seekable(&mut seekable);
}
#[cfg(feature = "seekable")]
fn new_seekable_archive(input: &[u8]) -> Vec<u8> {
use crate::{seekable::SeekableCStream, InBuffer, OutBuffer};
// Make sure the buffer is big enough
// The buffer needs to be bigger as the uncompressed data here as the seekable archive has
// more meta data than actual compressed data because the input is really small and we use
// a max_frame_size of 64, which is way to small for real-world usages.
let mut buffer = std::vec![0u8; 512];
let mut cstream = SeekableCStream::create();
cstream
.init(3, true, 64)
.map_err(zstd_safe::get_error_name)
.unwrap();
let mut in_buffer = InBuffer::around(input);
let mut out_buffer = OutBuffer::around(&mut buffer[..]);
// This could get stuck if the buffer is too small
while in_buffer.pos() < in_buffer.src.len() {
cstream
.compress_stream(&mut out_buffer, &mut in_buffer)
.map_err(zstd_safe::get_error_name)
.unwrap();
}
// Make sure everything is flushed to out_buffer
loop {
if cstream
.end_stream(&mut out_buffer)
.map_err(zstd_safe::get_error_name)
.unwrap()
== 0
{
break;
}
}
Vec::from(out_buffer.as_slice())
}
#[cfg(feature = "seekable")]
fn decompress_seekable(seekable: &mut crate::seekable::Seekable<'_>) {
// Make the buffer as big as max_frame_size so it can hold a complete frame
let mut buffer = std::vec![0u8; 64];
// Decompress only the first frame
let written = seekable
.decompress(&mut buffer[..], 0)
.map_err(zstd_safe::get_error_name)
.unwrap();
let decompressed = &buffer[..written];
assert!(INPUT.starts_with(decompressed));
assert_eq!(decompressed.len(), 64);
// Make the buffer big enough to hold the complete input
let mut buffer = std::vec![0u8; 256];
// Decompress everything
let written = seekable
.decompress(&mut buffer[..], 0)
.map_err(zstd_safe::get_error_name)
.unwrap();
let decompressed = &buffer[..written];
assert_eq!(INPUT, decompressed);
}