www.digitalmars.com [Home] [Search] [D]
Last update Feb 20, 2005

Phobos

D Runtime Library

Phobos is the standard runtime library that comes with the D language compiler. Also, check out the wiki for Phobos.

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.
Class implementations should use DBC
This will prove that DBC (Contract Programming) 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

Runtime library modules can be imported with the import statement. Each module falls into one of several packages:
std
These are the core modules.

std.windows
Modules specific to the Windows operating system.

std.linux
Modules specific to the Linux operating system.

std.c
Modules that are simply interfaces to C functions. For example, interfaces to standard C library functions will be in std.c, such as std.c.stdio would be the interface to C's stdio.h.

std.c.windows
Modules corresponding to the C Windows API functions.

std.c.linux
Modules corresponding to the C Linux API functions.

etc
This is the root of a hierarchy of modules mirroring the std hierarchy. Modules in etc are not standard D modules. They are here because they are experimental, or for some other reason are not quite suitable for std, although they are still useful.


std: Core library modules

std.base64
Encode/decode base64 format.
std.compiler
Information about the D compiler implementation.
std.conv
Conversion of strings to integers.
std.ctype
Simple character classification
std.date
Date and time functions. Support locales.
std.file
Basic file operations like read, write, append.
std.format
Formatted conversions of values to strings.
std.gc
Control the garbage collector.
std.intrinsic
Compiler built in intrinsic functions
std.math
Include all the usual math functions like sin, cos, atan, etc.
std.md5
Compute MD5 digests.
std.mmfile
Memory mapped files.
object
The root class of the inheritance hierarchy
std.outbuffer
Assemble data into an array of bytes
std.path
Manipulate file names, path names, etc.
std.process
Create/destroy threads.
std.random
Random number generation.
std.recls
Recursively search file system and (currently Windows only) FTP sites.
std.regexp
The usual regular expression functions.
std.socket
Sockets.
std.socketstream
Stream for a blocking, connected Socket.
std.stdint
Integral types for various purposes.
std.stdio
Standard I/O.
std.stream
Stream I/O.
std.string
Basic string operations not covered by array ops.
std.system
Inquire about the CPU, operating system.
std.thread
One per thread. Operations to do on a thread.
std.uri
Encode and decode Uniform Resource Identifiers (URIs).
std.utf
Encode and decode utf character encodings.
std.zip
Read/write zip archives.
std.zlib
Compression / Decompression of data.

std.c: Interface to C functions

std.c.stdio
Interface to C stdio functions like printf().

std.c.windows: Interface to C Windows functions

std.c.windows.windows
Interface to Windows APIs

std.c.linux: Interface to C Linux functions

std.c.linux
Interface to Linux APIs

std.base64

Encodes/decodes base64 data.

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


std.conv

std.conv provides basic building blocks for conversions from strings to integral types. They differ from the C functions atoi() and atol() by not allowing whitespace or overflows.

For conversion to signed types, the grammar recognized is:

	Integer:
		Sign UnsignedInteger
		UnsignedInteger

	Sign:
		+
		-
	
For conversion to unsigned types, the grammar recognized is:
	UnsignedInteger:
		DecimalDigit
		DecimalDigit UnsignedInteger
	
Any deviation from that grammar causes a ConvError exception to be thrown. Any overflows cause a ConvOverflowError to be thrown.
byte toByte(char[] s)

ubyte toUbyte(char[] s)

short toShort(char[] s)

ushort toUshort(char[] s)

int toInt(char[] s)

uint toUint(char[] s)

long toLong(char[] s)

ulong toUlong(char[] s)


std.ctype

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

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

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

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

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

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

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

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

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

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

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

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

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

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


std.date

Dates are represented in several formats. The date implementation revolves around a central type, d_time, from which other formats are converted to and from.

typedef d_time
Is a signed arithmetic type giving the time elapsed since January 1, 1970. Negative values are for dates preceding 1970. The time unit used is Ticks. Ticks are milliseconds or smaller intervals.

The usual arithmetic operations can be performed on d_time, such as adding, subtracting, etc. Elapsed time in Ticks can be computed by subtracting a starting d_time from an ending d_time.

An invalid value for d_time is represented by d_time.init.

int TicksPerSecond
A constant giving the number of Ticks per second for this implementation. It will be at least 1000.

char[] toString(d_time t)
Converts t into a text string of the form: "Www Mmm dd hh:mm:ss GMT+-TZ yyyy", for example, "Tue Apr 02 02:04:57 GMT-0800 1996". If t is invalid, "Invalid date" is returned.

char[] toUTCString(d_time t)
Converts t into a text string of the form: "Www, dd Mmm yyyy hh:mm:ss UTC". If t is invalid, "Invalid date" is returned.

char[] toDateString(d_time t)
Converts the date portion of t into a text string of the form: "Www Mmm dd yyyy", for example, "Tue Apr 02 1996". If t is invalid, "Invalid date" is returned.

char[] toTimeString(d_time t)
Converts the time portion of t into a text string of the form: "hh:mm:ss GMT+-TZ", for example, "02:04:57 GMT-0800". If t is invalid, "Invalid date" is returned.

d_time parse(char[] s)
Parses s as a textual date string, and returns it as a d_time. If the string is not a valid date, d_time.init is returned.

