Book Image

D Cookbook

By : Adam Ruppe
Book Image

D Cookbook

By: Adam Ruppe

Overview of this book

Table of Contents (21 chapters)
D Cookbook
Credits
Foreword
About the Author
About the Reviewers
www.PacktPub.com
Preface
Index

Creating user-defined literals


D doesn't have specialized syntax for user-defined literals, but using the template syntax with the right implementation, we can generate the same code as if it did. A distinguishing factor of user-defined literals is that there must be zero runtime cost to use them. Here, we'll write the code to enable integer literals written in octal, a simplified version of the implementation of octal in Phobos' std.conv module.

Getting ready

First, let's write an octal number parser, converting from string to integer. The algorithm is simple: read a digit, multiply our accumulator by eight, and then add the value to the accumulator until we're out of digits. Any invalid digit is an exception. All these steps are shown in the following code:

int readOctalString(string n) {
  int sum = 0;
  foreach(c; n) {
    if(c < '0' || c > '7')
      throw new Exception("Bad octal number " ~ n);
    sum *= 8;
    sum += c - '0';
  }

  return sum;
}

unittest {
  assert(readOctalString...