Report a bug
If you spot a problem with this page, click here to create a Bugzilla issue.
Improve this page
Quickly fork, edit online, and submit a pull request for this page. Requires a signed-in GitHub account. This works well for small changes. If you'd like to make larger changes you may want to consider using a local clone.

std.conv

A one-stop shop for converting values from one type to another.
Category Functions
Generic asOriginalType castFrom emplace parse to toChars
Strings text wtext dtext hexString
Numeric octal roundTo signed unsigned
Exceptions ConvException ConvOverflowException
Authors:
Walter Bright, Andrei Alexandrescu, Shin Fujishiro, Adam D. Ruppe, Kenji Hara

Source std/conv.d

public import std.ascii : LetterCase;
class ConvException: object.Exception;
Thrown on conversion errors.
Examples:
import std.exception : assertThrown;
assertThrown!ConvException(to!int("abc"));
class ConvOverflowException: std.conv.ConvException;
Thrown on conversion overflow errors.
Examples:
import std.exception : assertThrown;
assertThrown!ConvOverflowException(to!ubyte(1_000_000));
template to(T)
The to template converts a value from one type to another. The source type is deduced and the target type must be specified, for example the expression to!int(42.0) converts the number 42 from double to int. The conversion is "safe", i.e., it checks for overflow; to!int(4.2e10) would throw the ConvOverflowException exception. Overflow checks are only inserted when necessary, e.g., to!double(42) does not do any checking because any int fits in a double.
Conversions from string to numeric types differ from the C equivalents atoi() and atol() by checking for overflow and not allowing whitespace.
For conversion of strings 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
Examples:
Converting a value to its own type (useful mostly for generic code) simply returns its argument.
int a = 42;
int b = to!int(a);
double c = to!double(3.14); // c is double with value 3.14
Examples:
Converting among numeric types is a safe way to cast them around.
Conversions from floating-point types to integral types allow loss of precision (the fractional part of a floating-point number). The conversion is truncating towards zero, the same way a cast would truncate. (To round a floating point value when casting to an integral, use roundTo.)
import std.exception : assertThrown;

int a = 420;
writeln(to!long(a)); // a
assertThrown!ConvOverflowException(to!byte(a));

writeln(to!int(4.2e6)); // 4200000
assertThrown!ConvOverflowException(to!uint(-3.14));
writeln(to!uint(3.14)); // 3
writeln(to!uint(3.99)); // 3
writeln(to!int(-3.99)); // -3
Examples:
When converting strings to numeric types, note that the D hexadecimal and binary literals are not handled. Neither the prefixes that indicate the base, nor the horizontal bar used to separate groups of digits are recognized. This also applies to the suffixes that indicate the type.
To work around this, you can specify a radix for conversions involving numbers.
auto str = to!string(42, 16);
writeln(str); // "2A"
auto i = to!int(str, 16);
writeln(i); // 42
Examples:
Conversions from integral types to floating-point types always succeed, but might lose accuracy. The largest integers with a predecessor representable in floating-point format are 2^24-1 for float, 2^53-1 for double, and 2^64-1 for real (when real is 80-bit, e.g. on Intel machines).
// 2^24 - 1, largest proper integer representable as float
int a = 16_777_215;
writeln(to!int(to!float(a))); // a
writeln(to!int(to!float(-a))); // -a
Examples:
Conversion from string types to char types enforces the input to consist of a single code point, and said code point must fit in the target type. Otherwise, ConvException is thrown.
import std.exception : assertThrown;

writeln(to!char("a")); // 'a'
assertThrown(to!char("ñ")); // 'ñ' does not fit into a char
writeln(to!wchar("ñ")); // 'ñ'
assertThrown(to!wchar("😃")); // '😃' does not fit into a wchar
writeln(to!dchar("😃")); // '😃'

// Using wstring or dstring as source type does not affect the result
writeln(to!char("a"w)); // 'a'
writeln(to!char("a"d)); // 'a'

// Two code points cannot be converted to a single one
assertThrown(to!char("ab"));
Examples:
Converting an array to another array type works by converting each element in turn. Associative arrays can be converted to associative arrays as long as keys and values can in turn be converted.
import std.string : split;

