From 28d1b1c045cb136f2f9ad2d578f2293e87eb6979 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Bor=20Gro=C5=A1elj=20Simi=C4=87?= Date: Thu, 3 Feb 2022 14:24:22 +0100 Subject: [PATCH] color: add serialize/deserialize --- color.ha | 37 ++++++++++++++++++++++++++++++++++++- 1 file changed, 36 insertions(+), 1 deletion(-) diff --git a/color.ha b/color.ha index 08a498a..4c07feb 100644 --- a/color.ha +++ b/color.ha @@ -1,4 +1,6 @@ -use math::{sqrtf64, nextafterf64}; +use math::{f64frombits, f64bits, sqrtf64, nextafterf64}; +use endian; + export type color = struct { r: f64, @@ -37,6 +39,18 @@ export fn fromrgb(c: rgb) color = { }; }; +export fn deserialize(b: []u8) color = color { + r = f64frombits(endian::legetu64(b[..8])), + g = f64frombits(endian::legetu64(b[8..16])), + b = f64frombits(endian::legetu64(b[16..])), +}; + +export fn serialize(b: []u8, c: const *color) void = { + endian::leputu64(b[..8], f64bits(c.r)); + endian::leputu64(b[8..16], f64bits(c.g)); + endian::leputu64(b[16..24], f64bits(c.b)); +}; + export fn lerp(c1: *const color, c2: *const color, t: f64) color = color { r = (1.0 - t) * c1.r + t * c2.r, g = (1.0 - t) * c1.g + t * c2.g, @@ -51,3 +65,24 @@ export fn sum_color(c1: *const color, c2: *const color) color = color { export fn equal(c1: color, c2: color) bool = c1.r == c2.r && c1.g == c2.g && c1.b == c2.b; + +@test fn equal() void = { + let c = C(0.2, 0.45, 0.8); + assert(equal(C(0.2, 0.45, 0.8), c)); + assert(!equal(c, C(0.2, 0.0, 0.8))); + assert(!equal(c, C(0.0, 0.45, 0.8))); + assert(!equal(c, C(0.2, 0.45, 0.0))); +}; + +@test fn serialize() void = { + let c = C(0.2, 0.45, 0.8); + let b: [24]u8 = [0...]; + serialize(b, &c); + assert(equal(c, deserialize(b))); +}; + +@test fn sum_color() void = { + let grey = C(0.5, 0.5, 0.5); + let white = C(1.0, 1.0, 1.0); + assert(equal(sum_color(&grey, &grey), white)); +}; -- 2.45.2