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

Writing a digest utility

Phobos provides a package called std.digest that offers checksum and message digest algorithms through a unified API. Here, we'll create a small MD5 utility that calculates and prints the resulting digest of a file.

How to do it…

Let's print an MD5 digest by executing the following steps:

  1. Create a digest object with the algorithm you need. Here, we'll use MD5 from std.digest.md.
  2. Call the start method.
  3. Use the put method, or the put function from std.range, to feed data to the digest object.
  4. Call the finish method.
  5. Convert hexadecimal data to string if you want.

The code is as follows:

void main(string[] args) {
    import std.digest.md;
    import std.stdio;
    import std.range;

    File file;
    if(args.length > 1)
        file = File(args[1], "rb");
    else
        file = stdin;
    MD5 digest;
    digest.start();
    put(digest, file.byChunk(1024));
    writeln(toHexString(digest.finish()));
}

How it works…

The std.digest package in Phobos defines modules that all follow a common API. The digest structures are output ranges, which means you feed data to them by calling their put method. Each digest algorithm is in a separate module, but they all follow the same pattern: you create the object, call start(), put your data into it, and then call finish() to get the result. If you want it as a printable string, call toHexString on the result.

Tip

If you pass a digest structure to a function, be sure to pass it as a reference, because they are value types. So, without a reference, data added to it inside a function won't be visible outside the function!

The put method on the structure itself offers only one form, accepting one array of data at a time. However, the std.range module includes additional helper functions to expand the capabilities of any output range. The std.range.put function can also accept input ranges. The end result is we build something very similar to a Unix pipeline; put(digest, file.byChunk(1024)) will read a file, one kilobyte chunk at a time, and feed that data into the digest algorithm. The std.range.put method looks like the following:

foreach(chunk; input) output.put(chunk);

It is a generic function that works to connect any kind of output range to any kind of input range with a matching element type.

There's more…

Phobos' digest API also provides two other ways to get digests: a convenience function if all the data is available at once, md5Of, and the OOP API (an interface and classes) if you need to swap out implementations at runtime.

writeln("The MD5 hash of 'test' is ", toHexString(md5Of("test")));

There are also other algorithms available in std.digest with the same API, including SHA1 and CRC.

See also

主站蜘蛛池模板: 江山市| 望奎县| 广平县| 吉安县| 黑龙江省| 黎川县| 驻马店市| 盘山县| 托克逊县| 苍梧县| 武夷山市| 吐鲁番市| 铜陵市| 尼勒克县| 巨野县| 大厂| 建瓯市| 庆城县| 银川市| 东平县| 东丰县| 益阳市| 鄯善县| 内丘县| 大悟县| 阿克苏市| 兴隆县| 辽阳市| 马鞍山市| 岳阳县| 新龙县| 五家渠市| 梓潼县| 二连浩特市| 石门县| 江阴市| 长汀县| 通州区| 吉木萨尔县| 汉源县| 永丰县|