int[] a = [1, 2, 3];
auto b = to!(float[])(a);
writeln(b); // [1.0f, 2, 3]
string str = "1 2 3 4 5 6";
auto numbers = to!(double[])(split(str));
writeln(numbers); // [1.0, 2, 3, 4, 5, 6]
int[string] c;
c["a"] = 1;
c["b"] = 2;
auto d = to!(double[wstring])(c);
assert(d["a"w] == 1 && d["b"w] == 2);
Examples:
Conversions operate transitively, meaning that they work on arrays and associative arrays of any complexity.
This conversion works because to!short applies to an int, to!wstring applies to a string, to!string applies to a double, and to!(double[]) applies to an int[]. The conversion might throw an exception because to!short might fail the range check.
int[string][double[int[]]] a;
auto b = to!(short[wstring][string[double[]]])(a);
Examples:
Object-to-object conversions by dynamic casting throw exception when the source is non-null and the target is null.
import std.exception : assertThrown;
// Testing object conversions
class A {}
class B : A {}
class C : A {}
A a1 = new A, a2 = new B, a3 = new C;
assert(to!B(a2) is a2);
assert(to!C(a3) is a3);
assertThrown!ConvException(to!B(a3));
Examples:
Stringize conversion from all types is supported.
  • String to string conversion works for any two string types having (char, wchar, dchar) character widths and any combination of qualifiers (mutable, const, or immutable).
  • Converts array (other than strings) to string. Each element is converted by calling to!T.
  • Associative array to string conversion. Each element is printed by calling to!T.
  • Object to string conversion calls toString against the object or returns "null" if the object is null.
  • Struct to string conversion calls toString against the struct if it is defined.
  • For structs that do not define toString, the conversion to string produces the list of fields.
  • Enumerated types are converted to strings as their symbolic names.
  • Boolean values are printed as "true" or "false".
  • char, wchar, dchar to a string type.
  • Unsigned or signed integers to strings.
    [special case]
    Convert integral value to string in radix radix. radix must be a value from 2 to 36. value is treated as a signed value only if radix is 10. The characters A through Z are used to represent values 10 through 36 and their case is determined by the letterCase parameter.
  • All floating point types to all string types.
  • Pointer to string conversions prints the pointer as a size_t value. If pointer is char*, treat it as C-style strings. In that case, this function is @system.
// Conversion representing dynamic/static array with string
long[] a = [ 1, 3, 5 ];
writeln(to!string(a)); // "[1, 3, 5]"

// Conversion representing associative array with string
int[string] associativeArray = ["0":1, "1":2];
assert(to!string(associativeArray) == `["0":1, "1":2]` ||
       to!string(associativeArray) == `["1":2, "0":1]`);

// char* to string conversion
writeln(to!string(cast(char*)null)); // ""
writeln(to!string("foo\0".ptr)); // "foo"

// Conversion reinterpreting void array to string
auto w = "abcx"w;
const(void)[] b = w;
writeln(b.length); // 8

auto c = to!(wchar[])(b);
writeln(c); // "abcx"
template roundTo(Target)
Rounded conversion from floating point to integral.
Rounded conversions do not work with non-integral target types.
Examples:
writeln(roundTo!int(3.14)); // 3
writeln(roundTo!int(3.49)); // 3
writeln(roundTo!int(3.5)); // 4
writeln(roundTo!int(3.999)); // 4
writeln(roundTo!int(-3.14)); // -3
writeln(roundTo!int(-3.49)); // -3
writeln(roundTo!int(-3.5)); // -4
writeln(roundTo!int(-3.999)); // -4
writeln(roundTo!(const int)(to!(const double)(-3.999))); // -4
Target parse(Target, Source)(ref Source source)
if (isInputRange!Source && isSomeChar!(ElementType!Source) && is(Unqual!Target == bool));
The parse family of functions works quite like the to family, except that:
  1. It only works with character ranges as input.
  2. It takes the input by reference. (This means that rvalues - such as string literals - are not accepted: use to instead.)
  3. It advances the input to the position following the conversion.
  4. It does not throw if it could not convert the entire input.
This overload converts a character input range to a bool.
Parameters:
Target the type to convert to
Source source the lvalue of an input range
Returns:
A bool
Throws:
A ConvException if the range does not represent a bool.

