dyaml/examples/constructor/main.d

99 lines
2.3 KiB
D
Raw Normal View History

2011-08-16 12:53:13 +00:00
import std.ascii;
import std.stdio;
import std.string;
import yaml;
struct Color
{
ubyte red;
ubyte green;
ubyte blue;
}
Color constructColorScalar(Mark start, Mark end, ref Node node)
2011-08-16 12:53:13 +00:00
{
string value = node.as!string;
if(value.length != 6)
{
throw new ConstructorException("Invalid color: " ~ value, start, end);
}
//We don't need to check for uppercase chars this way.
value = value.toLower();
//Get value of a hex digit.
uint hex(char c)
{
if(!std.ascii.isHexDigit(c))
{
throw new ConstructorException("Invalid color: " ~ value, start, end);
}
if(std.ascii.isDigit(c))
{
return c - '0';
}
return c - 'a' + 10;
}
Color result;
result.red = cast(ubyte)(16 * hex(value[0]) + hex(value[1]));
result.green = cast(ubyte)(16 * hex(value[2]) + hex(value[3]));
result.blue = cast(ubyte)(16 * hex(value[4]) + hex(value[5]));
return result;
2011-08-16 12:53:13 +00:00
}
Color constructColorMapping(Mark start, Mark end, ref Node node)
2011-08-16 12:53:13 +00:00
{
ubyte r,g,b;
//Might throw if a value is missing is not an integer, or is out of range.
try
{
r = node["r"].as!ubyte;
g = node["g"].as!ubyte;
b = node["b"].as!ubyte;
}
catch(NodeException e)
{
throw new ConstructorException("Invalid color: " ~ e.msg, start, end);
}
return Color(cast(ubyte)r, cast(ubyte)g, cast(ubyte)b);
2011-08-16 12:53:13 +00:00
}
void main()
{
auto red = Color(255, 0, 0);
auto orange = Color(255, 255, 0);
try
{
auto constructor = new Constructor;
//both functions handle the same tag, but one handles scalar, one mapping.
constructor.addConstructorScalar("!color", &constructColorScalar);
constructor.addConstructorMapping("!color-mapping", &constructColorMapping);
2011-08-16 12:53:13 +00:00
auto loader = Loader("input.yaml");
loader.constructor = constructor;
2011-08-16 12:53:13 +00:00
auto root = loader.load();
2011-08-16 12:53:13 +00:00
if(root["scalar-red"].as!Color == red &&
root["mapping-red"].as!Color == red &&
root["scalar-orange"].as!Color == orange &&
root["mapping-orange"].as!Color == orange)
2011-08-16 12:53:13 +00:00
{
writeln("SUCCESS");
return;
}
}
catch(YAMLException e)
{
writeln(e.msg);
}
writeln("FAILURE");
}