13 Commits

23 changed files with 711 additions and 329 deletions

247
Cargo.lock generated
View File

@@ -36,34 +36,19 @@ dependencies = [
"sacabase", "sacabase",
] ]
[[package]]
name = "cfg-if"
version = "0.1.10"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "4785bdd1c96b2a846b2bd7cc02e86b6b3dbf14e7e53446c4f54c92a361040822"
[[package]] [[package]]
name = "cfg-if" name = "cfg-if"
version = "1.0.0" version = "1.0.0"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "baf1de4339761588bc0619e3cbc0120ee582ebb74b53b4efbf79117bd2da40fd" checksum = "baf1de4339761588bc0619e3cbc0120ee582ebb74b53b4efbf79117bd2da40fd"
[[package]]
name = "cloudabi"
version = "0.0.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "ddfc5b9aa5d4507acaf872de71051dfd0e309860e88966e1051e462a077aac4f"
dependencies = [
"bitflags",
]
[[package]] [[package]]
name = "crossbeam-channel" name = "crossbeam-channel"
version = "0.5.1" version = "0.5.1"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "06ed27e177f16d65f0f0c22a213e17c696ace5dd64b14258b52f9417ccb52db4" checksum = "06ed27e177f16d65f0f0c22a213e17c696ace5dd64b14258b52f9417ccb52db4"
dependencies = [ dependencies = [
"cfg-if 1.0.0", "cfg-if",
"crossbeam-utils", "crossbeam-utils",
] ]
@@ -73,26 +58,10 @@ version = "0.8.5"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "d82cfc11ce7f2c3faef78d8a684447b40d503d9681acebed6cb728d45940c4db" checksum = "d82cfc11ce7f2c3faef78d8a684447b40d503d9681acebed6cb728d45940c4db"
dependencies = [ dependencies = [
"cfg-if 1.0.0", "cfg-if",
"lazy_static", "lazy_static",
] ]
[[package]]
name = "crossterm"
version = "0.15.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "207a948d1b4ff59e5aec9bb9426cc4fd3d17b719e5c7b74e27f0a60c4cc2d095"
dependencies = [
"bitflags",
"crossterm_winapi 0.6.2",
"lazy_static",
"libc",
"mio 0.6.23",
"parking_lot 0.10.2",
"signal-hook 0.1.17",
"winapi 0.3.9",
]
[[package]] [[package]]
name = "crossterm" name = "crossterm"
version = "0.25.0" version = "0.25.0"
@@ -100,22 +69,13 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "e64e6c0fbe2c17357405f7c758c1ef960fce08bdfb2c03d88d2a18d7e09c4b67" checksum = "e64e6c0fbe2c17357405f7c758c1ef960fce08bdfb2c03d88d2a18d7e09c4b67"
dependencies = [ dependencies = [
"bitflags", "bitflags",
"crossterm_winapi 0.9.0", "crossterm_winapi",
"libc", "libc",
"mio 0.8.4", "mio",
"parking_lot 0.12.1", "parking_lot",
"signal-hook 0.3.14", "signal-hook",
"signal-hook-mio", "signal-hook-mio",
"winapi 0.3.9", "winapi",
]
[[package]]
name = "crossterm_winapi"
version = "0.6.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "c2265c3f8e080075d9b6417aa72293fc71662f34b4af2612d8d1b074d29510db"
dependencies = [
"winapi 0.3.9",
] ]
[[package]] [[package]]
@@ -124,42 +84,7 @@ version = "0.9.0"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "2ae1b35a484aa10e07fe0638d02301c5ad24de82d310ccbd2f3693da5f09bf1c" checksum = "2ae1b35a484aa10e07fe0638d02301c5ad24de82d310ccbd2f3693da5f09bf1c"
dependencies = [ dependencies = [
"winapi 0.3.9", "winapi",
]
[[package]]
name = "fuchsia-zircon"
version = "0.3.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "2e9763c69ebaae630ba35f74888db465e49e259ba1bc0eda7d06f4a067615d82"
dependencies = [
"bitflags",
"fuchsia-zircon-sys",
]
[[package]]
name = "fuchsia-zircon-sys"
version = "0.3.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "3dcaa9ae7725d12cdb85b3ad99a434db70b468c09ded17e012d86b5c1010f7a7"
[[package]]
name = "iovec"
version = "0.1.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "b2b3ea6ff95e175473f8ffe6a7eb7c00d054240321b84c57051175fe3c1e075e"
dependencies = [
"libc",
]
[[package]]
name = "kernel32-sys"
version = "0.2.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "7507624b29483431c0ba2d82aece8ca6cdba9382bff4ddd0f7490560c056098d"
dependencies = [
"winapi 0.2.8",
"winapi-build",
] ]
[[package]] [[package]]
@@ -180,15 +105,6 @@ version = "0.2.135"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "68783febc7782c6c5cb401fbda4de5a9898be1762314da0bb2c10ced61f18b0c" checksum = "68783febc7782c6c5cb401fbda4de5a9898be1762314da0bb2c10ced61f18b0c"
[[package]]
name = "lock_api"
version = "0.3.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "c4da24a77a3d8a6d4862d95f72e6fdb9c09a643ecdb402d754004a557f2bec75"
dependencies = [
"scopeguard",
]
[[package]] [[package]]
name = "lock_api" name = "lock_api"
version = "0.4.9" version = "0.4.9"
@@ -205,26 +121,7 @@ version = "0.4.17"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "abb12e687cfb44aa40f41fc3978ef76448f9b6038cad6aef4259d3c095a2382e" checksum = "abb12e687cfb44aa40f41fc3978ef76448f9b6038cad6aef4259d3c095a2382e"
dependencies = [ dependencies = [
"cfg-if 1.0.0", "cfg-if",
]
[[package]]
name = "mio"
version = "0.6.23"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "4afd66f5b91bf2a3bc13fad0e21caedac168ca4c707504e75585648ae80e4cc4"
dependencies = [
"cfg-if 0.1.10",
"fuchsia-zircon",
"fuchsia-zircon-sys",
"iovec",
"kernel32-sys",
"libc",
"log",
"miow",
"net2",
"slab",
"winapi 0.2.8",
] ]
[[package]] [[package]]
@@ -239,29 +136,6 @@ dependencies = [
"windows-sys 0.36.1", "windows-sys 0.36.1",
] ]
[[package]]
name = "miow"
version = "0.2.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "ebd808424166322d4a38da87083bfddd3ac4c131334ed55856112eb06d46944d"
dependencies = [
"kernel32-sys",
"net2",
"winapi 0.2.8",
"ws2_32-sys",
]
[[package]]
name = "net2"
version = "0.2.38"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "74d0df99cfcd2530b2e694f6e17e7f37b8e26bb23983ac530c0c97408837c631"
dependencies = [
"cfg-if 0.1.10",
"libc",
"winapi 0.3.9",
]
[[package]] [[package]]
name = "num-traits" name = "num-traits"
version = "0.2.14" version = "0.2.14"
@@ -271,38 +145,14 @@ dependencies = [
"autocfg", "autocfg",
] ]
[[package]]
name = "parking_lot"
version = "0.10.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "d3a704eb390aafdc107b0e392f56a82b668e3a71366993b5340f5833fd62505e"
dependencies = [
"lock_api 0.3.4",
"parking_lot_core 0.7.2",
]
[[package]] [[package]]
name = "parking_lot" name = "parking_lot"
version = "0.12.1" version = "0.12.1"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "3742b2c103b9f06bc9fff0a37ff4912935851bee6d36f3c02bcc755bcfec228f" checksum = "3742b2c103b9f06bc9fff0a37ff4912935851bee6d36f3c02bcc755bcfec228f"
dependencies = [ dependencies = [
"lock_api 0.4.9", "lock_api",
"parking_lot_core 0.9.4", "parking_lot_core",
]
[[package]]
name = "parking_lot_core"
version = "0.7.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "d58c7c768d4ba344e3e8d72518ac13e259d7c7ade24167003b8488e10b6740a3"
dependencies = [
"cfg-if 0.1.10",
"cloudabi",
"libc",
"redox_syscall 0.1.57",
"smallvec",
"winapi 0.3.9",
] ]
[[package]] [[package]]
@@ -311,9 +161,9 @@ version = "0.9.4"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "4dc9e0dc2adc1c69d09143aff38d3d30c5c3f0df0dad82e6d25547af174ebec0" checksum = "4dc9e0dc2adc1c69d09143aff38d3d30c5c3f0df0dad82e6d25547af174ebec0"
dependencies = [ dependencies = [
"cfg-if 1.0.0", "cfg-if",
"libc", "libc",
"redox_syscall 0.2.16", "redox_syscall",
"smallvec", "smallvec",
"windows-sys 0.42.0", "windows-sys 0.42.0",
] ]
@@ -327,7 +177,7 @@ dependencies = [
"crossbeam-channel", "crossbeam-channel",
"libc", "libc",
"time", "time",
"winapi 0.3.9", "winapi",
] ]
[[package]] [[package]]
@@ -348,12 +198,6 @@ dependencies = [
"proc-macro2", "proc-macro2",
] ]
[[package]]
name = "redox_syscall"
version = "0.1.57"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "41cc0f7e4d5d4544e8861606a285bb08d3e70712ccc7d2b84d7c0ccfaf4b05ce"
[[package]] [[package]]
name = "redox_syscall" name = "redox_syscall"
version = "0.2.16" version = "0.2.16"
@@ -378,17 +222,6 @@ version = "1.1.0"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "d29ab0c6d3fc0ee92fe66e2d99f700eab17a8d57d1c1d3b748380fb20baa78cd" checksum = "d29ab0c6d3fc0ee92fe66e2d99f700eab17a8d57d1c1d3b748380fb20baa78cd"
[[package]]
name = "signal-hook"
version = "0.1.17"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "7e31d442c16f047a671b5a71e2161d6e68814012b7f5379d269ebd915fac2729"
dependencies = [
"libc",
"mio 0.6.23",
"signal-hook-registry",
]
[[package]] [[package]]
name = "signal-hook" name = "signal-hook"
version = "0.3.14" version = "0.3.14"
@@ -406,8 +239,8 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "29ad2e15f37ec9a6cc544097b78a1ec90001e9f71b81338ca39f430adaca99af" checksum = "29ad2e15f37ec9a6cc544097b78a1ec90001e9f71b81338ca39f430adaca99af"
dependencies = [ dependencies = [
"libc", "libc",
"mio 0.8.4", "mio",
"signal-hook 0.3.14", "signal-hook",
] ]
[[package]] [[package]]
@@ -419,15 +252,6 @@ dependencies = [
"libc", "libc",
] ]
[[package]]
name = "slab"
version = "0.4.7"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "4614a76b2a8be0058caa9dbbaf66d988527d86d003c11a94fbd335d7661edcef"
dependencies = [
"autocfg",
]
[[package]] [[package]]
name = "smallvec" name = "smallvec"
version = "1.10.0" version = "1.10.0"
@@ -445,16 +269,6 @@ dependencies = [
"unicode-ident", "unicode-ident",
] ]
[[package]]
name = "terminal"
version = "0.2.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "9cd146db3fbe90911d0bb5498a393abda0af71a2c11e287ecb9ae30cf5d43667"
dependencies = [
"bitflags",
"crossterm 0.15.0",
]
[[package]] [[package]]
name = "thiserror" name = "thiserror"
version = "1.0.36" version = "1.0.36"
@@ -483,7 +297,7 @@ checksum = "6db9e6914ab8b1ae1c260a4ae7a49b6c5611b40328a735b21862567685e73255"
dependencies = [ dependencies = [
"libc", "libc",
"wasi 0.10.0+wasi-snapshot-preview1", "wasi 0.10.0+wasi-snapshot-preview1",
"winapi 0.3.9", "winapi",
] ]
[[package]] [[package]]
@@ -494,14 +308,13 @@ checksum = "dcc811dc4066ac62f84f11307873c4850cb653bfa9b1719cee2bd2204a4bc5dd"
[[package]] [[package]]
name = "upkr" name = "upkr"
version = "0.2.0" version = "0.2.2"
dependencies = [ dependencies = [
"anyhow", "anyhow",
"cdivsufsort", "cdivsufsort",
"crossterm 0.25.0", "crossterm",
"lexopt", "lexopt",
"pbr", "pbr",
"terminal",
"thiserror", "thiserror",
] ]
@@ -517,12 +330,6 @@ version = "0.11.0+wasi-snapshot-preview1"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "9c8d87e72b64a3b4db28d11ce29237c246188f4f51057d65a7eab63b7987e423" checksum = "9c8d87e72b64a3b4db28d11ce29237c246188f4f51057d65a7eab63b7987e423"
[[package]]
name = "winapi"
version = "0.2.8"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "167dc9d6949a9b857f3451275e911c3f44255842c1f7a76f33c55103a909087a"
[[package]] [[package]]
name = "winapi" name = "winapi"
version = "0.3.9" version = "0.3.9"
@@ -533,12 +340,6 @@ dependencies = [
"winapi-x86_64-pc-windows-gnu", "winapi-x86_64-pc-windows-gnu",
] ]
[[package]]
name = "winapi-build"
version = "0.1.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "2d315eee3b34aca4797b2da6b13ed88266e6d612562a0c46390af8299fc699bc"
[[package]] [[package]]
name = "winapi-i686-pc-windows-gnu" name = "winapi-i686-pc-windows-gnu"
version = "0.4.0" version = "0.4.0"
@@ -650,13 +451,3 @@ name = "windows_x86_64_msvc"
version = "0.42.0" version = "0.42.0"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "f40009d85759725a34da6d89a94e63d7bdc50a862acf0dbc7c8e488f1edcb6f5" checksum = "f40009d85759725a34da6d89a94e63d7bdc50a862acf0dbc7c8e488f1edcb6f5"
[[package]]
name = "ws2_32-sys"
version = "0.2.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "d59cefebd0c892fa2dd6de581e937301d8552cb44489cdff035c6187cb63fa5e"
dependencies = [
"winapi 0.2.8",
"winapi-build",
]