Note All character input range conversions using to are forwarded to parse and do not require lvalues.

Examples:
auto s = "true";
bool b = parse!bool(s);
assert(b);
Target parse(Target, Source)(ref Source s)
if (isSomeChar!(ElementType!Source) && isIntegral!Target && !is(Target == enum));

Target parse(Target, Source)(ref Source source, uint radix)
if (isSomeChar!(ElementType!Source) && isIntegral!Target && !is(Target == enum));
Parses a character input range to an integral value.
Parameters:
Target the integral type to convert to
Source s the lvalue of an input range
Returns:
A number of type Target
Throws:
A ConvException If an overflow occurred during conversion or if no character of the input was meaningfully converted.
Examples:
string s = "123";
auto a = parse!int(s);
writeln(a); // 123

// parse only accepts lvalues
static assert(!__traits(compiles, parse!int("123")));
Examples:
import std.string : tr;
string test = "123 \t  76.14";
auto a = parse!uint(test);
writeln(a); // 123
assert(test == " \t  76.14"); // parse bumps string
test = tr(test, " \t\n\r", "", "d"); // skip ws
writeln(test); // "76.14"
auto b = parse!double(test);
writeln(b); // 76.14
writeln(test); // ""
Target parse(Target, Source)(ref Source s)
if (isSomeString!Source && !is(Source == enum) && is(Target == enum));
Takes a string representing an enum type and returns that type.
Parameters:
Target the enum type to convert to
Source s the lvalue of the range to parse
Returns:
An enum of type Target
Throws:
A ConvException if type Target does not have a member represented by s.
Examples:
enum EnumType : bool { a = true, b = false, c = a }

auto str = "a";
writeln(parse!EnumType(str)); // EnumType.a
Target parse(Target, Source)(ref Source source)
if (isInputRange!Source && isSomeChar!(ElementType!Source) && !is(Source == enum) && isFloatingPoint!Target && !is(Target == enum));
Parses a character range to a floating point number.
Parameters:
Target a floating point type
Source source the lvalue of the range to parse
Returns:
A floating point number of type Target
Throws:
A ConvException if source is empty, if no number could be parsed, or if an overflow occurred.
Examples:
import std.math : approxEqual;
auto str = "123.456";

assert(parse!double(str).approxEqual(123.456));
Target parse(Target, Source)(ref Source s)
if (isSomeString!Source && !is(Source == enum) && (staticIndexOf!(Unqual!Target, dchar, Unqual!(ElementEncodingType!Source)) >= 0));

Target parse(Target, Source)(ref Source s)
if (!isSomeString!Source && isInputRange!Source && isSomeChar!(ElementType!Source) && isSomeChar!Target && (Target.sizeof >= ElementType!Source.sizeof) && !is(Target == enum));
Parsing one character off a range returns the first element and calls popFront.
Parameters:
Target the type to convert to
Source s the lvalue of an input range
Returns:
A character of type Target
Throws:
A ConvException if the range is empty.
Examples:
auto s = "Hello, World!";
char first = parse!char(s);
writeln(first); // 'H'
writeln(s); // "ello, World!"
Target parse(Target, Source)(ref Source s)
if (isInputRange!Source && isSomeChar!(ElementType!Source) && is(Unqual!Target == typeof(null)));
Parsing a character range to typeof(null) returns null if the range spells "null". This function is case insensitive.
Parameters:
Target the type to convert to
Source s the lvalue of an input range
Returns:
null
Throws:
A ConvException if the range doesn't represent null.
Examples:
import std.exception : assertThrown;

alias NullType = typeof(null);
auto s1 = "null";
assert(parse!NullType(s1) is null);
writeln(s1); // ""

auto s2 = "NUll"d;
assert(parse!NullType(s2) is null);
writeln(s2); // ""

auto m = "maybe";
assertThrown!ConvException(parse!NullType(m));
assert(m == "maybe");  // m shouldn't change on failure

auto s = "NULL";
assert(parse!(const NullType)(s) is null);
Target parse(Target, Source)(ref Source s, dchar lbracket = '[', dchar rbracket = ']', dchar comma = ',')
if (isSomeString!Source && !is(Source == enum) && isDynamicArray!Target && !is(Target == enum));

