50 lines
1.6 KiB
Zig
50 lines
1.6 KiB
Zig
|
const std = @import("std");
|
||
|
const fmt = std.fmt;
|
||
|
|
||
|
pub const RGB = struct {
|
||
|
r: u8,
|
||
|
g: u8,
|
||
|
b: u8,
|
||
|
|
||
|
pub fn init(comptime string: []const u8) !RGB {
|
||
|
std.debug.assert(string.len == 6 or string.len == 7);
|
||
|
comptime var index: usize = 0;
|
||
|
if (string[0] == '#') index += 1;
|
||
|
return .{
|
||
|
.r = try fmt.parseInt(u8, string[index .. index + 2], 16),
|
||
|
.g = try fmt.parseInt(u8, string[index + 2 .. index + 4], 16),
|
||
|
.b = try fmt.parseInt(u8, string[index + 4 .. index + 6], 16),
|
||
|
};
|
||
|
}
|
||
|
};
|
||
|
|
||
|
// pub const Default256 = [_]RGB{
|
||
|
// RGB{ .r = 0, .g = 0, .b = 0 },
|
||
|
// RGB{ .r = 204, .g = 4, .b = 3 },
|
||
|
// RGB{ .r = 25, .g = 203, .b = 0 },
|
||
|
// RGB{ .r = 206, .g = 203, .b = 0 },
|
||
|
// RGB{ .r = 13, .g = 115, .b = 204 },
|
||
|
// RGB{ .r = 203, .g = 30, .b = 209 },
|
||
|
// RGB{ .r = 13, .g = 205, .b = 205 },
|
||
|
// RGB{ .r = 221, .g = 221, .b = 221 },
|
||
|
// };
|
||
|
|
||
|
test "RGB init from string" {
|
||
|
const red = try RGB.init("#ff0000");
|
||
|
try std.testing.expectEqual(0xff, red.r);
|
||
|
try std.testing.expectEqual(0x00, red.g);
|
||
|
try std.testing.expectEqual(0x00, red.b);
|
||
|
|
||
|
const green = try RGB.init("00ff00");
|
||
|
try std.testing.expectEqual(0x00, green.r);
|
||
|
try std.testing.expectEqual(0xff, green.g);
|
||
|
try std.testing.expectEqual(0x00, green.b);
|
||
|
|
||
|
const blue = try RGB.init("#0000ff");
|
||
|
try std.testing.expectEqual(0x00, blue.r);
|
||
|
try std.testing.expectEqual(0x00, blue.g);
|
||
|
try std.testing.expectEqual(0xff, blue.b);
|
||
|
|
||
|
try std.testing.expectError(fmt.ParseIntError.InvalidCharacter, RGB.init("xyzxyz"));
|
||
|
}
|