authorgravatar for hello@nektro.netMeghan Denny <hello@nektro.net> 2023-09-14 18:20:41 -07:00
committergravatar for hello@nektro.netMeghan Denny <hello@nektro.net> 2023-09-14 18:20:41 -07:00
log70b5daf6a02ba292381a4b5a557d5cdf70a3c731
tree547572e3272e61e760b5f8aef00abe336d6dcfd8
parent2e5742ea7869077bed479a497ff5ee653076c9a5

add sRGB


2 files changed, 67 insertions(+), 0 deletions(-)

mod.zig+2
......@@ -1,2 +1,4 @@
11const std = @import("std");
22const color = @This();
3
4pub const sRGB = @import("./sRGB.zig");
sRGB.zig created+65
......@@ -0,0 +1,65 @@
1//! object representing a single color in the sRGB colorspace with channel values from 0-255
2
3const std = @import("std");
4const Self = @This();
5
6r: u8, // red value
7g: u8, // green value
8b: u8, // blue value
9a: u8, // alpha value
10
11pub 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
20pub fn initRGB(r: u8, g: u8, b: u8) Self {
21 return initRGBA(r, g, b, 255);
22}
23
24pub 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
33pub 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
43pub 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
47pub 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}