Target parse(Target, Source)(ref Source s, dchar lbracket = '[', dchar rbracket = ']', dchar comma = ',')
if (isExactSomeString!Source && isStaticArray!Target && !is(Target == enum));
Parses an array from a string given the left bracket (default '['), right bracket (default ']'), and element separator (by default ','). A trailing separator is allowed.
Parameters:
Source s The string to parse
dchar lbracket the character that starts the array
dchar rbracket the character that ends the array
dchar comma the character that separates the elements of the array
Returns:
An array of type Target
Examples:
auto s1 = `[['h', 'e', 'l', 'l', 'o'], "world"]`;
auto a1 = parse!(string[])(s1);
writeln(a1); // ["hello", "world"]

auto s2 = `["aaa", "bbb", "ccc"]`;
auto a2 = parse!(string[])(s2);
writeln(a2); // ["aaa", "bbb", "ccc"]
Target parse(Target, Source)(ref Source s, dchar lbracket = '[', dchar rbracket = ']', dchar keyval = ':', dchar comma = ',')
if (isSomeString!Source && !is(Source == enum) && isAssociativeArray!Target && !is(Target == enum));
Parses an associative array from a string given the left bracket (default '['), right bracket (default ']'), key-value separator (default ':'), and element seprator (by default ',').
Parameters:
Source s the string to parse
dchar lbracket the character that starts the associative array
dchar rbracket the character that ends the associative array
dchar keyval the character that associates the key with the value
dchar comma the character that separates the elements of the associative array
Returns:
An associative array of type Target
Examples:
auto s1 = "[1:10, 2:20, 3:30]";
auto aa1 = parse!(int[int])(s1);
writeln(aa1); // [1:10, 2:20, 3:30]

auto s2 = `["aaa":10, "bbb":20, "ccc":30]`;
auto aa2 = parse!(int[string])(s2);
writeln(aa2); // ["aaa":10, "bbb":20, "ccc":30]

auto s3 = `["aaa":[1], "bbb":[2,3], "ccc":[4,5,6]]`;
auto aa3 = parse!(int[][string])(s3);
writeln(aa3); // ["aaa":[1], "bbb":[2, 3], "ccc":[4, 5, 6]]
string text(T...)(T args)
if (T.length > 0);

wstring wtext(T...)(T args)
if (T.length > 0);

dstring dtext(T...)(T args)
if (T.length > 0);
Convenience functions for converting one or more arguments of any type into text (the three character widths).
Examples:
writeln(text(42, ' ', 1.5, ": xyz")); // "42 1.5: xyz"c
writeln(wtext(42, ' ', 1.5, ": xyz")); // "42 1.5: xyz"w
writeln(dtext(42, ' ', 1.5, ": xyz")); // "42 1.5: xyz"d
template octal(string num) if (isOctalLiteral(num))

template octal(alias decimalInteger) if (is(typeof(decimalInteger)) && isIntegral!(typeof(decimalInteger)))
The octal facility provides a means to declare a number in base 8. Using octal!177 or octal!"177" for 127 represented in octal (same as 0177 in C).
The rules for strings are the usual for literals: If it can fit in an int, it is an int. Otherwise, it is a long. But, if the user specifically asks for a long with the L suffix, always give the long. Give an unsigned iff it is asked for with the U or u suffix. Octals created from integers preserve the type of the passed-in integral.
See Also:
parse for parsing octal strings at runtime.
Examples:
// same as 0177
auto x = octal!177;
// octal is a compile-time device
enum y = octal!160;
// Create an unsigned octal
auto z = octal!"1_000_000u";
pure nothrow @safe T* emplace(T)(T* chunk);
Given a pointer chunk to uninitialized memory (but already typed as T), constructs an object of non-class type T at that address. If T is a class, initializes the class reference to null.
Returns:
A pointer to the newly constructed object (which is the same as chunk).
Examples:
static struct S
{
    int i = 42;
}
S[2] s2 = void;
emplace(&s2);
assert(s2[0].i == 42 && s2[1].i == 42);
Examples:
interface I {}
class K : I {}

K k = void;
emplace(&k);
assert(k is null);

