Search icon CANCEL
Subscription
0
Cart icon
Your Cart (0 item)
Close icon
You have no products in your basket yet
Save more on your purchases! discount-offer-chevron-icon
Savings automatically calculated. No voucher code required.
Arrow left icon
Explore Products
Best Sellers
New Releases
Books
Videos
Audiobooks
Learning Hub
Newsletter Hub
Free Learning
Arrow right icon
timer SALE ENDS IN
0 Days
:
00 Hours
:
00 Minutes
:
00 Seconds
D Cookbook
D Cookbook

D Cookbook: Discover the advantages of programming in D with over 100 incredibly effective recipes with this book and ebook.

eBook
€28.99 €32.99
Paperback
€41.99
Subscription
Free Trial
Renews at $19.99p/m

What do you get with a Packt Subscription?

Free for first 7 days. $19.99 p/m after that. Cancel any time!
Product feature icon Unlimited ad-free access to the largest independent learning library in tech. Access this title and thousands more!
Product feature icon 50+ new titles added per month, including many first-to-market concepts and exclusive early access to books as they are being written.
Product feature icon Innovative learning tools, including AI book assistants, code context explainers, and text-to-speech.
Product feature icon Thousands of reference materials covering every tech concept you need to stay up to date.
Subscribe now
View plans & pricing
Table of content icon View table of contents Preview book icon Preview Book

D Cookbook

Chapter 2. Phobos – The Standard Library

In this chapter, we will learn how to use the D standard library and explore the language concepts used in the implementation. You will learn the following recipes:

  • Performing type conversions

  • Finding the largest files in a directory

  • Creating a network client and server

  • Using Base64 to create a data URI

  • Generating random numbers

  • Normalizing a string and performing Unicode comparisons

  • Searching with regular expressions

  • Writing a digest utility

  • Using the std.zlib compression

  • Using the std.json module

Introduction


The D standard library, Phobos, provides a variety of modules that do a variety of tasks. This chapter will only cover a portion of its ever-growing capabilities.

Performing type conversions


D is a strongly typed language, which means converting between types often has to be done explicitly. The language's built-in cast operator only works when the types are already mostly compatible, for example int to short, or in cases where the user has defined an opCast function. This doesn't cover the very common need of converting strings to integers and vice versa. That's where Phobos' std.conv module is helpful.

How to do it…

Now it's time to perform type conversions by executing the following steps:

  1. Import std.conv.

  2. Use the to function as follows:

    import std.conv;
    auto converted = to!desired_type(variable_to_convert);

    This is pretty simple, and it works for a lot of types.

  3. To convert a string to an integer, use the following line of code:

    auto a = to!int("123"); // a == 123

That's all you have to do!

How it works…

The std.conv.to function strives to be a one-stop shop for type conversions. The to function isn't just one function. It is actually a family of functions...

Finding the largest files in a directory


Suppose you're out of disk space. A solution may be to delete old, large files from a directory. Let's write a D program to perform this task.

How to do it…

Execute the following steps to find the largest files in a directory:

  1. Use the std.file.dirEntries function to get a listing of all files.

  2. Define the DirEntry variable as an array.

  3. Sort the array by size in descending order by using std.algorithm and a lambda function.

  4. Filter out the newer files with std.algorithm.filter.

  5. Delete the top 10 files with the std.file.remove function.

The code is as follows:

void main() {
    import std.file, std.algorithm, std.datetime, std.range;
    DirEntry[] allFiles;
    foreach(DirEntry entry; dirEntries("target_directory", SpanMode.depth))
        allFiles ~= entry;
    auto sorted = sort!((a, b) => a.size > b.size)(allFiles);
    auto filtered = filter!((a) => Clock.currTime() - a.timeLastModified >> 14.days)(sorted);
    foreach(file; filtered.take!...

Creating a network client and server


Networking is a common requirement in modern applications. Phobos offers a module, std.socket, which provides a foundation for networked applications. We'll write a client and server pair to demonstrate how to use it. The client will send lines from standard input to the server. The server will accept any number of connections, say hello to new clients, and then echo back whatever it received.

How to do it…

We'll be building two separate applications: the client and the server.

Client

Let's create a client by executing the following steps:

  1. Create a Socket object.

  2. Connect to the server.

  3. Declare a buffer to hold the received data. The buffer must be preallocated to the maximum amount of data you want to handle in a single call to receive the data. Here, we'll use a static array of length 1024; it will have plenty of room to hold our message.

  4. Receive the hello message we sent in the server.

  5. Then, send each line of the message to the server, wait for the response...

Using Base64 to create a data URI


Given a CSS file, we want to replace all instances of a particular image URL with a data URI to reduce the number of requests. Let's write a small D program to do this replacement.

How to do it…

Let's create a data URI by executing the following steps:

  1. Load the image file with std.file.read().

  2. Create the data URI with std.base64 as shown in the following code:

    pure char[] makeDataUri(string contentType, in void[] data) {
        import std.base64;
        return "data:" ~ contentType ~ ";base64," ~ Base64.encode(cast(const(ubyte[]))) data;
    }
  3. Load the CSS file with std.file.readText.

  4. Use std.array.replace to replace the URL with the data URI.

  5. Save the CSS file with std.file.write.

Putting it all together in main, you will have the following code:

void main() {
    import std.file, std.array;
    auto imageData = std.file.read("image.png"); // step 1
    string dataUri = makeDataUri("image/png", imageData); 
    // step 2
    auto cssFile = std.file.readText("style.css"); ...

Generating random numbers


Random numbers are commonly necessary in computer programs. Phobos' std.random module offers a variety of random number generators and other functions related to randomization. Here, we'll create a little number guessing game with a replay function. The user guesses the generated number, and then the program tells them if they were high or low.

How to do it…

Let's generate random numbers by executing the following steps:

  1. Create a random number generator, seeding it with the replay value, if given, or unpredictableSeed for a new game.

  2. Generate a random number between 0 and 100.

  3. Ask the user for their guess. Tell them if they were low or high and let them continue trying until they get it. Save each line of user input to the replay file.

  4. When the user is done playing, let them know how many tries they took to get the correct number.

The code is as follows:

import std.random, std.conv, std.string, std.stdio;

int playRound(ref Random generator, File userInput, File saveFile...

Normalizing a string and performing Unicode comparisons


We want to make a filename or URL based on an article title. To do this, we'll have to limit the size to an appropriate number of characters, strip out improper characters, and format the string in a consistent way. We also want it to remain in the valid UTF-8 format.

How to do it…

Let's normalize a string by executing the following steps:

  1. Use std.uni.normalize to get Unicode characters into a consistent format.

  2. Use std.string.toLower to convert everything to lowercase for consistency.

  3. Use std.regex to strip out all but a small set of characters.

  4. Use std.string.squeeze to collapse consecutive whitespace.

  5. Use std.array.replace to change spaces into dashes.

  6. Use std.range.take to get the right number of characters, then convert the result back to string.

The code is as follows:

void main(){
  string title = "The D Programming Language: Easy Speed!";
  import std.uni, std.string, std.conv, std.range,std.regex;
  title = normalize(title);
  title...

Searching with regular expressions


Regular expressions are a common tool to perform advanced operations on text, including complex searches, replacements, splitting, and more. Unlike JavaScript or Perl, D does not have regular expressions built into the language, but it has all the same power—and more—as those languages through the std.regex Phobos module. To explore regular expressions in D, we'll write a small program that searches stdin for a particular regex that is given on the command line and prints out the matching lines.

How to do it…

Let's use the search operation with regular expressions by executing the following steps:

  1. Create a Regex object. If you are using string literals, D's r"" or `` syntax makes it much more readable.

  2. Loop over the matches and print them out.

Pretty simple! The code is as follows:

void main(string[] args) {
    import std.regex, std.stdio;
    auto re = regex(args[1], "g");
    foreach(line; stdin.byLine)
    if(line.match(re)) writeln(line, " was a match!"...

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...

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...

Using the std.json module


JSON is a common data interchange format used on the Web. Phobos has a std.json module that can be used to read and write JSON data. The std.json module is an old module that doesn't take advantage of many of D's advanced features, making it somewhat difficult to use. While newer JSON libraries exist for D, including ones that can be used with syntax and convenience, which is extremely similar to JavaScript itself, Phobos has not yet adopted any of them. Here, we'll read a JSON string, print the current contents, add a new field, and then print out the new JSON.

How to do it…

Suppose we're consuming a web API that returns an array of person objects with a name and ID field. We get the following JSON string from the API:

[{"name":"Alice","id":1},{"name":"Bob","id":2}]

Let's execute the following steps to use the std.json module:

  1. Parse the JSON string.

  2. Loop over the array, getting objects out.

  3. Print the information we need, getting the types out of the web API's specification...

Left arrow icon Right arrow icon

Product Details

Country selected
Publication date, Length, Edition, Language, ISBN-13
Publication date : May 26, 2014
Length: 362 pages
Edition :
Language : English
ISBN-13 : 9781783287215
Category :

What do you get with a Packt Subscription?

Free for first 7 days. $19.99 p/m after that. Cancel any time!
Product feature icon Unlimited ad-free access to the largest independent learning library in tech. Access this title and thousands more!
Product feature icon 50+ new titles added per month, including many first-to-market concepts and exclusive early access to books as they are being written.
Product feature icon Innovative learning tools, including AI book assistants, code context explainers, and text-to-speech.
Product feature icon Thousands of reference materials covering every tech concept you need to stay up to date.
Subscribe now
View plans & pricing

Product Details

Publication date : May 26, 2014
Length: 362 pages
Edition :
Language : English
ISBN-13 : 9781783287215
Category :

Packt Subscriptions

See our plans and pricing
Modal Close icon
$19.99 billed monthly
Feature tick icon Unlimited access to Packt's library of 7,000+ practical books and videos
Feature tick icon Constantly refreshed with 50+ new titles a month
Feature tick icon Exclusive Early access to books as they're written
Feature tick icon Solve problems while you work with advanced search and reference features
Feature tick icon Offline reading on the mobile app
Feature tick icon Simple pricing, no contract
$199.99 billed annually
Feature tick icon Unlimited access to Packt's library of 7,000+ practical books and videos
Feature tick icon Constantly refreshed with 50+ new titles a month
Feature tick icon Exclusive Early access to books as they're written
Feature tick icon Solve problems while you work with advanced search and reference features
Feature tick icon Offline reading on the mobile app
Feature tick icon Choose a DRM-free eBook or Video every month to keep
Feature tick icon PLUS own as many other DRM-free eBooks or Videos as you like for just €5 each
Feature tick icon Exclusive print discounts
$279.99 billed in 18 months
Feature tick icon Unlimited access to Packt's library of 7,000+ practical books and videos
Feature tick icon Constantly refreshed with 50+ new titles a month
Feature tick icon Exclusive Early access to books as they're written
Feature tick icon Solve problems while you work with advanced search and reference features
Feature tick icon Offline reading on the mobile app
Feature tick icon Choose a DRM-free eBook or Video every month to keep
Feature tick icon PLUS own as many other DRM-free eBooks or Videos as you like for just €5 each
Feature tick icon Exclusive print discounts

Frequently bought together


Stars icon
Total 113.97
D Web Development
€29.99
Learning D
€41.99
D Cookbook
€41.99
Total 113.97 Stars icon

Table of Contents

12 Chapters
Core Tasks Chevron down icon Chevron up icon
Phobos – The Standard Library Chevron down icon Chevron up icon
Ranges Chevron down icon Chevron up icon
Integration Chevron down icon Chevron up icon
Resource Management Chevron down icon Chevron up icon
Wrapped Types Chevron down icon Chevron up icon
Correctness Checking Chevron down icon Chevron up icon
Reflection Chevron down icon Chevron up icon
Code Generation Chevron down icon Chevron up icon
Multitasking Chevron down icon Chevron up icon
D for Kernel Coding Chevron down icon Chevron up icon
Web and GUI Programming Chevron down icon Chevron up icon

Customer reviews

Top Reviews
Rating distribution
Full star icon Full star icon Full star icon Full star icon Full star icon 5
(9 Ratings)
5 star 100%
4 star 0%
3 star 0%
2 star 0%
1 star 0%
Filter icon Filter
Top Reviews

Filter reviews by




Dmitry Podborits Oct 13, 2015
Full star icon Full star icon Full star icon Full star icon Full star icon 5
This book is a collection of well-crafted "recipes", each aiming at some realistic software engineering problem, and each blending just enough pragmatism, theory and hard-won programming experience to make a novice D user (such as myself) appreciate the sheer power and elegance of this language and learn more about it.While going through the recipes comprising this cookbook (and there is a lot to go through) it was hard to avoid developing an ever-growing sense of appreciation and respect for the author Adam D. Ruppe's level of expertise, eloquence and clarity of thought.I highly recommend this book. As a software practitioner, I felt both enlightened and empowered after I read it.
Amazon Verified review Amazon
Colden Cullen Jul 11, 2014
Full star icon Full star icon Full star icon Full star icon Full star icon 5
"The D Cookbook" by Adam Ruppe is one of the most diverse technical books I've read. It manages to range all the way from the classic "Hello, world" example, all the way up to stripping the Runtime bare and running it on an OS-less board, all the while managing to fully explain (almost) everything in a way that a beginner could understand.The book is formatted in such a way that each chapter is a group of related "recipes." Each recipe explains a concept by starting with a general summary, and a code sample, and ends it up with a *very* detailed explanation of how everything works. These descriptions also often include some very helpful tangential tips about how to be better D programmer in general, which can be very helpful. It's amazing how simply Ruppe can explain how and why you should do relatively advanced things like accessing and parsing exception-less stack traces.The only thing I don't like about the recipes is that sometimes the "How it works" section can be a bit long-winded. The descriptions can often span multiple pages, often reiterating lots of information. It isn't necessarily a bad thing, but be prepared to skim a lot of the book if you already know a fair amount about D programming.Overall, I think that "The D Cookbook" is an excellent read, and should be considered required reading for anyone serious about coding with D. It also makes a very handy reference for how to do things that you can't necessarily find on StackOverflow or Dlang.org yet.**Disclaimer**: I did receive a free copy of The D Cookbook ebook in exchange for a fair and unbiased review, and it did not alter my judgement in any way, shape, or form.
Amazon Verified review Amazon
Joe Page May 04, 2015
Full star icon Full star icon Full star icon Full star icon Full star icon 5
The D Cookbook is great! I became very interested in DLang earlier this year, though like others, I was put off by the lack of information out there. This book definitely solved that issue. I would say this book is ideal for those who already have a moderate to excellent understanding of programming as it doesn't really get into fundamentals and depth of the language or programming(though that is not the point of the book, so it is a plus in my view), The thing I like most about this book is that it solves just about every issue you may need help with when starting a new language. With a wide range of, shall I say "recipes", this book is very effective. A developer who already knows a language, can pick this book up and develop their project by getting help from the many great recipes.
Amazon Verified review Amazon
Philippe Peter Jan 01, 2016
Full star icon Full star icon Full star icon Full star icon Full star icon 5
Je m'initie au langage D depuis peu et il me fallait un livre de recettes, "D Cookbook" est vraiment bien et permet de migrer rapidement ses outils du C++ vers le D. Il est le compagnon indispensable de Programming in D: Tutorial and Reference de Andrei Alexandrescu.
Amazon Verified review Amazon
Stephen Aug 16, 2019
Full star icon Full star icon Full star icon Full star icon Full star icon 5
Great examples.
Amazon Verified review Amazon
Get free access to Packt library with over 7500+ books and video courses for 7 days!
Start Free Trial

FAQs

What is included in a Packt subscription? Chevron down icon Chevron up icon

A subscription provides you with full access to view all Packt and licnesed content online, this includes exclusive access to Early Access titles. Depending on the tier chosen you can also earn credits and discounts to use for owning content

How can I cancel my subscription? Chevron down icon Chevron up icon

To cancel your subscription with us simply go to the account page - found in the top right of the page or at https://subscription.packtpub.com/my-account/subscription - From here you will see the ‘cancel subscription’ button in the grey box with your subscription information in.

What are credits? Chevron down icon Chevron up icon

Credits can be earned from reading 40 section of any title within the payment cycle - a month starting from the day of subscription payment. You also earn a Credit every month if you subscribe to our annual or 18 month plans. Credits can be used to buy books DRM free, the same way that you would pay for a book. Your credits can be found in the subscription homepage - subscription.packtpub.com - clicking on ‘the my’ library dropdown and selecting ‘credits’.

What happens if an Early Access Course is cancelled? Chevron down icon Chevron up icon

Projects are rarely cancelled, but sometimes it's unavoidable. If an Early Access course is cancelled or excessively delayed, you can exchange your purchase for another course. For further details, please contact us here.

Where can I send feedback about an Early Access title? Chevron down icon Chevron up icon

If you have any feedback about the product you're reading, or Early Access in general, then please fill out a contact form here and we'll make sure the feedback gets to the right team. 

Can I download the code files for Early Access titles? Chevron down icon Chevron up icon

We try to ensure that all books in Early Access have code available to use, download, and fork on GitHub. This helps us be more agile in the development of the book, and helps keep the often changing code base of new versions and new technologies as up to date as possible. Unfortunately, however, there will be rare cases when it is not possible for us to have downloadable code samples available until publication.

When we publish the book, the code files will also be available to download from the Packt website.

How accurate is the publication date? Chevron down icon Chevron up icon

The publication date is as accurate as we can be at any point in the project. Unfortunately, delays can happen. Often those delays are out of our control, such as changes to the technology code base or delays in the tech release. We do our best to give you an accurate estimate of the publication date at any given time, and as more chapters are delivered, the more accurate the delivery date will become.

How will I know when new chapters are ready? Chevron down icon Chevron up icon

We'll let you know every time there has been an update to a course that you've bought in Early Access. You'll get an email to let you know there has been a new chapter, or a change to a previous chapter. The new chapters are automatically added to your account, so you can also check back there any time you're ready and download or read them online.

I am a Packt subscriber, do I get Early Access? Chevron down icon Chevron up icon

Yes, all Early Access content is fully available through your subscription. You will need to have a paid for or active trial subscription in order to access all titles.

How is Early Access delivered? Chevron down icon Chevron up icon

Early Access is currently only available as a PDF or through our online reader. As we make changes or add new chapters, the files in your Packt account will be updated so you can download them again or view them online immediately.

How do I buy Early Access content? Chevron down icon Chevron up icon

Early Access is a way of us getting our content to you quicker, but the method of buying the Early Access course is still the same. Just find the course you want to buy, go through the check-out steps, and you’ll get a confirmation email from us with information and a link to the relevant Early Access courses.

What is Early Access? Chevron down icon Chevron up icon

Keeping up to date with the latest technology is difficult; new versions, new frameworks, new techniques. This feature gives you a head-start to our content, as it's being created. With Early Access you'll receive each chapter as it's written, and get regular updates throughout the product's development, as well as the final course as soon as it's ready.We created Early Access as a means of giving you the information you need, as soon as it's available. As we go through the process of developing a course, 99% of it can be ready but we can't publish until that last 1% falls in to place. Early Access helps to unlock the potential of our content early, to help you start your learning when you need it most. You not only get access to every chapter as it's delivered, edited, and updated, but you'll also get the finalized, DRM-free product to download in any format you want when it's published. As a member of Packt, you'll also be eligible for our exclusive offers, including a free course every day, and discounts on new and popular titles.