void toISO8601YearWeek(d_time t, out int year, out int week)
Compute year and week [1..53] from t. The ISO 8601 week 1 is the first week of the year that includes January 4. Monday is the first day of the week.

d_time getUTCtime()
Get current UTC time.

d_time UTCtoLocalTime(d_time t)
Convert from UTC time to local time.

d_time LocalTimetoUTC(d_time t)
Convert from local time to UTC time.

typedef DosFileTime
Type representing the DOS file date/time format.

d_time toDtime(DosFileTime time)
Convert from DOS file date/time to d_time.

DosFileTime toDosFileTime(d_time t)
Convert from d_time to DOS file date/time.

std.file

class FileException
Exception thrown if file I/O errors.

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

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

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

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

void copy(char[] from, char[] to)
Copy 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.

int exists(char[] name)
Does name[] exist (file or directory)?

int isfile(char[] name)
Is name[] a file? Error if name[] doesn't exist.

int isdir(char[] name)
Is name[] a directory? Error if name[] doesn't exist.

void chdir(char[] name)
Change directory.

void mkdir(char[] name)
Make directory.

void rmdir(char[] name)
Remove directory.

char[] getcwd()
Get current directory.

char[][] listdir(char[] pathname)
Return contents of directory.


std.gc

The garbage collector normally works behind the scenes without needing any specific interaction. These functions are for advanced applications that benefit from tuning the operation of the collector.
class OutOfMemory
Thrown if garbage collector runs out of memory.

void addRoot(void* p)
Add p to list of roots. Roots are references to memory allocated by the collector that are maintained in memory outside the collector pool. The garbage collector will by default look for roots in the stacks of each thread, the registers, and the default static data segment. If roots are held elsewhere, use addRoot() or addRange() to tell the collector not to free the memory it points to.

void removeRoot(void* p)
Remove p from list of roots.

void addRange(void* pbot, void* ptop)
Add range to scan for roots.

void removeRange(void* pbot)
Remove range.

void fullCollect()
Run a full garbage collection cycle. The collector normally runs synchronously with a storage allocation request (i.e. it never happens when in code that does not allocate memory). In some circumstances, for example when a particular task is finished, it is convenient to explicitly run the collector and free up all memory used by that task. It can also be helpful to run a collection before starting a new task that would be annoying if it ran a collection in the middle of that task. Explicitly running a collection can also be done in a separate very low priority thread, so that if the program is idly waiting for input, memory can be cleaned up.

void genCollect()
Run a generational garbage collection cycle. Takes less time than a fullCollect(), but isn't as effective.

void minimize()
Minimize physical memory usage.

void disable()
Temporarilly disable garbage collection cycle. This is used for brief time critical sections of code, so the amount of time it will take is predictable. If the collector runs out of memory while it is disabled, it will throw an OutOfMemory exception. The disable() function calls can be nested, but must be matched with corresponding enable() calls.

void enable()
Reenable garbage collection cycle after being disabled with disable(). It is an error to call more enable()s than disable()s.

std.intrinsic

Intrinsic functions are functions built in to the compiler, usually to take advantage of specific CPU features that are inefficient to handle via external functions. The compiler's optimizer and code generator are fully integrated in with intrinsic functions, bringing to bear their full power on them. This can result in some surprising speedups.
int bsf(uint v)
Scans the bits in v starting with bit 0, looking for the first set bit.
int bsr(uint v)
Scans the bits in v from the most significant bit to the least significant bit, looking for the first set bit.

Both return the bit number of the first set bit. The return value is undefined if v is zero.

Example

	
	import std.intrinsic;

	int main()
	{   
	    uint v;
	    int x;

	    v = 0x21;
	    x = bsf(v);
	    printf("bsf(x%x) = %d\n", v, x);
	    x = bsr(v);
	    printf("bsr(x%x) = %d\n", v, x);
	    return 0;
	} 
	
	
Output
	bsf(x21) = 0
	bsr(x21) = 5
	
int bt(uint* p, uint index)
Tests the bit.
int btc(uint* p, uint index)
Tests and complements the bit.
int btr(uint* p, uint index)
Tests and resets (sets to 0) the bit.
int bts(uint* p, uint index)
Tests and sets the bit.

p is a non-NULL pointer to an array of uints. index is a bit number, starting with bit 0 of p[0], and progressing. It addresses bits like the expression:

	p[index / (uint.size*8)] & (1 << (index & ((uint.size*8) - 1)))
	

All return a non-zero value if the bit was set, and a zero if it was clear.

Example

	
	import std.intrinsic;

	int main()
	{   
	    uint array[2];

	    array[0] = 2;
	    array[1] = 0x100;

	    printf("btc(array, 35) = %d\n", btc(array, 35));
	    printf("array = [0]:x%x, [1]:x%x\n", array[0], array[1]);

	    printf("btc(array, 35) = %d\n", btc(array, 35));
	    printf("array = [0]:x%x, [1]:x%x\n", array[0], array[1]);

	    printf("bts(array, 35) = %d\n", bts(array, 35));
	    printf("array = [0]:x%x, [1]:x%x\n", array[0], array[1]);

	    printf("btr(array, 35) = %d\n", btr(array, 35));
	    printf("array = [0]:x%x, [1]:x%x\n", array[0], array[1]);

	    printf("bt(array, 1) = %d\n", bt(array, 1));
	    printf("array = [0]:x%x, [1]:x%x\n", array[0], array[1]);

	    return 0;
	} 

