www.digitalmars.com [Home] [Search] [D]

Last update Jan 9, 2002


D Runtime Library (Phobos)

This document describes the standard runtime library that comes with the D language compiler.

Philosophy

Each module in Phobos conforms as much as possible to the following design goals. These are goals rather than requirements because D is not a religion, it's a programming language, and it recognizes that sometimes the goals are contradictory and counterproductive in certain situations, and programmers have jobs that need to get done.
Machine and Operating System Independent Interfaces
It's pretty well accepted that gratuitous non-portability should be avoided. This should not be construed, however, as meaning that access to unusual features of an operating system should be prevented.
Simple Operations should be Simple
A common and simple operation, like writing an array of bytes to a file, should be simple to code. I haven't seen a class library yet that simply and efficiently implemented common, basic file I/O operations.
Classes should strive to be independent of one another
It's discouraging to pull in a megabyte of code bloat by just trying to read a file into an array of bytes. Class independence also means that classes that turn out to be mistakes can be deprecated and redesigned without forcing a rewrite of the rest of the class library.
No pointless wrappers around C runtime library functions or OS API functions
D provides direct access to C runtime library functions and operating system API functions. Pointless D wrappers around those functions just adds blather, bloat, baggage and bugs.
No user interface windowing classes
GUI styles, philosophies, etc., are not portable from machine to machine. A GUI Windows app should look like a Windows app when running on a Windows machine. It should not look and feel like a Mac app unless it is running on a Mac. Attempts to create a common GUI class library between Windows, Mac, and other GUI operating systems have all to my knowledge failed.
Java has a successful GUI class library, but does so by creating its own GUI with its own look and feel. This approach is fine for a web language, but not for a systems language like D is.
Windowing class libraries should be separate.
Class implementations should use DBC
This will prove that DBC (Design by Contract) is worthwhile. Not only will it aid in debugging the class, but it will help every class user use the class correctly. DBC in the class library will have great leverage.
Use Exceptions for Error Handling
See Error Handling in D.

Imports

Each of these can be imported with the import statement. The categories are:

Core D: Available on all D implementations

compiler
Information about the D compiler implementation
ctype
Simple character classification
date
Date and time functions. Support locales.
file
Basic file operations like read, write, append.
gc
Control the garbage collector.
math
Include all the usual math functions like sin, cos, atan, etc.
object
The root class of the inheritance heirarchy
outbuffer
Assemble data into an array of bytes
path
Manipulate file names, path names, etc.
process
Create/destroy threads.
random
Random number generation.
regexp
The usual regular expression functions.
string
Basic string operations not covered by array ops.
system
Inquire about the CPU, operating system.
thread
One per thread. Operations to do on a thread.
zip
Manipulate zip files.

Standard C: interface to C functions

stdio
Interface to C stdio functions like printf().

Operating System APIs: platform specific

windows
Interface to Windows APIs

compiler

char[] name;
Vendor specific string naming the compiler, for example: "Digital Mars D".

enum Vendor
Master list of D compiler vendors.
DigitalMars
Digital Mars

Vendor vendor;
Which vendor produced this compiler.

uint version_major;
uint version_minor;
The vendor specific version number, as in version_major.version_minor.

uint D_major;
uint D_minor;
The version of the D Programming Language Specification supported by the compiler.


ctype

int isalnum(char c)
Returns !=0 if c is a letter or a digit.

int isalpha(char c)
Returns !=0 if c is an upper or lower case letter.

int iscntrl(char c)
Returns !=0 if c is a control character.

int isdigit(char c)
Returns !=0 if c is a digit.

int isgraph(char c)
Returns !=0 if c is a printing character except for the space character.

int islower(char c)
Returns !=0 if c is lower case.

int isprint(char c)
Returns !=0 if c is a printing character or a space.

int ispunct(char c)
Returns !=0 if c is a punctuation character.

int isspace(char c)
Returns !=0 if c is a space, tab, vertical tab, form feed, carriage return, or linefeed.

int isupper(char c)
Returns !=0 if c is an upper case character.

