June 14, 2010 [phobos] string-to-bool conversions in std.conv | ||||
---|---|---|---|---|
| ||||
I'd like to add the following to std.conv, to enable parse!bool(string) and to!bool(string). This will fix bug 3386 (and to some extent 1733 and 3223). It will also require a minor change to std.string.icmp(), shown at the bottom. Objections? // std.conv: Target parse(Target, Source)(ref Source s) if (isSomeString!Source && is(Target==bool)) { if (s.length >= 4 && icmp(s[0 .. 4], "true")==0) { s = s[4 .. $]; return true; } if (s.length >= 5 && icmp(s[0 .. 5], "false")==0) { s = s[5 .. $]; return false; } conv_error!(Source, Target)(s); assert(0); } unittest { auto t = "TrueType"; assert (parse!bool(t) == true); assert (t == "Type"); auto f = "False killer whale"; assert (parse!bool(f) == false); assert (f == " killer whale"); try { auto m = "maybe?"; parse!bool(m); assert(false); } catch(ConvError e) { } } // std.string, line 137: - int icmp(in char[] s1, in char[] s2) + int icmp(C1, C2)(in C1[] s1, in C2[] s2) |
June 14, 2010 [phobos] string-to-bool conversions in std.conv | ||||
---|---|---|---|---|
| ||||
Posted in reply to Lars Tandle Kyllingstad | Looks good to me.
Andrei
Lars Tandle Kyllingstad wrote:
> I'd like to add the following to std.conv, to enable parse!bool(string)
> and to!bool(string). This will fix bug 3386 (and to some extent 1733
> and 3223). It will also require a minor change to std.string.icmp(),
> shown at the bottom. Objections?
>
>
> // std.conv:
> Target parse(Target, Source)(ref Source s)
> if (isSomeString!Source && is(Target==bool))
> {
> if (s.length >= 4 && icmp(s[0 .. 4], "true")==0)
> {
> s = s[4 .. $];
> return true;
> }
> if (s.length >= 5 && icmp(s[0 .. 5], "false")==0)
> {
> s = s[5 .. $];
> return false;
> }
> conv_error!(Source, Target)(s);
> assert(0);
> }
>
>
> unittest
> {
> auto t = "TrueType";
> assert (parse!bool(t) == true);
> assert (t == "Type");
>
> auto f = "False killer whale";
> assert (parse!bool(f) == false);
> assert (f == " killer whale");
>
> try {
> auto m = "maybe?";
> parse!bool(m);
> assert(false);
> }
> catch(ConvError e) { }
> }
>
>
> // std.string, line 137:
> - int icmp(in char[] s1, in char[] s2)
> + int icmp(C1, C2)(in C1[] s1, in C2[] s2)
>
>
> _______________________________________________
> phobos mailing list
> phobos at puremagic.com
> http://lists.puremagic.com/mailman/listinfo/phobos
|
Copyright © 1999-2021 by the D Language Foundation