Output
	btc(array, 35) = 0
	array = [0]:x2, [1]:x108
	btc(array, 35) = -1
	array = [0]:x2, [1]:x100
	bts(array, 35) = 0
	array = [0]:x2, [1]:x108
	btr(array, 35) = -1
	array = [0]:x2, [1]:x100
	bt(array, 1) = -1
	array = [0]:x2, [1]:x100
uint bswap(uint x)
Swaps bytes in a 4 byte uint end-to-end, i.e. byte 0 becomes byte 3, byte 1 becomes byte 2, byte 2 becomes byte 1, byte 3 becomes byte 0.

ubyte inp(uint port_address)
ushort inpw(uint port_address)
uint inpl(uint port_address)
Reads I/O port at port_address.

ubyte outp(uint port_address, ubyte value)
ushort outpw(uint port_address, ushort value)
uint outpl(uint port_address, uint value)
Writes and returns value to I/O port at port_address.

real cos(real)
real fabs(real)
real rint(real)
long rndtol(real)
real sin(real)
real sqrt(real)
Intrinsic verions of the math functions of the same name.

std.math

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

real acos(real)
real asin(real)
real atan(real)
real atan2(real, real)

real cos(real x)
Compute cosine of x. x is in radians.
Special values:
x return value invalid?
±INFINITY NAN yes

real sin(real x)
Compute sine of x. x is in radians.
Special values:
x return value invalid?
±0.0 ±0.0 no
±INFINITY NAN yes

real tan(real x)
Compute tangent of x. x is in radians.
Special values:
x return value invalid?
±0.0 ±0.0 no
±INFINITY NAN yes

real cosh(real)
real sinh(real)
real tanh(real)
real exp(real)

real frexp(real value, out int exp)
Calculate and return x and exp such that:
value=x*2exp
.5 <= |x| < 1.0
x has same sign as value.
Special values:
value x exp
+-0.0 +-0.0 0
+INFINITY +INFINITY int.max
-INFINITY -INFINITY int.min
+-NAN +-NAN int.min

real ldexp(real n, int exp)
Compute n * 2exp

real log(real x)
Calculate the natural logarithm of x.
Special values:
x return value divide by 0? invalid?
±0.0 -INFINITY yes no
< 0.0 NAN no yes
+INFINITY +INFINITY no no

real log10(real x)
Calculate the base-10 logarithm of x.
Special values:
x return value divide by 0? invalid?
±0.0 -INFINITY yes no
< 0.0 NAN no yes
+INFINITY +INFINITY no no

real modf(real, real*)

real pow(real, real)

real sqrt(real x)
creal sqrt(creal x)
Compute square root of x.
Special values:
x return value invalid?
-0.0 -0.0 no
<0.0 NAN yes
+INFINITY +INFINITY no

real ceil(real)
real floor(real)

real log1p(real x)
Calculates the natural logarithm of 1 + x. For very small x, log1p(x) will be more accurate than log(1 + x).
Special values:
x log1p(x) divide by 0? invalid?
±0.0 ±0.0 no no
-1.0 -INFINITY yes no
<-1.0 NAN no yes
+INFINITY -INFINITY no no

real expm1(real x)
Calculates the value of the natural logarithm base (e) raised to the power of x, minus 1. For very small x, expm1(x) is more accurate than exp(x)-1.
Special values:
x ex-1
±0.0 ±0.0
+INFINITY +INFINITY
-INFINITY -1.0

real atof(char*)
Math functions.

real hypot(real x, real y)
Calculates the length of the hypotenuse of a right-angled triangle with sides of length x and y. The hypotenuse is the value of the square root of the sums of the squares of x and y:
	sqrt(x2 + y2)
Note that hypot(x,y), hypot(y,x) and hypot(x,-y) are equivalent.
Special values:
x y return value invalid?
x +-0.0 fabs(x) no
+-INFINITY y +INFINITY no
+-INFINITY NAN +INFINITY no

int isnan(real e)
Is number a nan?

int isfinite(real e)
Is number finite?

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

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

int isinf(real e)
Is number infinity?

int signbit(real e)
Get sign bit.

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


std.md5

Computes MD5 digests of arbitrary data. MD5 digests are 16 byte quantities that are like a checksum or crc, but are more robust.

There are two ways to do this. The first does it all in one function call to sum(). The second is for when the data is buffered.

The routines and algorithms are derived from the RSA Data Security, Inc. MD5 Message-Digest Algorithm.

void sum(ubyte[16] digest, void[] data)
Compute MD5 digest from data.

void printDigest(ubyte[16] digest)
Print MD5 digest to standard output.

struct MD5_CTX
Use when data to be digested is buffered.

void start()
Begins an MD5 message-digest operation.

void update(void[] input)
Continues an MD5 message-digest operation, processing another message block input, and updating the context.

void finish(ubyte[16] digest)
Ends an MD5 message-digest operation and writes the result to digest.

Example

// This code is derived from the
// RSA Data Security, Inc. MD5 Message-Digest Algorithm.