View File

@@ -1,16 +1,18 @@
[package] [package]
name = "upkr" name = "upkr"
version = "0.2.0" version = "0.2.2"
edition = "2021" edition = "2021"
[profile.release] [profile.release]
strip = "debuginfo" strip = "debuginfo"
[features]
terminal = ["crossterm", "pbr"]
[dependencies] [dependencies]
cdivsufsort = "2" cdivsufsort = "2"
lexopt = "0.2.1" lexopt = "0.2.1"
anyhow = "1" anyhow = "1"
thiserror = "1.0.36" thiserror = "1.0.36"
pbr = "1" pbr = { version = "1", optional = true }
crossterm = { version = "0.25.0", default-features = false } crossterm = { version = "0.25.0", default-features = false, optional = true }
terminal = { version = "0.2.1", default-features = false, features = ["crossterm-backend"] }

View File

@@ -22,6 +22,12 @@ c_unpacker and asm_unpackers unpack the default upkr compressed format. The z80_
is based on some variations to the compressed format. (Use `upkr --z80` to select those variations.) is based on some variations to the compressed format. (Use `upkr --z80` to select those variations.)
The 16 bit dos unpacker also uses some variations. (`upkr --x86`) The 16 bit dos unpacker also uses some variations. (`upkr --x86`)
### More unpackers outside this repository
* [Atari Lynx](https://github.com/42Bastian/new_bll/blob/master/demos/depacker/unupkr.asm)
* [Atari Jaguar](https://github.com/42Bastian/new_bjl/blob/main/exp/depacker/unupkr.js)
* [8080, R800](https://github.com/ivagorRetrocomp/DeUpkr)
## Usage ## Usage
``` ```
@@ -32,10 +38,17 @@ The 16 bit dos unpacker also uses some variations. (`upkr --x86`)
-l, --level N compression level 0-9 -l, --level N compression level 0-9
-0, ..., -9 short form for setting compression level -0, ..., -9 short form for setting compression level
-u, --unpack unpack infile -d, --decompress decompress infile
--heatmap calculate heatmap from compressed file --heatmap calculate heatmap from compressed file
--raw-cost report raw cost of literals in heatmap
(the cost of literals is spread across all matches
that reference the literal by default.)
--hexdump print heatmap as colored hexdump
--margin calculate margin for overlapped unpacking of a packed file --margin calculate margin for overlapped unpacking of a packed file
When no infile is given, or the infile is '-', read from stdin.
When no outfile is given and reading from stdin, or when outfile is '-', write to stdout.
Config presets for specific unpackers: Config presets for specific unpackers:
--z80 --big-endian-bitstream --invert-bit-encoding --simplified-prob-update -9 --z80 --big-endian-bitstream --invert-bit-encoding --simplified-prob-update -9
--x86 --bitstream --invert-is-match-bit --invert-continue-value-bit --invert-new-offset-bit --x86 --bitstream --invert-is-match-bit --invert-continue-value-bit --invert-new-offset-bit

BIN
README.md.upk Normal file

Binary file not shown.

2
c_library/.gitignore vendored Normal file
View File

@@ -0,0 +1,2 @@
/target/
/upkr

127
c_library/Cargo.lock generated Normal file
View File

@@ -0,0 +1,127 @@
# This file is automatically @generated by Cargo.
# It is not intended for manual editing.
version = 3
[[package]]
name = "anyhow"
version = "1.0.69"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "224afbd727c3d6e4b90103ece64b8d1b67fbb1973b1046c2281eed3f3803f800"
[[package]]
name = "autocfg"
version = "1.1.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "d468802bab17cbc0cc575e9b053f41e72aa36bfa6b7f55e3529ffa43161b97fa"
[[package]]
name = "cc"
version = "1.0.79"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "50d30906286121d95be3d479533b458f87493b30a4b5f79a607db8f5d11aa91f"
[[package]]
name = "cdivsufsort"
version = "2.0.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "edefce019197609da416762da75bb000bbd2224b2d89a7e722c2296cbff79b8c"
dependencies = [
"cc",
"sacabase",
]
[[package]]
name = "lexopt"
version = "0.2.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "478ee9e62aaeaf5b140bd4138753d1f109765488581444218d3ddda43234f3e8"
[[package]]
name = "num-traits"
version = "0.2.15"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "578ede34cf02f8924ab9447f50c28075b4d3e5b269972345e7e0372b38c6cdcd"
dependencies = [
"autocfg",
]
[[package]]
name = "proc-macro2"
version = "1.0.51"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "5d727cae5b39d21da60fa540906919ad737832fe0b1c165da3a34d6548c849d6"
dependencies = [
"unicode-ident",
]
[[package]]
name = "quote"
version = "1.0.23"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "8856d8364d252a14d474036ea1358d63c9e6965c8e5c1885c18f73d70bff9c7b"
dependencies = [
"proc-macro2",
]
[[package]]
name = "sacabase"
version = "2.0.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "9883fc3d6ce3d78bb54d908602f8bc1f7b5f983afe601dabe083009d86267a84"
dependencies = [
"num-traits",
]
[[package]]
name = "syn"
version = "1.0.109"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "72b64191b275b66ffe2469e8af2c1cfe3bafa67b529ead792a6d0160888b4237"
dependencies = [
"proc-macro2",
"quote",
"unicode-ident",
]
[[package]]
name = "thiserror"
version = "1.0.39"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "a5ab016db510546d856297882807df8da66a16fb8c4101cb8b30054b0d5b2d9c"
dependencies = [
"thiserror-impl",
]
[[package]]
name = "thiserror-impl"
version = "1.0.39"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "5420d42e90af0c38c3290abcca25b9b3bdf379fc9f55c528f53a269d9c9a267e"
dependencies = [
"proc-macro2",
"quote",
"syn",
]
[[package]]
name = "unicode-ident"
version = "1.0.8"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "e5464a87b239f13a63a501f2701565754bae92d243d4bb7eb12f6d57d2269bf4"
[[package]]
name = "upkr"
version = "0.2.1"
dependencies = [
"anyhow",
"cdivsufsort",
"lexopt",
"thiserror",
]
[[package]]
name = "upkr_c"
version = "0.0.1"
dependencies = [
"upkr",
]

17
c_library/Cargo.toml Normal file
View File

@@ -0,0 +1,17 @@
[package]
name = "upkr_c"
version = "0.0.1"
edition = "2021"
[lib]
name = "upkr"
crate-type = ["staticlib"]
[profile.release]
opt-level = "s"
strip = "debuginfo"
lto = true
panic = "abort"
[dependencies]
upkr = { path="..", default-features=false }

8
c_library/Makefile Normal file
View File

@@ -0,0 +1,8 @@
upkr: upkr.c upkr.h target/release/libupkr.a
gcc -O2 -Ltarget/release -o upkr upkr.c -lupkr -lm
strip upkr
target/release/libupkr.a: cargo
cargo build --release
.PHONY: cargo

11
c_library/Readme.md Normal file
View File

@@ -0,0 +1,11 @@
This is a simple example of compiling upkr to a library that can be linked in a
c program. It consists of a small rust crate which implements the c api and
compiles to a static library and a matching c header file. As is, the rust
crate offers two simple functions to compress/uncompress data with the default
upkr config.
The provided makefile will only work on linux. Building the example upkr.c on
other platforms is left as an exercise for the reader ;)
On Windows you might have to make sure to install and use the correct rust
toolchain version (mingw vs. msvc) to match your c compiler.

42
c_library/src/lib.rs Normal file
View File

@@ -0,0 +1,42 @@
use std::ffi::c_int;
// the upkr config to use, this can be modified to use other configs
fn config() -> upkr::Config {
upkr::Config::default()
}
#[no_mangle]
pub extern "C" fn upkr_compress(
output_buffer: *mut u8,
output_buffer_size: usize,
input_buffer: *const u8,
input_size: usize,
compression_level: c_int,
) -> usize {
let output_buffer = unsafe { std::slice::from_raw_parts_mut(output_buffer, output_buffer_size) };
let input_buffer = unsafe { std::slice::from_raw_parts(input_buffer, input_size) };
let packed_data = upkr::pack(input_buffer, compression_level.max(0).min(9) as u8, &config(), None);
let copy_size = packed_data.len().min(output_buffer.len());
output_buffer[..copy_size].copy_from_slice(&packed_data[..copy_size]);
packed_data.len()
}
#[no_mangle]
pub extern "C" fn upkr_uncompress(output_buffer: *mut u8, output_buffer_size: usize, input_buffer: *const u8, input_size: usize) -> isize {
let output_buffer = unsafe { std::slice::from_raw_parts_mut(output_buffer, output_buffer_size)};
let input_buffer = unsafe { std::slice::from_raw_parts(input_buffer, input_size)};
match upkr::unpack(input_buffer, &config(), output_buffer.len()) {
Ok(unpacked_data) => {
output_buffer[..unpacked_data.len()].copy_from_slice(&unpacked_data);
unpacked_data.len() as isize
}
Err(upkr::UnpackError::OverSize { size, .. }) => size as isize,
Err(other) => {
eprintln!("[upkr] compressed data corrupt: {}", other);
-1
}
}
}

99
c_library/upkr.c Normal file
View File

@@ -0,0 +1,99 @@
#include "upkr.h"
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
int main(int argc, char** argv) {
if(argc < 2) {
fprintf(stdout, "Usage:\n upkr [compress] [-0 .. -9] <file> [<out-file>]\n upkr [uncompress] <file> [<out-file>]\n");
return 1;
}
int argi = 1;
int uncompress = 0;
int compression_level = 4;
if(strcmp(argv[argi], "compress") == 0) {
++argi;
} else if(strcmp(argv[argi], "uncompress") == 0) {
uncompress = 1;
++argi;
}
if(argi < argc && argv[argi][0] == '-') {
compression_level = atoi(argv[argi] + 1);
++argi;
}
if(argi == argc) {
fprintf(stdout, "intput filename missing\n");
return 1;
}
const char* input_name = argv[argi++];
char* output_name;
if(argi < argc) {
output_name = argv[argi];
} else {
output_name = malloc(strlen(input_name) + 5);
strcpy(output_name, input_name);
strcat(output_name, uncompress ? ".unp" : ".upk");
}
FILE* file = fopen(input_name, "rb");
if(file == 0) {
fprintf(stdout, "failed to open input file '%s'\n", file);
return 1;
}
fseek(file, 0, SEEK_END);
long input_size = ftell(file);
rewind(file);
char* input_buffer = (char*)malloc(input_size);
long offset = 0;
while(offset < input_size) {
long read_size = fread(input_buffer + offset, 1, input_size - offset, file);
if(read_size <= 0) {
fprintf(stdout, "error reading input file\n");
return 1;
}
offset += read_size;
}
fclose(file);
long output_buffer_size = input_size * 8;
long output_size;
char* output_buffer = (char*)malloc(output_buffer_size);
for(;;) {
if(uncompress) {
output_size = upkr_uncompress(output_buffer, output_buffer_size, input_buffer, input_size);
} else {
output_size = upkr_compress(output_buffer, output_buffer_size, input_buffer, input_size, compression_level);
}
if(output_size < 0) {
return 1;
}
if(output_size <= output_buffer_size) {
break;
}
output_buffer = (char*)realloc(output_buffer, output_size);
output_buffer_size = output_size;
}
file = fopen(output_name, "wb");
if(file == 0) {
fprintf(stdout, "failed to open output file '%s'\n", output_name);
return 1;
}
offset = 0;
while(offset < output_size) {
long written_size = fwrite(output_buffer + offset, 1, output_size - offset, file);
if(written_size <= 0) {
fprintf(stdout, "error writing output file\n");
return 1;
}
offset += written_size;
}
fclose(file);
return 0;
}

25
c_library/upkr.h Normal file
View File

@@ -0,0 +1,25 @@
#ifndef UPKR_H_INCLUDED
#include <stddef.h>
#ifdef __cplusplus
extern "C" {
#endif
// input_buffer/input_size: input data to compress
// output_buffer/output_buffer_size: buffer to compress into
// compression_level: 0-9
// returns the size of the compressed data, even if it didn't fit into the output buffer
size_t upkr_compress(void* output_buffer, size_t output_buffer_size, void* input_buffer, size_t input_size, int compression_level);
// input_buffer/input_size: compressed data
// output_buffer/output_buffer_size: buffer to uncompress into
// return value:
// >= 0 : size of uncompressed data, even if it didn't fit into the output buffer
// < 0 : input data corrupt, unable to decompress
ptrdiff_t upkr_uncompress(void* output_buffer, size_t output_buffer_size, void* input_buffer, size_t input_size);
#ifdef __cplusplus
}
#endif
#endif

View File

@@ -105,15 +105,14 @@ upkr_decode_bit:
dec dx dec dx
jns upkr_load_bit jns upkr_load_bit
movzx ax, byte [bx] ; u16 prob = upkr_probs[context_index] movzx ax, byte [bx] ; u16 prob = upkr_probs[context_index]
neg byte [bx]
push ax ; save prob, tmp = prob push ax ; save prob, tmp = prob
cmp dl, al ; int bit = (upkr_state & 255) < prob ? 1 : 0; (carry = bit) cmp dl, al ; int bit = (upkr_state & 255) < prob ? 1 : 0; (carry = bit)
pushf ; save bit flags pushf ; save bit flags
jc .bit ; (skip if bit) jc .bit ; (skip if bit)
neg al ; tmp = 256 - tmp; xchg [bx], al ; tmp = 256 - tmp;
.bit: .bit:
mov [bx], al ; upkr_probs[context_index] = tmp + (256 - tmp + 8) >> 4; shr byte [bx], 4 ; upkr_probs[context_index] = tmp + (256 - tmp + 8) >> 4;
neg byte [bx]
shr byte [bx], 4
adc [bx], al adc [bx], al
mul dh ; upkr_state = tmp * (upkr_state >> 8) + (upkr_state & 255); mul dh ; upkr_state = tmp * (upkr_state >> 8) + (upkr_state & 255);
mov dh, 0 mov dh, 0

View File

@@ -95,16 +95,15 @@ upkr_decode_bit:
inc dx inc dx
dec dx ; inc dx, dec dx is used to test the top (sign) bit of dx dec dx ; inc dx, dec dx is used to test the top (sign) bit of dx
jns upkr_load_bit jns upkr_load_bit
movzx ax, byte [bx] ; int prob = upkr_probs[context_index] movzx ax, byte [bx] ; u16 prob = upkr_probs[context_index]
push ax ; save prob neg byte [bx]
push ax ; save prob, tmp = prob
cmp dl, al ; int bit = (upkr_state & 255) < prob ? 1 : 0; (carry = bit) cmp dl, al ; int bit = (upkr_state & 255) < prob ? 1 : 0; (carry = bit)
pushf ; save bit flags pushf ; save bit flags
jc .bit ; (skip if bit) jc .bit ; (skip if bit)
neg al ; tmp = 256 - tmp; xchg [bx], al ; tmp = 256 - tmp;
.bit: .bit:
mov [bx], al ; tmp_new = tmp + (256 - tmp + 8) >> 4; shr byte [bx], 4 ; upkr_probs[context_index] = tmp + (256 - tmp + 8) >> 4;
neg byte [bx]
shr byte [bx], 4
adc [bx], al adc [bx], al
mul dh ; upkr_state = tmp * (upkr_state >> 8) + (upkr_state & 255); mul dh ; upkr_state = tmp * (upkr_state >> 8) + (upkr_state & 255);
mov dh, 0 mov dh, 0

View File

@@ -98,16 +98,15 @@ upkr_decode_bit:
inc dx inc dx
dec dx ; or whatever other test for the top bit there is dec dx ; or whatever other test for the top bit there is
jns upkr_load_bit jns upkr_load_bit
movzx ax, byte [bx] ; int prob = upkr_probs[context_index] movzx ax, byte [bx] ; u16 prob = upkr_probs[context_index]
push ax ; save prob neg byte [bx]
push ax ; save prob, tmp = prob
cmp dl, al ; int bit = (upkr_state & 255) < prob ? 1 : 0; (carry = bit) cmp dl, al ; int bit = (upkr_state & 255) < prob ? 1 : 0; (carry = bit)
pushf ; save bit flags pushf ; save bit flags
jc .bit ; (skip if bit) jc .bit ; (skip if bit)
neg al ; tmp = 256 - tmp; xchg [bx], al ; tmp = 256 - tmp;
.bit: .bit:
mov [bx], al ; tmp += (256 - tmp + 8) >> 4; shr byte [bx], 4 ; upkr_probs[context_index] = tmp + (256 - tmp + 8) >> 4;
neg byte [bx]
shr byte [bx],4
adc [bx], al ; upkr_probs[context_index] = tmp; adc [bx], al ; upkr_probs[context_index] = tmp;
mul dh ; upkr_state = tmp * (upkr_state >> 8) + (upkr_state & 255); mul dh ; upkr_state = tmp * (upkr_state >> 8) + (upkr_state & 255);
mov dh, 0 mov dh, 0

1
release/.gitignore vendored
View File

@@ -2,3 +2,4 @@
*.tgz *.tgz
upkr-linux/ upkr-linux/
upkr-windows/ upkr-windows/
upkr-windows-32/

View File

@@ -1,11 +1,12 @@
VERSION := $(shell cargo run --release -- --version) VERSION := $(shell cargo run --release -- --version)
all: clean upkr-linux-$(VERSION).tgz upkr-windows-$(VERSION).zip all: clean upkr-linux-$(VERSION).tgz upkr-windows-$(VERSION).zip upkr-windows-32-$(VERSION).zip
clean: clean:
rm -rf upkr-linux rm -rf upkr-linux
rm -f upkr-linux*.tgz rm -f upkr-linux*.tgz
rm -rf upkr-windows rm -rf upkr-windows
rm -rf upkr-windows-32
rm -f upkr-windows*.zip rm -f upkr-windows*.zip
upkr-linux-$(VERSION).tgz: upkr-linux/upkr PHONY upkr-linux-$(VERSION).tgz: upkr-linux/upkr PHONY
@@ -22,14 +23,29 @@ upkr-windows-$(VERSION).zip: upkr-windows/upkr.exe PHONY
cd .. && git archive HEAD asm_unpackers | tar -xC release/upkr-windows cd .. && git archive HEAD asm_unpackers | tar -xC release/upkr-windows
zip -r -9 $@ upkr-windows zip -r -9 $@ upkr-windows
upkr-windows-32-$(VERSION).zip: upkr-windows-32/upkr.exe PHONY
cp ../README.md upkr-windows-32/
cd .. && git archive HEAD c_unpacker | tar -xC release/upkr-windows-32
cd .. && git archive HEAD z80_unpacker | tar -xC release/upkr-windows-32
cd .. && git archive HEAD asm_unpackers | tar -xC release/upkr-windows-32
zip -r -9 $@ upkr-windows-32
upkr-linux/upkr: upkr-linux/upkr:
cargo build --target x86_64-unknown-linux-musl --release cargo build --target x86_64-unknown-linux-musl --release -F terminal
mkdir -p upkr-linux mkdir -p upkr-linux
cp ../target/x86_64-unknown-linux-musl/release/upkr upkr-linux/ cp ../target/x86_64-unknown-linux-musl/release/upkr upkr-linux/
strip upkr-linux/upkr
upkr-windows/upkr.exe: upkr-windows/upkr.exe:
cargo build --target x86_64-pc-windows-gnu --release cargo build --target x86_64-pc-windows-gnu --release -F terminal
mkdir -p upkr-windows mkdir -p upkr-windows
cp ../target/x86_64-pc-windows-gnu/release/upkr.exe upkr-windows/ cp ../target/x86_64-pc-windows-gnu/release/upkr.exe upkr-windows/
x86_64-w64-mingw32-strip upkr-windows/upkr.exe
upkr-windows-32/upkr.exe:
cargo build --target i686-pc-windows-gnu --release -F terminal
mkdir -p upkr-windows-32
cp ../target/i686-pc-windows-gnu/release/upkr.exe upkr-windows-32/
i686-w64-mingw32-strip upkr-windows-32/upkr.exe
PHONY: PHONY:

View File

@@ -12,7 +12,7 @@ pub fn pack(
let mut rans_coder = RansCoder::new(config); let mut rans_coder = RansCoder::new(config);
let mut state = lz::CoderState::new(config); let mut state = lz::CoderState::new(config);
let mut pos = 0; let mut pos = config.dictionary_size;
while pos < data.len() { while pos < data.len() {
if let Some(ref mut cb) = progress_callback { if let Some(ref mut cb) = progress_callback {
cb(pos); cb(pos);

View File

@@ -1,25 +1,38 @@
/// Heatmap information about a compressed block of data.
///
/// For each byte in the uncompressed data, the heatmap provides two pieces of intormation:
/// 1. whether this byte was encoded as a literal or as part of a match
/// 2. how many (fractional) bits where spend on encoding this byte
///
/// For the sake of the heatmap, the cost of literals are spread out across all matches
/// that reference the literal.
///
/// If the `terminal` feature is enabled, there is a function to write out the
/// heatmap as a colored hexdump.
pub struct Heatmap { pub struct Heatmap {
data: Vec<u8>, data: Vec<u8>,
cost: Vec<f32>, cost: Vec<f32>,
raw_cost: Vec<f32>,
literal_index: Vec<usize>, literal_index: Vec<usize>,
} }
impl Heatmap { impl Heatmap {
pub fn new() -> Heatmap { pub(crate) fn new() -> Heatmap {
Heatmap { Heatmap {
data: Vec::new(), data: Vec::new(),
cost: Vec::new(), cost: Vec::new(),
raw_cost: Vec::new(),
literal_index: Vec::new(), literal_index: Vec::new(),
} }
} }
pub fn add_literal(&mut self, byte: u8, cost: f32) { pub(crate) fn add_literal(&mut self, byte: u8, cost: f32) {
self.data.push(byte); self.data.push(byte);
self.cost.push(cost); self.cost.push(cost);
self.literal_index.push(self.literal_index.len()); self.literal_index.push(self.literal_index.len());
} }
pub fn add_match(&mut self, offset: usize, length: usize, mut cost: f32) { pub(crate) fn add_match(&mut self, offset: usize, length: usize, mut cost: f32) {
cost /= length as f32; cost /= length as f32;
for _ in 0..length { for _ in 0..length {
self.data.push(self.data[self.data.len() - offset]); self.data.push(self.data[self.data.len() - offset]);
@@ -29,7 +42,9 @@ impl Heatmap {
} }
} }
pub fn finish(&mut self) { pub(crate) fn finish(&mut self) {
self.raw_cost = self.cost.clone();
let mut ref_count = vec![0usize; self.literal_index.len()]; let mut ref_count = vec![0usize; self.literal_index.len()];
for &index in &self.literal_index { for &index in &self.literal_index {
ref_count[index] += 1; ref_count[index] += 1;
@@ -47,6 +62,7 @@ impl Heatmap {
} }
} }
/// Reverses the heatmap
pub fn reverse(&mut self) { pub fn reverse(&mut self) {
self.data.reverse(); self.data.reverse();
self.cost.reverse(); self.cost.reverse();
@@ -56,23 +72,47 @@ impl Heatmap {
} }
} }
/// The number of (uncompressed) bytes of data in this heatmap
pub fn len(&self) -> usize { pub fn len(&self) -> usize {
self.cost.len() self.cost.len()
} }
/// Returns whether the byte at `index` was encoded as a literal
pub fn is_literal(&self, index: usize) -> bool { pub fn is_literal(&self, index: usize) -> bool {
self.literal_index[index] == index self.literal_index[index] == index
} }
/// Returns the cost of encoding the byte at `index` in (fractional) bits.
/// The cost of literal bytes is spread across the matches that reference it.
/// See `raw_cost` for the raw encoding cost of each byte.
pub fn cost(&self, index: usize) -> f32 { pub fn cost(&self, index: usize) -> f32 {
self.cost[index] self.cost[index]
} }
/// Returns the raw cost of encoding the byte at `index` in (fractional) bits
pub fn raw_cost(&self, index: usize) -> f32 {
self.raw_cost[index]
}
/// Returns the uncompressed data byte at `index`
pub fn byte(&self, index: usize) -> u8 { pub fn byte(&self, index: usize) -> u8 {
self.data[index] self.data[index]
} }
#[cfg(feature = "crossterm")]
/// Print the heatmap as a colored hexdump
pub fn print_as_hex(&self) -> std::io::Result<()> { pub fn print_as_hex(&self) -> std::io::Result<()> {
self.print_as_hex_internal(false)
}
#[cfg(feature = "crossterm")]
/// Print the heatmap as a colored hexdump, based on `raw_cost`.
pub fn print_as_hex_raw_cost(&self) -> std::io::Result<()> {
self.print_as_hex_internal(true)
}
#[cfg(feature = "crossterm")]
fn print_as_hex_internal(&self, report_raw_cost: bool) -> std::io::Result<()> {
use crossterm::{ use crossterm::{
style::{Attribute, Color, Print, SetAttribute, SetBackgroundColor}, style::{Attribute, Color, Print, SetAttribute, SetBackgroundColor},
QueueableCommand, QueueableCommand,
@@ -84,8 +124,13 @@ impl Heatmap {
heatmap: &Heatmap, heatmap: &Heatmap,
index: usize, index: usize,
num_colors: u16, num_colors: u16,
report_raw_cost: bool,
) -> std::io::Result<()> { ) -> std::io::Result<()> {
let cost = heatmap.cost(index); let cost = if report_raw_cost {
heatmap.raw_cost(index)
} else {
heatmap.cost(index)
};
if num_colors < 256 { if num_colors < 256 {
let colors = [ let colors = [
Color::Red, Color::Red,
@@ -131,7 +176,7 @@ impl Heatmap {
stdout.queue(Print(&format!("{:04x} ", row_start)))?; stdout.queue(Print(&format!("{:04x} ", row_start)))?;
for i in row_range.clone() { for i in row_range.clone() {
set_color(&mut stdout, self, i, num_colors)?; set_color(&mut stdout, self, i, num_colors, report_raw_cost)?;
stdout.queue(Print(&format!("{:02x} ", self.data[i])))?; stdout.queue(Print(&format!("{:02x} ", self.data[i])))?;
} }
@@ -142,7 +187,7 @@ impl Heatmap {
.queue(Print(&gap))?; .queue(Print(&gap))?;
for i in row_range.clone() { for i in row_range.clone() {
set_color(&mut stdout, self, i, num_colors)?; set_color(&mut stdout, self, i, num_colors, report_raw_cost)?;
let byte = self.data[i]; let byte = self.data[i];
if byte >= 32 && byte < 127 { if byte >= 32 && byte < 127 {
stdout.queue(Print(format!("{}", byte as char)))?; stdout.queue(Print(format!("{}", byte as char)))?;

View File

@@ -1,3 +1,12 @@
#![deny(missing_docs)]
//! Compression and decompression of the upkr format and variants.
//!
//! Upkr is a compression format initially designed for the MicroW8 fantasy console,
//! with design goals being a competitive compression ratio, reasonable fast
//! decompression, low memory overhead and very small decompression code
//! when handoptimized in assembler. (An optimized DOS execuable decompressor is <140 bytes.)
mod context_state; mod context_state;
mod greedy_packer; mod greedy_packer;
mod heatmap; mod heatmap;
@@ -9,26 +18,62 @@ mod rans;
pub use heatmap::Heatmap; pub use heatmap::Heatmap;
pub use lz::{calculate_margin, create_heatmap, unpack, UnpackError}; pub use lz::{calculate_margin, create_heatmap, unpack, UnpackError};
/// The type of a callback function to be given to the `pack` function.
///
/// It will be periodically called with the number of bytes of the input already processed.
pub type ProgressCallback<'a> = &'a mut dyn FnMut(usize); pub type ProgressCallback<'a> = &'a mut dyn FnMut(usize);
/// A configuration of which compression format variation to use.
///
/// Use `Config::default()` for the standard upkr format.
///
/// Compression format variants exist to help with micro-optimizations in uncompression
/// code on specific platforms.
#[derive(Debug)] #[derive(Debug)]
pub struct Config { pub struct Config {
/// Shift in bits from a bitstream into the rANS state, rather than whole bytes.
/// This decreases the size of the rNAS state to 16 bits which is very useful on
/// 8 bit platforms.
pub use_bitstream: bool, pub use_bitstream: bool,
/// The number of parity contexts (usually 1, 2 or 4). This can improve compression
/// on data that consists of regular groups of 2 or 4 bytes. One example is 32bit ARM
/// code, where each instruction is 4 bytes, so `parity_contexts = 4` improves compression
/// quite a bit. Defaults to `1`.
pub parity_contexts: usize, pub parity_contexts: usize,
/// Invert the encoding of bits in the rANS coder. `bit = state_lo >= prob` instead of
/// `bit = state_lo < prob`.
pub invert_bit_encoding: bool, pub invert_bit_encoding: bool,
/// The boolean value which encodes a match. Defaults to `true`.
pub is_match_bit: bool, pub is_match_bit: bool,
/// The boolean value which encodes a new offset (rather than re-using the previous offset).
/// Defaults to `true`.
pub new_offset_bit: bool, pub new_offset_bit: bool,
/// The boolean value which encodes that there are more bits comming for length/offset values.
/// Defaults to `true`.
pub continue_value_bit: bool, pub continue_value_bit: bool,
/// Reverses the bits in the bitstream.
pub bitstream_is_big_endian: bool, pub bitstream_is_big_endian: bool,
/// A slightly less accurate, but slightly simpler variation of the prob update in the
/// rANS coder, Used for the z80 uncompressor.
pub simplified_prob_update: bool, pub simplified_prob_update: bool,
/// Disables support for re-using the last offset in the compression format.
/// This might save a few bytes when working with very small data.
pub no_repeated_offsets: bool, pub no_repeated_offsets: bool,
/// Standard upkr encodes the EOF marker in the offset. This encodes it in the match length
/// instead.
pub eof_in_length: bool, pub eof_in_length: bool,
/// The maximum match offset value to encode when compressing.
pub max_offset: usize, pub max_offset: usize,
/// The maximum match length value to encode when compressing.
pub max_length: usize, pub max_length: usize,
/// Size of dictionary at the beginning of data (how many bytes to skip when compressing.)
pub dictionary_size: usize,
} }
impl Default for Config { impl Default for Config {
@@ -50,12 +95,14 @@ impl Default for Config {
max_offset: usize::MAX, max_offset: usize::MAX,
max_length: usize::MAX, max_length: usize::MAX,
dictionary_size: 0,
} }
} }
} }
impl Config { impl Config {
pub fn min_length(&self) -> usize { fn min_length(&self) -> usize {
if self.eof_in_length { if self.eof_in_length {
2 2
} else { } else {
@@ -64,6 +111,21 @@ impl Config {
} }
} }
/// Compresses the given data.
///
/// # Arguments
/// - `data`: The data to compress
/// - `level`: The compression level (0-9). Increasing the level by one roughly halves the
/// compression speed.
/// - `config`: The compression format variant to use.
/// - `progress_callback`: An optional callback which will periodically be called with
/// the number of bytes already processed.
///
/// # Example
/// ```rust
/// let compressed_data = upkr::pack(b"Hello, World! Yellow world!", 0, &upkr::Config::default(), None);
/// assert!(compressed_data.len() < 27);
/// ```
pub fn pack( pub fn pack(
data: &[u8], data: &[u8],
level: u8, level: u8,
@@ -77,6 +139,9 @@ pub fn pack(
} }
} }
/// Estimate the exact (fractional) size of upkr compressed data.
///
/// Note that this currently does NOT work for the bitstream variant.
pub fn compressed_size(mut data: &[u8]) -> f32 { pub fn compressed_size(mut data: &[u8]) -> f32 {
let mut state = 0; let mut state = 0;
while state < 4096 { while state < 4096 {

View File

@@ -133,21 +133,47 @@ impl CoderState {
} }
} }
/// The error type for the uncompressing related functions
#[derive(Error, Debug)] #[derive(Error, Debug)]
pub enum UnpackError { pub enum UnpackError {
/// a match offset pointing beyond the start of the unpacked data was encountered
#[error("match offset out of range: {offset} > {position}")] #[error("match offset out of range: {offset} > {position}")]
OffsetOutOfRange { offset: usize, position: usize }, OffsetOutOfRange {
/// the match offset
offset: usize,
/// the current position in the uncompressed stream
position: usize,
},
/// The passed size limit was exceeded
#[error("Unpacked data over size limit: {size} > {limit}")] #[error("Unpacked data over size limit: {size} > {limit}")]
OverSize { size: usize, limit: usize }, OverSize {
/// the size of the uncompressed data
size: usize,
/// the size limit passed into the function
limit: usize,
},
/// The end of the packed data was reached without an encoded EOF marker
#[error("Unexpected end of input data")] #[error("Unexpected end of input data")]
UnexpectedEOF { UnexpectedEOF {
#[from] #[from]
/// the underlying EOF error in the rANS decoder
source: crate::rans::UnexpectedEOF, source: crate::rans::UnexpectedEOF,
}, },
/// An offset or length value was found that exceeded 32bit
#[error("Overflow while reading value")] #[error("Overflow while reading value")]
ValueOverflow, ValueOverflow,
} }
/// Uncompress a piece of compressed data
///
/// Returns either the uncompressed data, or an `UnpackError`
///
/// # Parameters
///
/// - `packed_data`: the compressed data
/// - `config`: the exact compression format config used to compress the data
/// - `max_size`: the maximum size of uncompressed data to return. When this is exceeded,
/// `UnpackError::OverSize` is returned
pub fn unpack( pub fn unpack(
packed_data: &[u8], packed_data: &[u8],
config: &Config, config: &Config,
@@ -158,10 +184,22 @@ pub fn unpack(
Ok(result) Ok(result)
} }
/// Calculates the minimum margin when overlapping buffers.
///
/// Returns the minimum margin needed between the end of the compressed data and the
/// end of the uncompressed data when overlapping the two buffers to save on RAM.
pub fn calculate_margin(packed_data: &[u8], config: &Config) -> Result<isize, UnpackError> { pub fn calculate_margin(packed_data: &[u8], config: &Config) -> Result<isize, UnpackError> {
unpack_internal(None, None, packed_data, config, usize::MAX) unpack_internal(None, None, packed_data, config, usize::MAX)
} }
/// Calculates a `Heatmap` from compressed data.
///
/// # Parameters
///
/// - `packed_data`: the compressed data
/// - `config`: the exact compression format config used to compress the data
/// - `max_size`: the maximum size of the heatmap to return. When this is exceeded,
/// `UnpackError::OverSize` is returned
pub fn create_heatmap( pub fn create_heatmap(
packed_data: &[u8], packed_data: &[u8],
config: &Config, config: &Config,

View File

@@ -10,10 +10,13 @@ fn main() -> Result<()> {
let mut unpack = false; let mut unpack = false;
let mut calculate_margin = false; let mut calculate_margin = false;
let mut create_heatmap = false; let mut create_heatmap = false;
let mut report_raw_cost = false;
#[allow(unused_mut)]
let mut do_hexdump = false; let mut do_hexdump = false;
let mut level = 2; let mut level = 2;
let mut infile: Option<PathBuf> = None; let mut infile: Option<PathBuf> = None;
let mut outfile: Option<PathBuf> = None; let mut outfile: Option<PathBuf> = None;
let mut dictionary: Option<PathBuf> = None;
let mut max_unpacked_size = 512 * 1024 * 1024; let mut max_unpacked_size = 512 * 1024 * 1024;
let mut parser = lexopt::Parser::from_env(); let mut parser = lexopt::Parser::from_env();
@@ -58,9 +61,11 @@ fn main() -> Result<()> {
level = 9; level = 9;
} }
Short('u') | Long("unpack") => unpack = true, Short('u') | Long("unpack") | Short('d') | Long("decompress") => unpack = true,
Long("margin") => calculate_margin = true, Long("margin") => calculate_margin = true,
Long("heatmap") => create_heatmap = true, Long("heatmap") => create_heatmap = true,
Long("raw-cost") => report_raw_cost = true,
#[cfg(feature = "crossterm")]
Long("hexdump") => do_hexdump = true, Long("hexdump") => do_hexdump = true,
Short('l') | Long("level") => level = parser.value()?.parse()?, Short('l') | Long("level") => level = parser.value()?.parse()?,
Short(n) if n.is_ascii_digit() => level = n as u8 - b'0', Short(n) if n.is_ascii_digit() => level = n as u8 - b'0',
@@ -70,44 +75,15 @@ fn main() -> Result<()> {
process::exit(0); process::exit(0);
} }
Long("max-unpacked-size") => max_unpacked_size = parser.value()?.parse()?, Long("max-unpacked-size") => max_unpacked_size = parser.value()?.parse()?,
Long("dictionary") => dictionary = Some(parser.value()?.try_into()?),
Value(val) if infile.is_none() => infile = Some(val.try_into()?), Value(val) if infile.is_none() => infile = Some(val.try_into()?),
Value(val) if outfile.is_none() => outfile = Some(val.try_into()?), Value(val) if outfile.is_none() => outfile = Some(val.try_into()?),
_ => return Err(arg.unexpected().into()), _ => return Err(arg.unexpected().into()),
} }
} }
let infile = infile.unwrap_or_else(|| print_help(1)); let infile = IoTarget::from_filename(infile);
enum OutFileType { let outfile = |tpe: OutFileType| infile.output(tpe, &outfile);
Packed,
Unpacked,
Heatmap,
}
let outfile = |tpe: OutFileType| {
outfile.clone().unwrap_or_else(|| {
let mut name = infile.clone();
match tpe {
OutFileType::Packed => {
let mut filename = name
.file_name()
.unwrap_or_else(|| OsStr::new(""))
.to_os_string();
filename.push(".upk");
name.set_file_name(filename);
}
OutFileType::Unpacked => {
if name.extension().filter(|&e| e == "upk").is_some() {
name.set_extension("");
} else {
name.set_extension("bin");
}
}
OutFileType::Heatmap => {
name.set_extension("heatmap");
}
}
name
})
};
if config.parity_contexts != 1 && config.parity_contexts != 2 && config.parity_contexts != 4 { if config.parity_contexts != 1 && config.parity_contexts != 2 && config.parity_contexts != 4 {
eprintln!("--parity has to be 1, 2, or 4"); eprintln!("--parity has to be 1, 2, or 4");
@@ -115,38 +91,52 @@ fn main() -> Result<()> {
} }
if !unpack && !calculate_margin && !create_heatmap { if !unpack && !calculate_margin && !create_heatmap {
let mut data = vec![]; let mut data = infile.read()?;
File::open(&infile)?.read_to_end(&mut data)?;
if reverse { if reverse {
data.reverse(); data.reverse();
} }
let mut pb = pbr::ProgressBar::new(data.len() as u64); if let Some(dictionary) = dictionary {
pb.set_units(pbr::Units::Bytes); let mut dict = vec![];
let mut packed_data = upkr::pack( File::open(dictionary)?.read_to_end(&mut dict)?;
&data, config.dictionary_size = dict.len();
level, // prepend dict
&config, dict.append(&mut data);
Some(&mut |pos| { data = dict;
pb.set(pos as u64); }
}),
); #[cfg(feature = "terminal")]
pb.finish(); let mut packed_data = {
let mut pb = pbr::ProgressBar::on(std::io::stderr(), data.len() as u64);
pb.set_units(pbr::Units::Bytes);
let packed_data = upkr::pack(
&data,
level,
&config,
Some(&mut |pos| {
pb.set(pos as u64);
}),
);
pb.finish();
eprintln!();
packed_data
};
#[cfg(not(feature = "terminal"))]
let mut packed_data = upkr::pack(&data, level, &config, None);
if reverse { if reverse {
packed_data.reverse(); packed_data.reverse();
} }
println!( eprintln!(
"Compressed {} bytes to {} bytes ({}%)", "Compressed {} bytes to {} bytes ({}%)",
data.len(), data.len(),
packed_data.len(), packed_data.len(),
packed_data.len() as f32 * 100. / data.len() as f32 packed_data.len() as f32 * 100. / data.len() as f32
); );
File::create(outfile(OutFileType::Packed))?.write_all(&packed_data)?; outfile(OutFileType::Packed).write(&packed_data)?;
} else { } else {
let mut data = vec![]; let mut data = infile.read()?;
File::open(&infile)?.read_to_end(&mut data)?;
if reverse { if reverse {
data.reverse(); data.reverse();
} }
@@ -155,25 +145,35 @@ fn main() -> Result<()> {
if reverse { if reverse {
unpacked_data.reverse(); unpacked_data.reverse();
} }
File::create(outfile(OutFileType::Unpacked))?.write_all(&unpacked_data)?; outfile(OutFileType::Unpacked).write(&unpacked_data)?;
} }
if create_heatmap { if create_heatmap {
let mut heatmap = upkr::create_heatmap(&data, &config, max_unpacked_size)?; let mut heatmap = upkr::create_heatmap(&data, &config, max_unpacked_size)?;
if reverse { if reverse {
heatmap.reverse(); heatmap.reverse();
} }
if do_hexdump { match do_hexdump {
heatmap.print_as_hex()?; #[cfg(feature = "crossterm")]
} else { true => {
let mut heatmap_bin = Vec::with_capacity(heatmap.len()); if report_raw_cost {
for i in 0..heatmap.len() { heatmap.print_as_hex_raw_cost()?
let cost = (heatmap.cost(i).log2() * 8. + 64.) } else {
.round() heatmap.print_as_hex()?
.max(0.) }
.min(127.) as u8; }
heatmap_bin.push((cost << 1) | heatmap.is_literal(i) as u8); _ => {
let mut heatmap_bin = Vec::with_capacity(heatmap.len());
for i in 0..heatmap.len() {
let cost = if report_raw_cost {
heatmap.raw_cost(i)
} else {
heatmap.cost(i)
};
let cost = (cost.log2() * 8. + 64.).round().max(0.).min(127.) as u8;
heatmap_bin.push((cost << 1) | heatmap.is_literal(i) as u8);
}
outfile(OutFileType::Heatmap).write(&heatmap_bin)?;
} }
File::create(outfile(OutFileType::Heatmap))?.write_all(&heatmap_bin)?;
} }
} }
if calculate_margin { if calculate_margin {
@@ -184,6 +184,81 @@ fn main() -> Result<()> {
Ok(()) Ok(())
} }
enum OutFileType {
Packed,
Unpacked,
Heatmap,
}
enum IoTarget {
StdInOut,
File(PathBuf),
}
impl IoTarget {
fn from_filename(filename: Option<PathBuf>) -> IoTarget {
if let Some(path) = filename {
if path.as_os_str() == "-" {
IoTarget::StdInOut
} else {
IoTarget::File(path)
}
} else {
IoTarget::StdInOut
}
}
fn read(&self) -> Result<Vec<u8>> {
let mut buffer = vec![];
match *self {
IoTarget::StdInOut => std::io::stdin().read_to_end(&mut buffer)?,
IoTarget::File(ref path) => File::open(path)?.read_to_end(&mut buffer)?,
};
Ok(buffer)
}
fn write(&self, data: &[u8]) -> Result<()> {
match *self {
IoTarget::StdInOut => std::io::stdout().write_all(data)?,
IoTarget::File(ref path) => File::create(path)?.write_all(data)?,
};
Ok(())
}
fn output(&self, tpe: OutFileType, outname: &Option<PathBuf>) -> IoTarget {
if outname.is_some() {
return IoTarget::from_filename(outname.clone());
}
match *self {
IoTarget::StdInOut => IoTarget::StdInOut,
IoTarget::File(ref path) => {
let mut name = path.clone();
match tpe {
OutFileType::Packed => {
let mut filename = name
.file_name()
.unwrap_or_else(|| OsStr::new(""))
.to_os_string();
filename.push(".upk");
name.set_file_name(filename);
}
OutFileType::Unpacked => {
if name.extension().filter(|&e| e == "upk").is_some() {
name.set_extension("");
} else {
name.set_extension("bin");
}
}
OutFileType::Heatmap => {
name.set_extension("heatmap");
}
}
IoTarget::File(name)
}
}
}
}
fn print_help(exit_code: i32) -> ! { fn print_help(exit_code: i32) -> ! {
eprintln!("Usage:"); eprintln!("Usage:");
eprintln!(" upkr [-l level(0-9)] [config options] <infile> [<outfile>]"); eprintln!(" upkr [-l level(0-9)] [config options] <infile> [<outfile>]");
@@ -193,10 +268,18 @@ fn print_help(exit_code: i32) -> ! {
eprintln!(); eprintln!();
eprintln!(" -l, --level N compression level 0-9"); eprintln!(" -l, --level N compression level 0-9");
eprintln!(" -0, ..., -9 short form for setting compression level"); eprintln!(" -0, ..., -9 short form for setting compression level");
eprintln!(" -u, --unpack unpack infile"); eprintln!(" -d, --decompress decompress infile");
eprintln!(" --heatmap calculate heatmap from compressed file"); eprintln!(" --heatmap calculate heatmap from compressed file");
eprintln!(" --raw-cost report raw cost of literals in heatmap");
#[cfg(feature = "crossterm")]
eprintln!(" --hexdump print heatmap as colored hexdump");
eprintln!(" --margin calculate margin for overlapped unpacking of a packed file"); eprintln!(" --margin calculate margin for overlapped unpacking of a packed file");
eprintln!(); eprintln!();
eprintln!("When no infile is given, or the infile is '-', read from stdin.");
eprintln!(
"When no outfile is given and reading from stdin, or when outfile is '-', write to stdout."
);
eprintln!();
eprintln!("Version: {}", env!("CARGO_PKG_VERSION")); eprintln!("Version: {}", env!("CARGO_PKG_VERSION"));
eprintln!(); eprintln!();
eprintln!("Config presets for specific unpackers:"); eprintln!("Config presets for specific unpackers:");

View File

@@ -137,7 +137,7 @@ fn parse(
} }
add_arrival( add_arrival(
&mut arrivals, &mut arrivals,
0, encoding_config.dictionary_size,
Arrival { Arrival {
parse: None, parse: None,
state: lz::CoderState::new(encoding_config), state: lz::CoderState::new(encoding_config),
@@ -148,7 +148,7 @@ fn parse(
let cost_counter = &mut CostCounter::new(encoding_config); let cost_counter = &mut CostCounter::new(encoding_config);
let mut best_per_offset = HashMap::new(); let mut best_per_offset = HashMap::new();
for pos in 0..data.len() { for pos in encoding_config.dictionary_size..data.len() {
let match_length = |offset: usize| { let match_length = |offset: usize| {
data[pos..] data[pos..]
.iter() .iter()