int isxdigit(char c)
Returns !=0 if c is a hex digit (0..9, a..f, A..F).

int isascii(uint c)
Returns !=0 if c is in the ascii character set.

char tolower(char c)
If c is upper case, return the lower case equivalent, otherwise return c.

char toupper(char c)
If c is lower case, return the upper case equivalent, otherwise return c.


date


file

class FileException
Exception thrown if file I/O errors.

byte[] read(char[] name)
Read file name[], return array of bytes read.

void write(char[] name, byte[] buffer)
Write buffer[] to file name[].

void append(char[] name, byte[] buffer)
Append buffer[] to file name[].

void rename(char[] from, char[] to)
Rename file from[] to to[].

void remove(char[] name)
Delete file name[].

uint getSize(char[] name)
Get size of file name[].

uint getAttributes(char[] name)
Get file name[] attributes.


gc


math

const extended PI
const extended LOG2
const extended LN2
const extended LOG2T
const extended LOG2E
const extended E
const extended LOG10E
const extended LN10
const extended PI_2
const extended PI_4
const extended M_1_PI
const extended M_2_PI
const extended M_2_SQRTPI
const extended SQRT2
const extended SQRT1_2
Math constants.

extended acos(extended)
extended asin(extended)
extended atan(extended)
extended atan2(extended, extended)
extended cos(extended)
extended sin(extended)
extended tan(extended)
extended cosh(extended)
extended sinh(extended)
extended tanh(extended)
extended exp(extended)
extended frexp(extended,int *)
extended ldexp(extended,int)
extended log(extended)
extended log10(extended)
extended modf(extended, extended *)
extended pow(extended, extended)
extended sqrt(extended)
extended ceil(extended)
extended floor(extended)
extended log1p(extended)
extended expm1(extended)
extended atof(char *)
extended hypot(extended, extended)
Math functions.

int isnan(extended e)
Is number a nan?

int isfinite(extended e)
Is number finite?

int isnormal(float f)
int isnormal(double d)
int isnormal(extended e)
Is number normalized?

int issubnormal(float f)
int issubnormal(double d)
int issubnormal(extended e)
Is number subnormal? (Also called "denormal".) Subnormals have a 0 exponent and a 0 most significant mantissa bit.

int isinf(extended e)
Is number infinity?

int signbit(extended e)
Get sign bit.

extended copysign(extended to, extended from)
Copy sign.


object

This module is implicitly imported.
class Object
All class objects in D inherit from Object.

static int printf(char* format, ...);
C printf function.

char[] toString()
Convert Object to a human readable string.

uint toHash()
Compute hash function for Object.

int cmp(Object obj)
Compare with another Object obj. Returns:
<0 for (this < obj)
=0 for (this == obj)
>0 for (this > obj)

class ClassInfo
Runtime type information about a class.

class Exception
All exceptions should be derived from class Exception.


outbuffer

class OutBuffer
OutBuffer provides a way to build up an array of bytes out of raw data. It is useful for things like preparing an array of bytes to write out to a file. OutBuffer's byte order is the format native to the computer. To control the byte order (endianness), use a class derived from OutBuffer. To convert an array of bytes back into raw data, use InBuffer.

void reserve(uint nbytes)
Preallocate nbytes more to the size of the internal buffer. This is a speed optimization, a good guess at the maximum size of the resulting buffer will improve performance by eliminating reallocations and copying.

void write(ubyte[] bytes)
void write(ubyte b)
void write(byte b)
void write(char c)
void write(ushort w)
void write(short s)
void write(wchar c)
void write(uint w)
void write(int i)
void write(ulong l)
void write(long l)
void write(float f)
void write(double f)
void write(extended f)
void write(char[] s)
void write(OutBuffer buf)
Append data to the internal buffer.

void fill0(uint nbytes)
Append nbytes of 0 to the internal buffer.

void alignSize(uint alignsize)
0-fill to align on an alignsize boundary. alignsize must be a power of 2.

void align2()
Optimize common special case alignSize(2)

