官术网_书友最值得收藏!

  • 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:

  1. Import std.zlib.
  2. Create an instance of Compress or UnCompress, depending on what direction you want to go.
  3. Call the compress or uncompress methods for each block of data, concatenating the pieces together as they are made.
  4. 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.

主站蜘蛛池模板: 和政县| 大渡口区| 新密市| 洪洞县| 龙里县| 龙井市| 丰原市| 从化市| 岑巩县| 藁城市| 永春县| 乌拉特中旗| 贡觉县| 五河县| 德化县| 宣恩县| 鲁甸县| 棋牌| 永济市| 巴彦淖尔市| 苍山县| 喜德县| 满洲里市| 贞丰县| 乌拉特中旗| 杨浦区| 中卫市| 通道| 宁武县| 鸡东县| 台前县| 南漳县| 合阳县| 乡宁县| 兴义市| 广州市| 新兴县| 禹城市| 五常市| 专栏| 甘洛县|