# 压缩
`compress/` 完全在内存中打包和解包归档数据:tar、gzip
以及 tar.gz 辅助函数,消费并生成字节字符串。它们是原生标准库,在
每个宿主中都可用,无需导入。将它们与 文件系统 组合可在
磁盘与归档之间搬运数据,与 加密 组合可在载荷发布前
进行哈希或加密。
## 函数
| 函数 | 用途 |
|---|---|
| `compress/tar-create $dir-path` | 将目录树打包为 USTAR tar;返回归档字节 |
| `compress/tar-extract $bytes $dest-dir` | 将 tar 字节解包到 `$dest-dir`(不存在时创建) |
| `compress/gzip $bytes` | 将字节 gzip 压缩为 RFC 1952 容器 |
| `compress/gunzip $bytes` | 将 gzip 编码的字节解压回原始内容 |
| `compress/tgz-create $dir-path` | 将目录树打包为 tar.gz;在 `tar-create` 之上套 gzip |
| `compress/tgz-extract $bytes $dest-dir` | 先解压再解包 tar 到 `$dest-dir` |
| `compress/list-tgz $bytes` | tar.gz 内条目路径的向量,无需解包 |
所有参数和结果都是二进制安全的字符串:
- `tar-create` 和 `tgz-create` 接受目录路径(相对或
绝对)。归档内的条目路径相对于该目录的 basename,因此
`[compress/tar-create "./src"]` 会存储
`src/...` 条目 —— 解包时在 `$dest-dir` 下重建该布局。
- `tar-extract` 和 `tgz-extract` 成功时返回 `true`,并在
`$dest-dir` 缺失时创建它。普通文件、目录和
符号链接都会被恢复。
- `list-tgz` 返回路径字符串的向量(`@{ "src/a.dft" ... }`)。
- gzip 编码器写入存储型 deflate 块:输出是任何解码器都能读取的
有效 gzip,生成成本低,但它存储数据而非压缩数据。
- 所有函数在输入格式错误时返回 `%Err{ :message "..." }`
而不是抛出异常;使用结果前先用 `err?` 检查。
## 示例
# Pack a tree, write it to disk, list and restore it set tgz [compress/tgz-create "./src"] [fs/write "src.tgz" $tgz] [compress/list-tgz $tgz] # => @{ "src/main.dft" "src/util.dft" ... } set ok [compress/tgz-extract [unwrap [fs/read "src.tgz"]] "./backup"] # => true # The tar and gzip layers work on their own set tar [compress/tar-create "./src"] set copy [compress/gunzip [compress/gzip $tar]] # Errors come back as values, so check before use set bad [compress/gunzip "not a gzip stream"] if [err? $bad] { echo "bad archive:" $bad~message }