void align4()
Optimize common special case alignSize(4)

ubyte[] toBytes()
Convert internal buffer to array of bytes.

char[] toString()
Convert internal buffer to array of chars.

void vprintf(char[] format, va_list args)
Append output of vprintf() to internal buffer.

void printf(char[] format, ...)
Append output of printf() to internal buffer.

void spread(uint index, uint nbytes)
At offset index into buffer, create nbytes of space by shifting upwards all data past index.


path

const char[] sep;
Character used to separate directory names in a path.

const char[] altsep;
Alternate version of sep[], used in Windows.

const char[] pathsep;
Path separator string.

const char[] linesep;
String used to separate lines.

const char[] curdir;
String representing the current directory.

const char[] pardir;
String representing the parent directory.

char[] getExt(char[] fullname)
Get extension. For example, "d:\path\foo.bat" returns "bat".

char[] getBaseName(char[] fullname)
Get base name. For example, "d:\path\foo.bat" returns "foo.bat".

char[] getDirName(char[] fullname)
Get directory name. For example, "d:\path\foo.bat" returns "d:\path".

char[] getDrive(char[] fullname)
Get drive. For example, "d:\path\foo.bat" returns "d:". Returns null string on systems without the concept of a drive.

char[] defaultExt(char[] fullname, char[] ext)
Put a default extension on fullname if it doesn't already have an extension.

char[] addExt(char[] fullname, char[] ext)
Add file extension or replace existing extension.

int isabs(char[] path)
Determine if absolute path name.

char[] join(char[] p1, char[] p2)
Join two path components.

int fncharmatch(char c1, char c2)
Match file name characters. Case sensitivity depends on the operating system.

int fnmatch(char[] name, char[] pattern)
Match filename strings with pattern[], using the following wildcards:
* match 0 or more characters
? match any character
[chars] match any character that appears between the []
[!chars] match any character that does not appear between the [! ]
Matching is case sensitive on a file system that is case sensitive.
Returns:
!=0 match
0 no match


process


random

void rand_seed(uint seed, uint index)
The random number generator is seeded at program startup with a random value. This ensures that each program generates a different sequence of random numbers. To generate a repeatable sequence, use rand_seed() to start the sequence. seed and index start it, and each successive value increments index. This means that the nth random number of the sequence can be directly generated by passing index + n to rand_seed().

uint rand()
Get next random number in sequence.


regexp

RegExp is a D class to handle regular expressions. Regular expressions are a powerful method of string pattern matching. The RegExp class is the core foundation for adding powerful string pattern matching capabilities to programs like grep, text editors, awk, sed, etc. The regular expression language used is the same as that commonly used, however, some of the very advanced forms may behave slightly differently.

The RegExp class has these methods:

this(char[] pattern, char[] attributes)
Create a new RegExp object. Compile pattern[] with attributes[] into an internal form for fast execution. Throws a RegExpError if there are any compilation errors.

char[][] split(char[] string)
Split string[] into an array of strings, using the regular expression as the separator. Returns array of slices in string[].

int search(char[] string)
Search string[] for match with regular expression.
Returns Description
>=0 index of match
-1 no match

char[][] match(char[] string)
Search string[] for match.
Attribute Returns
global same as call to exec(string)
not global array of all matches

char[][] exec(char[] string)
Search string[] for next match. Returns array of slices into string[] representing matches.

int test(char[] string)
Search string[] for next match.
Returns Description
0 no match
!=0 match

char[] replace(char[] string, char[] format)
Find regular expression matches in string[]. Replace those matches with a new string composed of format[] merged with the result of the matches.
Attribute Action
global replace all matches
not global replace first match
Returns the new string.

