const std = @import("std"); const Color = @This(); r: u8, g: u8, b: u8, a: u8, pub const black = Color{ .r = 0, .g = 0, .b = 0, .a = 255, }; pub fn parse(str: []const u8, hash_required: bool) !Color { var color = Color{ .r = undefined, .g = undefined, .b = undefined, .a = 255, }; if (str.len < 1) { return error.InvalidColorFormat; } const has_hash = str[0] == '#'; if (hash_required and !has_hash) { return error.InvalidColorFormat; } const hex_str = if (has_hash) str[1..] else str; if (hex_str.len == 6) { color.r = try std.fmt.parseInt(u8, hex_str[0..2], 16); color.g = try std.fmt.parseInt(u8, hex_str[2..4], 16); color.b = try std.fmt.parseInt(u8, hex_str[4..6], 16); } else if (hex_str.len == 8) { color.a = try std.fmt.parseInt(u8, hex_str[0..2], 16); color.r = try std.fmt.parseInt(u8, hex_str[2..4], 16); color.g = try std.fmt.parseInt(u8, hex_str[4..6], 16); color.b = try std.fmt.parseInt(u8, hex_str[6..8], 16); } else { return error.InvalidColorFormat; } return color; }