- D Cookbook
- Adam D. Ruppe
- 251字
- 2021-07-16 11:50:47
Using the std.zlib compression
Phobos provides a wrapper for the common zlib
/gzip
/DEFLATE
compression algorithm. This algorithm is used in the .zip
files, the .png
images, the HTTP protocol, the common gzip
utility, and more. With std.zlib
, we can both compress and decompress data easily.
How to do it…
Let's compress and decompress data by executing the following steps:
- Import
std.zlib
. - Create an instance of
Compress
orUnCompress
, depending on what direction you want to go. - Call the
compress
oruncompress
methods for each block of data, concatenating the pieces together as they are made. - Call
flush
to get the last block of data.
The code is as follows:
void main() { import std.zlib, std.file; auto compressor = new Compress(HeaderFormat.gzip); void[] compressedData; compressedData ~= compressor.compress("Hello, "); compressedData ~= compressor.compress("world!"); compressedData ~= compressor.flush(); std.file.write("compressed.gz", compressedData); }
Running the program will create a file, compressed.gz
, which can be unzipped to become a text file with Hello, world!
.
How it works…
The std.zlib
module doesn't follow exactly the same pattern as std.digest
(the implementation of std.zlib
was written before ranges were incorporated into Phobos), but it is a very simple API. It works with one block of data at a time, returning the compressed or uncompressed block. When finished, the flush
method clears any partial blocks, returning the final piece of data.
There are also convenience functions, compress
and uncompress
, that can perform the operation in a single function call if you have all the data available as a single array at once.
- Learning Scala Programming
- 流量的秘密:Google Analytics網站分析與優化技巧(第2版)
- JavaScript前端開發模塊化教程
- Python機器學習:數據分析與評分卡建模(微課版)
- Apache Spark Graph Processing
- 微服務架構深度解析:原理、實踐與進階
- Python極簡講義:一本書入門數據分析與機器學習
- Microsoft Azure Storage Essentials
- Java實戰(第2版)
- 微信小程序開發與實戰(微課版)
- 圖數據庫實戰
- 區塊鏈國產化實踐指南:基于Fabric 2.0
- JavaScript+jQuery網頁特效設計任務驅動教程
- 超簡單:用Python讓Excel飛起來(實戰150例)
- JavaScript Concurrency