char[] replace(char[] format)
After a match is found with test(), this function will take the match results and, using the format[] string, generate and return a new string. The format commands are:
Format Description
$$ insert $
$& insert the matched substring
$` insert the string that precedes the match
$' insert the string that following the match
$n replace with the nth parenthesized match, n is 1..9
$nn replace with the nnth parenthesized match, nn is 01..99
$ insert $

char[] replaceOld(char[] format)
Like replace(char[] format), but uses old style formatting:
Format Description
& replace with the match
\n replace with the nth parenthesized match, n is 1..9
\c replace with char c.


string

To copy or not to copy?

When a function takes a string as a parameter, and returns a string, is that string the same as the input string, modified in place, or is it a modified copy of the input string? The D array convention is "copy-on-write". This means that if no modifications are done, the original string (or slices of it) can be returned. If any modifications are done, the returned string is a copy.
class StringException
Thrown on errors in string functions.

const char[] hexdigits;
"0123456789ABCDEF"

const char[] digits;
"0123456789"

const char[] octdigits;
"01234567"

const char[] lowercase;
"abcdefghijklmnopqrstuvwxyz"

const char[] uppercase;
"ABCDEFGHIJKLMNOPQRSTUVWXYZ"

const char[] letters;
"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz"

const char[] whitespace;
" \t\v\r\n\f"

long atoi(char[] s)
Convert string to integer.

extended atof(char[] s)
Convert string to extended.

int cmp(char[] s1, char[] s2)
Compare two strings. Returns:
<0 for (s1 < s2)
=0 for (s1 == s2)
>0 for (s1 > s2)

int icmp(char[] s1, char[] s2)
Same as cmp() but case insensitive.

char* toCharz(char[] string)
Converts a D array of chars to a C-style 0 terminated string.

int find(char[] s, char c)
Find first occurrance of c in string s. Return index in s where it is found. Return -1 if not found.

int rfind(char[] s, char c)
Find last occurrance of c in string s. Return index in s where it is found. Return -1 if not found.

int find(char[] s, char[] sub)
Find first occurrance of sub[] in string s[]. Return index in s[] where it is found. Return -1 if not found.

int rfind(char[] s, char[] sub)
Find last occurrance of sub in string s. Return index in s where it is found. Return -1 if not found.

char[] tolower(char[] s)
Convert string to lower case.

char[] toupper(char[] s)
Convert string to upper case.

char[] capitalize(char[] s)
Capitalize first character of string.

char[] capwords(char[] s)
Capitalize all words in string. Remove leading and trailing whitespace. Replace all sequences of whitespace with a single space.

char[] join(char[][] words, char[] sep)
Concatenate all the strings together into one string; use sep[] as the separator.

char[][] split(char[] s)
Split s[] into an array of words, using whitespace as the delimiter.

char[][] split(char[] s, char[] delim)
Split s[] into an array of words, using delim[] as the delimiter.

char[][] splitlines(char[] s)
Split s[] into an array of lines, using CR, LF, or CR-LF as the delimiter.

char[] stripl(char[] s)
char[] stripr(char[] s)
char[] strip(char[] s)
Strips leading or trailing whitespace, or both.

char[] ljustify(char[] s, int width)
char[] rjustify(char[] s, int width)
char[] center(char[] s, int width)
Left justify, right justify, or center string in field width chars wide.

char[] zfill(char[] s, int width)
Same as rjustify(), but fill with '0's.

char[] replace(char[] s, char[] from, char[] to)
Replace occurrences of from[] with to[] in s[].

char[] replaceSlice(char[] string, char[] slice, char[] replacement)
Given a string[] with a slice[] into it, replace slice[] with replacement[].

char[] insert(char[] s, int index, char[] sub)
Insert sub[] into s[] at location index.

int count(char[] s, char[] sub)
Count up all instances of sub[] in s[].

char[] expandtabs(char[] s, int tabsize)
Replace tabs with the appropriate number of spaces. tabsize is the distance between tab stops.

char[] maketrans(char[] from, char[] to)
Construct translation table for translate().

char[] translate(char[] s, char[] transtab, char[] delchars)
Translate characters in s[] using table created by maketrans(). Delete chars in delchars[].


system


thread


zip



stdio

int printf(char* format, ...)
C printf() function.

Copyright (c) 1999-2002 by Digital Mars, All Rights Reserved