| ... | @@ -0,0 +1,65 @@ |
| 1 | //! object representing a single color in the sRGB colorspace with channel values from 0-255 |
| 2 | |
| 3 | const std = @import("std"); |
| 4 | const Self = @This(); |
| 5 | |
| 6 | r: u8, // red value |
| 7 | g: u8, // green value |
| 8 | b: u8, // blue value |
| 9 | a: u8, // alpha value |
| 10 | |
| 11 | pub fn initRGBA(r: u8, g: u8, b: u8, a: u8) Self { |
| 12 | return Self{ |
| 13 | .r = r, |
| 14 | .g = g, |
| 15 | .b = b, |
| 16 | .a = a, |
| 17 | }; |
| 18 | } |
| 19 | |
| 20 | pub fn initRGB(r: u8, g: u8, b: u8) Self { |
| 21 | return initRGBA(r, g, b, 255); |
| 22 | } |
| 23 | |
| 24 | pub fn parseHexConst(comptime input: *const [7:0]u8) Self { |
| 25 | comptime std.debug.assert(input[0] == '#'); |
| 26 | return comptime initRGB( |
| 27 | std.fmt.parseInt(u8, input[1..3], 16) catch unreachable, |
| 28 | std.fmt.parseInt(u8, input[3..5], 16) catch unreachable, |
| 29 | std.fmt.parseInt(u8, input[5..7], 16) catch unreachable, |
| 30 | ); |
| 31 | } |
| 32 | |
| 33 | pub fn parseHex(input: []const u8) Self { |
| 34 | std.debug.assert(input.len == 7); |
| 35 | std.debug.assert(input[0] == '#'); |
| 36 | return initRGB( |
| 37 | std.fmt.parseInt(u8, input[1..3], 16) catch unreachable, |
| 38 | std.fmt.parseInt(u8, input[3..5], 16) catch unreachable, |
| 39 | std.fmt.parseInt(u8, input[5..7], 16) catch unreachable, |
| 40 | ); |
| 41 | } |
| 42 | |
| 43 | pub fn eql(x: Self, y: Self) bool { |
| 44 | return x.r == y.r and x.g == y.g and x.b == y.b; |
| 45 | } |
| 46 | |
| 47 | pub fn format(x: Self, comptime fmt: []const u8, options: std.fmt.FormatOptions, writer: anytype) !void { |
| 48 | _ = fmt; |
| 49 | _ = options; |
| 50 | if (x.a < 255) { |
| 51 | @setCold(true); |
| 52 | try writer.print("#{:0>2}{:0>2}{:0>2}{:0>2}", .{ |
| 53 | std.fmt.fmtSliceHexLower(&.{x.r}), |
| 54 | std.fmt.fmtSliceHexLower(&.{x.g}), |
| 55 | std.fmt.fmtSliceHexLower(&.{x.b}), |
| 56 | std.fmt.fmtSliceHexLower(&.{x.a}), |
| 57 | }); |
| 58 | return; |
| 59 | } |
| 60 | try writer.print("#{:0>2}{:0>2}{:0>2}", .{ |
| 61 | std.fmt.fmtSliceHexLower(&.{x.r}), |
| 62 | std.fmt.fmtSliceHexLower(&.{x.g}), |
| 63 | std.fmt.fmtSliceHexLower(&.{x.b}), |
| 64 | }); |
| 65 | } |