Report a bug
If you spot a problem with this page, click here to create a Github 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.

mir.parse

@nogc Parsing Utilities

Authors:
Ilya Yaroshenko
T fromString(T, Range)(auto ref scope Range r);
Throws:
nogc Exception in case of parse error or non-empty remaining input.
Examples:
assert("123".fromString!int == 123);

auto s = "123";
assert(s.fromString!int == 123);
assert(s == "");

s = "123";
assert(s[].fromString!int == 123);
assert(s == "123");
bool parse(T : byte, Range)(ref scope Range r, ref scope T value)
if (isInputRange!Range && !__traits(isUnsigned, T));

bool parse(T : short, Range)(ref scope Range r, ref scope T value)
if (isInputRange!Range && !__traits(isUnsigned, T));

bool parse(T : int, Range)(ref scope Range r, ref scope T value)
if (isInputRange!Range && !__traits(isUnsigned, T));

bool parse(T : long, Range)(ref scope Range r, ref scope T value)
if (isInputRange!Range && !__traits(isUnsigned, T));

bool parse(T : ubyte, Range)(ref scope Range r, ref scope T value)
if (isInputRange!Range && __traits(isUnsigned, T));

bool parse(T : ushort, Range)(ref scope Range r, ref scope T value)
if (isInputRange!Range && __traits(isUnsigned, T));

bool parse(T : uint, Range)(ref scope Range r, ref scope T value)
if (isInputRange!Range && __traits(isUnsigned, T));

bool parse(T : ulong, Range)(ref scope Range r, ref scope T value)
if (isInputRange!Range && __traits(isUnsigned, T));
Examples:
import std.meta: AliasSeq;
foreach (T; AliasSeq!(byte, ubyte, short, ushort, int, uint, long, ulong))
{
    auto str = "123";
    T val;
    assert(parse(str, val));
    assert(val == 123);
    str = "0";
    assert(parse(str, val));
    assert(val == 0);
    str = "9";
    assert(parse(str, val));
    assert(val == 9);
    str = "";
    assert(!parse(str, val));
    assert(val == 0);
    str = "text";
    assert(!parse(str, val));
    assert(val == 0);
}
Examples:
import std.meta: AliasSeq;
foreach (T; AliasSeq!(byte, short, int, long))
{
    auto str = "-123";
    T val;
    assert(parse(str, val));
    assert(val == -123);
    str = "-0";
    assert(parse(str, val));
    assert(val == 0);
    str = "-9text";
    assert(parse(str, val));
    assert(val == -9);
    assert(str == "text");
    enum m = T.min + 0;
    str = m.stringof;
    assert(parse(str, val));
    assert(val == T.min);
}