I i = void;
emplace(&i);
assert(i is null);
T* emplace(T, Args...)(T* chunk, auto ref Args args)
if (is(T == struct) || Args.length == 1);
Given a pointer chunk to uninitialized memory (but already typed as a non-class type T), constructs an object of type T at that address from arguments args. If T is a class, initializes the class reference to args[0].
This function can be @trusted if the corresponding constructor of T is @safe.
Returns:
A pointer to the newly constructed object (which is the same as chunk).
Examples:
int a;
int b = 42;
writeln(*emplace!int(&a, b)); // 42
T emplace(T, Args...)(T chunk, auto ref Args args)
if (is(T == class));
Given a raw memory area chunk (but already typed as a class type T), constructs an object of class type T at that address. The constructor is passed the arguments Args.
If T is an inner class whose outer field can be used to access an instance of the enclosing class, then Args must not be empty, and the first member of it must be a valid initializer for that outer field. Correct initialization of this field is essential to access members of the outer class inside T methods.

Note This function is @safe if the corresponding constructor of T is @safe.

Returns:
The newly constructed object.
Examples:
() @safe {
    class SafeClass
    {
        int x;
        @safe this(int x) { this.x = x; }
    }

    auto buf = new void[__traits(classInstanceSize, SafeClass)];
    auto support = (() @trusted => cast(SafeClass)(buf.ptr))();
    auto safeClass = emplace!SafeClass(support, 5);
    writeln(safeClass.x); // 5

    class UnsafeClass
    {
        int x;
        @system this(int x) { this.x = x; }
    }

    auto buf2 = new void[__traits(classInstanceSize, UnsafeClass)];
    auto support2 = (() @trusted => cast(UnsafeClass)(buf2.ptr))();
    static assert(!__traits(compiles, emplace!UnsafeClass(support2, 5)));
    static assert(!__traits(compiles, emplace!UnsafeClass(buf2, 5)));
}();
T emplace(T, Args...)(void[] chunk, auto ref Args args)
if (is(T == class));
Given a raw memory area chunk, constructs an object of class type T at that address. The constructor is passed the arguments Args.
If T is an inner class whose outer field can be used to access an instance of the enclosing class, then Args must not be empty, and the first member of it must be a valid initializer for that outer field. Correct initialization of this field is essential to access members of the outer class inside T methods.

Preconditions chunk must be at least as large as T needs and should have an alignment multiple of T's alignment. (The size of a class instance is obtained by using _traits(classInstanceSize, T)).

Note This function can be @trusted if the corresponding constructor of T is @safe.

Returns:
The newly constructed object.
Examples:
static class C
{
    int i;
    this(int i){this.i = i;}
}
auto buf = new void[__traits(classInstanceSize, C)];
auto c = emplace!C(buf, 5);
writeln(c.i); // 5
T* emplace(T, Args...)(void[] chunk, auto ref Args args)
if (!is(T == class));
Given a raw memory area chunk, constructs an object of non-class type T at that address. The constructor is passed the arguments args, if any.

Preconditions chunk must be at least as large as T needs and should have an alignment multiple of T's alignment.

Note This function can be @trusted if the corresponding constructor of T is @safe.

Returns:
A pointer to the newly constructed object.
Examples:
struct S
{
    int a, b;
}
auto buf = new void[S.sizeof];
S s;
s.a = 42;
s.b = 43;
auto s1 = emplace!S(buf, s);
assert(s1.a == 42 && s1.b == 43);
auto unsigned(T)(T x)
if (isIntegral!T);
Returns the corresponding unsigned value for x (e.g. if x has type int, it returns cast(uint) x). The advantage compared to the cast is that you do not need to rewrite the cast if x later changes type (e.g from int to long).
Note that the result is always mutable even if the original type was const or immutable. In order to retain the constness, use std.traits.Unsigned.
Examples:
import std.traits : Unsigned;
immutable int s = 42;
auto u1 = unsigned(s); //not qualified
static assert(is(typeof(u1) == uint));
Unsigned!(typeof(s)) u2 = unsigned(s); //same qualification
static assert(is(typeof(u2) == immutable uint));
immutable u3 = unsigned(s); //explicitly qualified
auto signed(T)(T x)
if (isIntegral!T);
Returns the corresponding signed value for x (e.g. if x has type uint, it returns cast(int) x). The advantage compared to the cast is that you do not need to rewrite the cast if x later changes type (e.g from uint to ulong).
Note that the result is always mutable even if the original type was const or immutable. In order to retain the constness, use std.traits.Signed.
Examples:
import std.traits : Signed;