import std.md5;
import std.string;
import std.c.stdio;

int main(char[][] args)
{
    for (int i = 1; i < args.length; i++)
	 MDFile(args[i]);
    return 0;
}

/* Digests a file and prints the result. */
void MDFile(char[] filename)
{
    FILE* file;
    MD5_CTX context;
    int len;
    ubyte [4 * 1024] buffer;
    ubyte digest[16];

    if ((file = fopen(std.string.toStringz(filename), "rb")) == null)
	printf("%.*s can't be opened\n", filename);
    else
    {
	context.start();
	while ((len = fread(buffer, 1, buffer.size, file)) != 0)
	    context.update(buffer[0 .. len]);
	context.finish(digest);
	fclose(file);

	printf("MD5 (%.*s) = ", filename);
	printDigest(digest);
	printf("\n");
    }
}

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


std.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(real 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.


std.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(dchar c1, dchar 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


std.process

int system(char[] command)
Execute command in a command shell. Returns exit status of command.

int execv(char[] program, char[][] arguments)
int execve(char[] program, char[][] arguments, char[][] environment)
int execvp(char[] program, char[][] arguments)
int execvpe(char[] program, char[][] arguments, char[][] environment)
Execute program, passing it the arguments and the environment, returning the exit status. The 'p' versions of exec search the PATH environment variable setting for program.


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


std.socketstream

class SocketStream : std.stream.Stream
SocketStream is a stream for a blocking, connected Socket.

this(Socket sock, std.stream.FileMode mode)
Constructs a SocketStream with the specified Socket and FileMode flags.
this(Socket sock)
Uses mode FileMode.In | FileMode.Out.

Socket socket
Property to get the Socket that is being streamed.

uint readBlock(void* buffer, uint size)
Attempts to read the entire block, waiting if necessary.

char[] readLine()
wchar[] readLineW()
Read a line. Safely does not use ungetc/ungetcw.

uint writeBlock(void* buffer, uint size)
Attempts to write the entire block, waiting if necessary.

bit eof()
Returns true if a remote disconnection has been detected.

char[] toString()
Does not return the entire stream because that would require the remote connection to be closed.

void close()
Close the Socket.

Notes

For Win32 systems, link with ws2_32.lib.

Example

See /dmd/samples/d/htmlget.d.

std.stdint

D constrains integral types to specific sizes. But efficiency of different sizes varies from machine to machine, pointer sizes vary, and the maximum integer size varies. stdint offers a portable way of trading off size vs efficiency, in a manner compatible with the stdint.h definitions in C.

The exact aliases are types of exactly the specified number of bits. The at least aliases are at least the specified number of bits large, and can be larger. The fast aliases are the fastest integral type supported by the processor that is at least as wide as the specified number of bits.

The aliases are:

Exact Alias Description At Least Alias Description Fast Alias Description
int8_t exactly 8 bits signed int_least8_t at least 8 bits signed int_fast8_t fast 8 bits signed
uint8_t exactly 8 bits unsigned uint_least8_t at least 8 bits unsigned uint_fast8_t fast 8 bits unsigned
int16_t exactly 16 bits signed int_least16_t at least 16 bits signed int_fast16_t fast 16 bits signed
uint16_t exactly 16 bits unsigned uint_least16_t at least 16 bits unsigned uint_fast16_t fast 16 bits unsigned
int32_t exactly 32 bits signed int_least32_t at least 32 bits signed int_fast32_t fast 32 bits signed
uint32_t exactly 32 bits unsigned uint_least32_t at least 32 bits unsigned uint_fast32_t fast 32 bits unsigned
int64_t exactly 64 bits signed int_least64_t at least 64 bits signed int_fast64_t fast 64 bits signed
uint64_t exactly 64 bits unsigned uint_least64_t at least 64 bits unsigned uint_fast64_t fast 64 bits unsigned

The ptr aliases are integral types guaranteed to be large enough to hold a pointer without losing bits:

Alias Description
intptr_t signed integral type large enough to hold a pointer
uintptr_t unsigned integral type large enough to hold a pointer

The max aliases are the largest integral types:

Alias Description
intmax_t the largest signed integral type
uintmax_t the largest unsigned integral type


std.stdio

Standard I/O functions that extend std.c.stdio. std.c.stdio is automatically imported when importing std.stdio.
void writef(...);
Arguments are formatted per the format strings and written to stdout.

void writefln(...);
Same as writef, but a newline is appended to the output.

void fwritef(FILE* fp, ...);
Same as writef, but output is sent to the stream fp instead of stdout.

void fwritefln(FILE* fp, ...);
Same as writefln, but output is sent to the stream fp instead of stdout.


std.stream

interface InputStream
InputStream is the interface for readable streams.

void readExact(void* buffer, uint size)
Read exactly size bytes into the buffer, throwing a ReadException if it is not correct.

uint read(ubyte[] buffer)
Read a block of data big enough to fill the given array and return the actual number of bytes read. Unfilled bytes are not modified.

void read(out byte x)
void read(out ubyte x)
void read(out short x)
void read(out ushort x)
void read(out int x)
void read(out uint x)
void read(out long x)
void read(out ulong x)
void read(out float x)
void read(out double x)
void read(out real x)
void read(out ifloat x)
void read(out idouble x)
void read(out ireal x)
void read(out cfloat x)
void read(out cdouble x)
void read(out creal x)
void read(out char x)
void read(out wchar x)
void read(out dchar x)
void read(out char[] s)
void read(out wchar[] s)
Read a basic type or counted string, throwing a ReadException if it could not be read. Outside of byte, ubyte, and char, the format is implementation-specific and should not be used except as opposite actions to write.

char[] readLine()
char[] readLine(char[] buffer)
wchar[] readLineW()
wchar[] readLineW(wchar[] buffer)
Read a line that is terminated with some combination of carriage return and line feed or end-of-file. The terminators are not included. The wchar version is identical. When a buffer is supplied as a parameter it is filled unless the content does not fit in the buffer, in which case a new buffer is allocated, filled and returned.

char[] readString(uint length)
Read a string of the given length, throwing ReadException if there was a problem.

wchar[] readStringW(uint length)
Read a string of the given length, throwing ReadException if there was a problem. The file format is implementation-specific and should not be used except as opposite actions to write.

char getc()
wchar getcw()
Read and return the next character in the stream. This is the only method that will handle ungetc properly. getcw's format is implementation-specific.

char ungetc(char c)
wchar ungetcw(wchar c)
Push a character back onto the stream. They will be returned in first-in last-out order from getc/getcw.

int scanf(char[] fmt, ...)
int vscanf(char[] fmt, va_list args)
Scan a string from the input using a similar form to C's scanf.

uint available()
Retrieve the nubmer of bytes available for immediate reading.


interface OutputStream
OutputStream is the interface for writable streams.

void writeExact(void* buffer, uint size)
Write exactly size bytes from buffer, or throw a WriteException if that could not be done.

uint write(ubyte[] buffer)
Write as much of the buffer as possible, returning the number of bytes written.

void write(byte x)
void write(ubyte x)
void write(short x)
void write(ushort x)
void write(int x)
void write(uint x)
void write(long x)
void write(ulong x)
void write(float x)
void write(double x)
void write(real x)
void write(ifloat x)
void write(idouble x)
void write(ireal x)
void write(cfloat x)
void write(cdouble x)
void write(creal x)
void write(char x)
void write(wchar x)
void write(dchar x)
void write(char[] s)
void write(wchar[] s)
Write a basic type or counted string. Outside of byte, ubyte, and char, the format is implementation-specific and should only be used in conjunction with read.

void writeLine(char[] s)
Write a line of text, appending the line with an operating-system-specific line ending.

void writeLineW(wchar[] s)
Write a line of text, appending the line with an operating-system-specific line ending. The format is implementation-specific.

void writeString(char[] s)
Write a string of text, throwing WriteException if it could not be fully written.

void writeStringW(wchar[] s)
Write a string of text, throwing WriteException if it could not be fully written. The format is implementation-dependent.

uint printf(char[] format, ...)
uint vprintf(char[] format, va_list args)
Print a formatted string into the stream using printf-style syntax, returning the number of bytes written.

void writef(...)
void writefln(...)
Print a formatted string into the stream using writef-style syntax. See std.format


class Stream : InputStream,OutputStream
Stream is the base abstract class from which the other stream classes derive. Stream's byte order is the format native to the computer.

bit readable
Indicates whether this stream can be read from.

bit writeable
Indicates whether this stream can be written to.

bit seekable
Indicates whether this stream can be seeked within.

Reading

These methods require that the readable flag be set. Problems with reading result in a ReadException being thrown. Stream implements the InputStream interface in addition to the following methods.

uint readBlock(void* buffer, uint size)
Read up to size bytes into the buffer and return the number of bytes actually read.

Writing

These methods require that the writeable flag be set. Problems with writing result in a WriteException being thrown. Stream implements the OutputStream interface in addition to the following methods.

uint writeBlock(void* buffer, uint size)
Write up to size bytes from buffer in the stream, returning the actual number of bytes that were written.

void copyFrom(Stream s)
Copies all data from s into this stream. This may throw ReadException or WriteException on failure. This restores the file position of s so that it is unchanged.
void copyFrom(Stream s, uint count)
Copy a specified number of bytes from the given stream into this one. This may throw ReadException or WriteException on failure. Unlike the previous form, this doesn't restore the file position of s.

Seeking

These methods require that the seekable flag be set. Problems with seeking result in a SeekException being thrown.

ulong seek(long offset, SeekPos whence)
Change the current position of the stream. whence is either SeekPos.Set, in which case the offset is an absolute index from the beginning of the stream, SeekPos.Current, in which case the offset is a delta from the current position, or SeekPos.End, in which case the offset is a delta from the end of the stream (negative or zero offsets only make sense in that case). This returns the new file position.

ulong seekSet(long offset)
ulong seekCur(long offset)
ulong seekEnd(long offset)
Aliases for their normal seek counterparts.

ulong position()
void position(ulong pos)
Retrieve or set the file position, identical to calling seek(0, SeekPos.Current) or seek(pos, SeekPos.Set) respectively.

ulong size()
Retrieve the size of the stream in bytes.

bit eof()
Return whether the current file position is the same as the end of the file. This does not require actually reading past the end of the file, as with stdio.

bit isOpen()
Return true if the stream is currently open.

void flush()
Flush pending output if appropriate.

void close()
Close the stream, flushing output if appropriate.

char[] toString()
Read the entire stream and return it as a string.

uint toHash()
Get a hash of the stream by reading each byte and using it in a CRC-32 checksum.


class BufferedStream : Stream
This subclass is for buffering a source stream. A buffered stream must be closed explicitly to ensure the final buffer content is written to the source stream.

this(Stream source, uint bufferSize = 8192)
Create a buffered stream for the stream source with the buffer size bufferSize.

class File : Stream
This subclass is for file system streams.

this()
this(char[] filename, FileMode mode = FileMode.In)
Create the stream with no open file, an open file in read mode, or an open file with explicit file mode. mode, if given, is a combination of FileMode.In (indicating a file that can be read) and FileMode.Out (indicating a file that can be written). Opening a file for reading that doesn't exist will error. Opening a file for writing that doesn't exist will create the file. The FileMode.OutNew mode will open the file for writing and reset the legnth to zero. The FileMode.Append mode will open the file for writing and move the file position to the end of the file.

void open(char[] filename, FileMode mode = FileMode.In)
Open a file for the stream, in an identical manner to the constructors.

void create(char[] filename, FileMode mode = FileMode.OutNew)
Create a file for the stream.

void close()
Close the current file if it is open; otherwise it does nothing.

uint readBlock(void* buffer, uint size)
uint writeBlock(void* buffer, uint size)
ulong seek(long offset, SeekPos rel)
Overrides of the Stream methods.


class BufferedFile : BufferedStream
This subclass is for buffered file system streams. It is a convenience class for wrapping a File in a BufferedStream. A buffered stream must be closed explicitly to ensure the final buffer content is written to the file.

this()
this(char[] filename, FileMode mode = FileMode.In, uint buffersize = 8192)
this(File file, uint buffersize = 8192)
void open(char[] filename, FileMode mode = FileMode.In)
void create(char[] filename, FileMode mode = FileMode.OutNew)
void close()
uint readBlock(void* buffer, uint size)
uint writeBlock(void* buffer, uint size)
ulong seek(long offset, SeekPos rel)
Overrides of the Stream methods.


enum BOM
UTF byte-order-mark signatures
UTF8
UTF-8
UTF16LE
UTF-16 Little Endian
UTF16BE
UTF-16 Big Endian
UTF32LE
UTF-32 Little Endian
UTF32BE
UTF-32 Big Endian

class EndianStream : Stream
This subclass wraps a stream with big-endian or little-endian byte order swapping. UTF Byte-Order-Mark (BOM) signatures can be read and deduced or written.

this(Stream source, Endian end = std.system.endian)
Create the endian stream for the source stream source with endianness end. The default endianness is the native byte order. The Endian type is defined in the std.system module.
Endian endian
property for endianness of the source stream
int readBOM(int ungetCharSize = 1)
Return -1 if no BOM and otherwise read the BOM and return it. If there is no BOM or if bytes beyond the BOM are read then the bytes read are pushed back onto the ungetc buffer or ungetcw buffer. Pass ungetCharSize == 2 to use ungetcw instead of ungetc when no BOM is present.
void writeBOM(BOM b)
Write the BOM b to the source stream
final void fixBO(void* buffer, uint size)
fix the byte order of the given buffer to match the native order


class TArrayStream(Buffer) : Stream
This subclass wraps an array-like buffer with a stream interface. The type Buffer must support the length property and reading ubyte slices.

this(Buffer buf)
Create the stream for the the buffer buf.
uint readBlock(void* buffer, uint size)
uint writeBlock(void* buffer, uint size)
ulong seek(long offset, SeekPos rel)
char[] toString()
Overrides of Stream methods.


class MemoryStream : TArrayStream!(ubyte[])
This subclass reads and constructs an array of bytes in memory.

this()
this(ubyte[] data)
Create the output buffer and setup for reading, writing, and seeking. The second constructor loads it with specific input data.

ubyte[] data()
Get the current memory data in total.

uint readBlock(void* buffer, uint size)
uint writeBlock(void* buffer, uint size)
ulong seek(long offset, SeekPos rel)
char[] toString()
Overrides of Stream methods.


class SliceStream : Stream
This subclass slices off a portion of another stream, making seeking relative to the boundaries of the slice. It could be used to section a large file into a set of smaller files, such as with tar archives.

this(Stream base, int low)
Indicate both the base stream to use for reading from and the low part of the slice. The high part of the slice is dependent upon the end of the base stream, so that if you write beyond the end it resizes the stream normally.

this(Stream base, int low, int high)
Indicate the high index as well. Attempting to read or write past the high index results in the end being clipped off.

uint readBlock(void* buffer, uint size)
uint writeBlock(void* buffer, uint size)
ulong seek(long offset, SeekPos rel)
Overrides of Stream methods.

std.system

enum Endian
Byte order endianness
BigEndian
big endian byte order
LittleEndian
little endian byte order

Endian endian
Native system endianness

std.thread

The thread module defines the class Thread. Thread is the basis for writing multithreaded applications. Each thread has a unique instance of class Thread associated with it. It is important to use the Thread class to create and manage threads as the garbage collector needs to know about all the threads.

typedef ... thread_hdl
The type of the thread handle used by the operating system.

class Thread
One for each thread.

class ThreadError
Thrown for errors.

The members of Thread are:

this()
Constructor used by classes derived from Thread that override main().

this(int (*fp)(void*), void* arg)
Constructor used by classes derived from Thread that override run().

this(int delegate() dg)
Constructor used by classes derived from Thread that override run().

thread_hdl hdl;
The handle to this thread assigned by the operating system. This is set to thread_id.init if the thread hasn't been started yet.

void start();
Create a new thread and start it running. The new thread initializes itself and then calls run(). start() can only be called once.

int run(void* p);
Entry point for a thread. If not overridden, it calls the function pointer fp and argument arg passed in the constructor, or the delegate dg. The return value is the thread exit code, which is normally 0.

void wait();
Wait for this thread to terminate. Throws ThreadError if the thread hasn't begun yet or has already terminated or is called on itself.

void wait(unsigned milliseconds);
Wait for this thread to terminate or until milliseconds time has elapsed, whichever occurs first. Throws ThreadError if the thread hasn't begun yet or has already terminated or is called on itself.

TS getState();
Returns the state of the thread. The state is one of the following:

TS Description
INITIAL The thread hasn't been started yet.
RUNNING The thread is running or paused.
TERMINATED The thread has ended.

void setPriority(PRIORITY* p);
Adjust the priority of this thread.

PRIORITY Description
INCREASE Increase thread priority
DECREASE Decrease thread priority
IDLE Assign thread low priority
CRITICAL Assign thread high priority

static Thread getThis();
Returns a reference to the Thread for the thread that called the function.

static Thread[] getAll();
Returns an array of all the threads currently running.

void pause();
Suspend execution of this thread.

void resume();
Resume execution of this thread.

static void pauseAll();
Suspend execution of all threads but this thread.

static void resumeAll();
Resume execution of all paused threads.

static void yield();
Give up the remainder of this thread's time slice.


std.uri

Encode and decode Uniform Resource Identifiers (URIs). URIs are used in internet transfer protocols. Valid URI characters consist of letters, digits, and the characters ;/?:@&=+$,-_.!~*'(). Escape sequences consist of '%' followed by two hex digits.
char[] decode(char[] encodedURI)
Decodes the URI string encodedURI into a UTF-8 string and returns it. Escape sequences that resolve to valid URI characters are not replaced. Escape sequences that resolve to the '#' character are not replaced.

char[] decodeComponent(char[] encodedURIComponent)
Decodes the URI string encodedURI into a UTF-8 string and returns it. All escape sequences are decoded.

char[] encode(char[] uri)
Encodes the UTF-8 string uri into a URI and returns that URI. Any character not a valid URI character is escaped. The '#' character is not escaped.

char[] encodeComponent(char[] uriComponent)
Encodes the UTF-8 string uri into a URI and returns that URI. Any character not a letter, digit, or one of -_.!~*'() is escaped.

std.utf

Encode and decode UTF-8, UTF-16 and UTF-32 strings. For more information on UTF-8, see http://www.cl.cam.ac.uk/~mgk25/unicode.html#utf-8.

Note: For Win32 systems, the C wchar_t type is UTF-16 and corresponds to the D wchar type. For linux systems, the C wchar_t type is UTF-32 and corresponds to the D utf.dchar type.

UTF character support is restricted to (0 <= character <= 0x10FFFF).

class UtfError
Exception class that is thrown upon any errors. The members are:
idx
Set to the index of the start of the offending UTF sequence.

alias ... dchar
An alias for a single UTF-32 character. This may become a D basic type in the future.

bit isValidDchar(dchar c)
Test if c is a valid UTF-32 character. Returns true if it is, false if not.

dchar decode(char[] s, inout uint idx)
dchar decode(wchar[] s, inout uint idx)
dchar decode(dchar[] s, inout uint idx)
Decodes and returns character starting at s[idx]. idx is advanced past the decoded character. If the character is not well formed, a UriError is thrown and idx remains unchanged.

void encode(inout char[] s, dchar c)
void encode(inout wchar[] s, dchar c)
void encode(inout dchar[] s, dchar c)
Encodes character c and appends it to array s.

void validate(char[] s)
void validate(wchar[] s)
void validate(dchar[] s)
Checks to see if string is well formed or not. Throws a UtfError if it is not. Use to check all untrusted input for correctness.

char[] toUTF8(char[] s)
char[] toUTF8(wchar[] s)
char[] toUTF8(dchar[] s)
Encodes string s into UTF-8 and returns the encoded string.

wchar[] toUTF16(char[] s)
wchar* toUTF16z(char[] s)
wchar[] toUTF16(wchar[] s)
wchar[] toUTF16(dchar[] s)
Encodes string s into UTF-16 and returns the encoded string. toUTF16z is suitable for calling the 'W' functions in the Win32 API that take an LPWSTR or LPCWSTR argument.

dchar[] toUTF32(char[] s)
dchar[] toUTF32(wchar[] s)
dchar[] toUTF32(dchar[] s)
Encodes string s into UTF-32 and returns the encoded string.

std.zip

Read/write data in the zip archive format. Makes use of the zlib compression library.
class ZipException
Thrown on error.

class ZipArchive
Object representing the entire archive. ZipArchives are collections of ArchiveMembers.

this()
Constructor used when creating a new archive.

void addMember(ArchiveMember de)
Add de to the archive.

void deleteMember(ArchiveMember de)
Delete de from the archive.

void[] build()
Construct an archive out of the current members of the archive. Fills in the properties data[], diskNumber, diskStartDir, numEntries, totalEntries, and directory[]. For each ArchiveMember, fills in properties crc32, compressedSize, compressedData[]. Return array representing the entire archive.

this(void[] data)
Constructor used when reading an existing archive. data[] is the entire contents of the archive. Fills in the properties data[], diskNumber, diskStartDir, numEntries, totalEntries, comment[], and directory[]. For each ArchiveMember, fills in properties madeVersion, extractVersion, flags, compressionMethod, time, crc32, compressedSize, expandedSize, compressedData[], diskNumber, internalAttributes, externalAttributes, name[], extra[], comment[]. Use expand() to get the expanded data for each ArchiveMember.

ubyte[] expand(ArchiveMember de)
Decompress the contents of archive member de and return the expanded data. Fills in properties extractVersion, flags, compressionMethod, time, crc32, compressedSize, expandedSize, expandedData[], name[], extra[].

ubyte[] data
Read Only: array representing the entire contents of the archive.

uint diskNumber
Read Only: 0 since multi-disk zip archives are not supported.

uint diskStartDir
Read Only: 0 since multi-disk zip archives are not supported.

uint numEntries
Read Only: number of ArchiveMembers in the directory.

uint totalEntries
Read Only: same as totalEntries.

char[] comment
Read/Write: the archive comment. Must be less than 65536 bytes in length.

ArchiveMember[char[]] directory
Read Only: array indexed by the name of each member of the archive. All the members of the archive can be accessed with a foreach loop:
ZipArchive archive = new ZipArchive(data);
foreach (ArchiveMember am; archive)
{
    printf("member name is '%.*s'\n", am.name);
}

class ArchiveMember
A member of the ZipArchive.

ushort madeVersion
Read Only

ushort extractVersion
Read Only

ushort flags
Read/Write: normally set to 0

ushort compressionMethod
Read/Write: the only supported values are 0 (no compression) and 8 (deflate).

date.DosFileTime time
Read/Write: Last modified time of the member. It's in the DOS date/time format.

uint crc32
Read Only: cyclic redundancy check (CRC) value

uint compressedSize
Read Only: size of data of member in compressed form.

uint expandedSize
Read Only: size of data of member in expanded form.

ushort diskNumber
Read Only: should be 0.

ushort internalAttributes
Read/Write

uint externalAttributes
Read/Write

char[] name
Read/Write: Usually the file name of the archive member; it is used to index the archive directory for the member. Each member must have a unique name[]. Do not change without removing member from the directory first.

ubyte[] extra
Read/Write: extra data for this member.

char[] comment
Read/Write: comment associated with this member.

ubyte[] compressedData
Read Only: data of member in compressed form.

ubyte[] expandedData
Read/Write: data of member in uncompressed form.
Bugs:

std.zlib

Compress / decompress data using the zlib library.
uint adler32(uint adler, void[] buf)
Compute the Adler32 checksum of the data in buf[]. adler is the starting value when computing a cumulative checksum.

uint crc32(uint crc, void[] buf)
Compute the CRC32 checksum of the data in buf[]. crc is the starting value when computing a cumulative checksum.

class ZlibException
Thrown in the case of errors occurring in the following:

void[] compress(void[] buf)
void[] compress(void[] buf, int level)
Compresses the data in buf[] using compression level level. The default value for level is 6, legal values are 1..9, with 1 being the least compression and 9 being the most. Returns the compressed data.

void[] uncompress(void[] buf)
void[] uncompress(void[] buf, uint destbufsize)
Decompresses the data in buf[]. destbufsize is the size of the uncompressed data. It need not be accurate, but the decompression will be faster if the exact size is supplied. Returns the decompressed data.

class Compress
Used when the data to be compressed is not all in one buffer.

this()
this(int level)
Construct. level is the same as for D.zlib.compress().

void[] compress(void[] buf)
Compress the data in buf and return the compressed data. The buffers returned from successive calls to this should be concatenated together.

void[] flush()
void[] flush(int mode)
Compress and return any remaining data. The returned data should be appended to that returned by compress(). mode is one of the following:
Z_SYNC_FLUSH
Syncs up flushing to the next byte boundary. Used when more data is to be compressed later on.
Z_FULL_FLUSH
Syncs up flushing to the next byte boundary. Used when more data is to be compressed later on, and the decompressor needs to be restartable at this point.
Z_FINISH (default)
Used when finished compressing the data.

class UnCompress
Used when the data to be decompressed is not all in one buffer.

this()
this(uint destbufsize)
Construct. destbufsize is the same as for D.zlib.uncompress().

void[] uncompress(void[] buf)
Decompress the data in buf and return the decompressed data. The buffers returned from successive calls to this should be concatenated together.

void[] flush()
Decompress and return any remaining data. The returned data should be appended to that returned by uncompress(). The UnCompress object cannot be used further.


std.c.stdio

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

Feedback and Comments

Add feedback and comments regarding this page.
Copyright (c) 1999-2007 by Digital Mars, All Rights Reserved