Hi,
I’ve created a CSS color parser library for Zig.
csscolorparser-zig is a Zig library for parsing CSS color string as defined in the W3C’s CSS Color Module Level 4.
This library is ported from both the csscolorparser
crate in Rust and the github.com/mazznoer/csscolorparser
package in Go.
Example
test parse {
var buf: [9]u8 = undefined;
{
const color = try Color(f64).parse("#ff0");
try testing.expectEqual(
.{ 1.0, 1.0, 0.0, 1.0 },
.{ color.red, color.green, color.blue, color.alpha },
);
try testing.expectEqual(.{ 255, 255, 0, 255 }, color.toRgba8());
const hex = try color.toHexString(&buf);
try testing.expectEqualStrings("#ffff00", hex);
}
{
const color = try Color(f64).parse("hsl(360 100% 50%)");
try testing.expectEqual(
.{ 1.0, 0.0, 0.0, 1.0 },
.{ color.red, color.green, color.blue, color.alpha },
);
try testing.expectEqual(.{ 255, 0, 0, 255 }, color.toRgba8());
const hex = try color.toHexString(&buf);
try testing.expectEqualStrings("#ff0000", hex);
}
{
const color = try Color(f64).parse("rgb(255 0 0)");
try testing.expectEqual(
.{ 1.0, 0.0, 0.0, 1.0 },
.{ color.red, color.green, color.blue, color.alpha },
);
try testing.expectEqual(.{ 255, 0, 0, 255 }, color.toRgba8());
const hex = try color.toHexString(&buf);
try testing.expectEqualStrings("#ff0000", hex);
}
{
const color = try Color(f64).parse("#ff00007f");
try testing.expectEqual(.{ 255, 0, 0, 127 }, color.toRgba8());
const hex = try color.toHexString(&buf);
try testing.expectEqualStrings("#ff00007f", hex);
}
}
test name {
const color = try Color(f64).parse("#008080");
try testing.expectEqualStrings("teal", color.name().?);
const color_with_alpha = try Color(f64).parse("#0080807f");
try testing.expectEqual(null, color_with_alpha.name());
const color_without_name = try Color(f64).parse("#7f7f7f");
try testing.expectEqual(null, color_without_name.name());
}