immutable uint u = 42;
auto s1 = signed(u); //not qualified
static assert(is(typeof(s1) == int));
Signed!(typeof(u)) s2 = signed(u); //same qualification
static assert(is(typeof(s2) == immutable int));
immutable s3 = signed(u); //explicitly qualified
OriginalType!E asOriginalType(E)(E value)
if (is(E == enum));
Returns the representation of an enumerated value, i.e. the value converted to the base type of the enumeration.
Examples:
enum A { a = 42 }
static assert(is(typeof(A.a.asOriginalType) == int));
writeln(A.a.asOriginalType); // 42
enum B : double { a = 43 }
static assert(is(typeof(B.a.asOriginalType) == double));
writeln(B.a.asOriginalType); // 43
template castFrom(From)
A wrapper on top of the built-in cast operator that allows one to restrict casting of the original type of the value.
A common issue with using a raw cast is that it may silently continue to compile even if the value's type has changed during refactoring, which breaks the initial assumption about the cast.
Parameters:
From The type to cast from. The programmer must ensure it is legal to make this cast.
Examples:
// Regular cast, which has been verified to be legal by the programmer:
{
    long x;
    auto y = cast(int) x;
}

// However this will still compile if 'x' is changed to be a pointer:
{
    long* x;
    auto y = cast(int) x;
}

// castFrom provides a more reliable alternative to casting:
{
    long x;
    auto y = castFrom!long.to!int(x);
}

// Changing the type of 'x' will now issue a compiler error,
// allowing bad casts to be caught before it's too late:
{
    long* x;
    static assert(
        !__traits(compiles, castFrom!long.to!int(x))
    );

    // if cast is still needed, must be changed to:
    auto y = castFrom!(long*).to!int(x);
}
ref @system auto to(To, T)(auto ref T value);
Parameters:
To The type to cast to.
T value The value to cast. It must be of type From, otherwise a compile-time error is emitted.
Returns:
the value after the cast, returned by reference if possible.
template hexString(string hexData) if (hexData.isHexLiteral)

template hexString(wstring hexData) if (hexData.isHexLiteral)

template hexString(dstring hexData) if (hexData.isHexLiteral)
Converts a hex literal to a string at compile time.
Takes a string made of hexadecimal digits and returns the matching string by converting each pair of digits to a character. The input string can also include white characters, which can be used to keep the literal string readable in the source code.
The function is intended to replace the hexadecimal literal strings starting with 'x', which could be removed to simplify the core language.
Parameters:
hexData string to be converted.
Returns:
a string, a wstring or a dstring, according to the type of hexData.
Examples:
// conversion at compile time
auto string1 = hexString!"304A314B";
writeln(string1); // "0J1K"
auto string2 = hexString!"304A314B"w;
writeln(string2); // "0J1K"w
auto string3 = hexString!"304A314B"d;
writeln(string3); // "0J1K"d
pure nothrow @nogc @safe auto toChars(ubyte radix = 10, Char = char, LetterCase letterCase = LetterCase.lower, T)(T value)
if ((radix == 2 || radix == 8 || radix == 10 || radix == 16) && (is(Unqual!T == uint) || is(Unqual!T == ulong) || radix == 10 && (is(Unqual!T == int) || is(Unqual!T == long))));
Convert integer to a range of characters. Intended to be lightweight and fast.
Parameters:
radix 2, 8, 10, 16
Char character type for output
letterCase lower for deadbeef, upper for DEADBEEF
T value integer to convert. Can be uint or ulong. If radix is 10, can also be int or long.
Returns:
Random access range with slicing and everything
Examples:
import std.algorithm.comparison : equal;

assert(toChars(1).equal("1"));
assert(toChars(1_000_000).equal("1000000"));

assert(toChars!(2)(2U).equal("10"));
assert(toChars!(16)(255U).equal("ff"));
assert(toChars!(16, char, LetterCase.upper)(255U).equal("FF"));