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

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

主站蜘蛛池模板: 东丽区| 澜沧| 扎鲁特旗| 汨罗市| 潜江市| 卫辉市| 内丘县| 陆良县| 麟游县| 礼泉县| 南华县| 阿拉尔市| 新巴尔虎右旗| 邮箱| 钟祥市| 平阴县| 磴口县| 措勤县| 堆龙德庆县| 泽库县| 昌江| 新巴尔虎右旗| 二手房| 墨脱县| 庆云县| 临海市| 临清市| 湘潭市| 岚皋县| 寿宁县| 锡林浩特市| 兴隆县| 巢湖市| 施秉县| 九江县| 盐亭县| 万盛区| 庆元县| 布尔津县| 延安市| 永济市|