chromashift/
xyzd65.rs

1use crate::{ToAlpha, round_dp};
2use core::fmt;
3
4/// A colour expressed as X, Y and Z values, expressed in the CIE XYZ tristimulus colour space, with an explicit D65
5/// white point.
6/// The components are:
7/// - X - a number between 0.0 and 100.0
8/// - Y - a number between 0.0 and 100.0
9/// - Z - a number between 0.0 and 100.0
10/// - Alpha - a number between 0.0 and 100.0
11#[derive(Debug, Clone, Copy, PartialEq)]
12pub struct XyzD65 {
13	pub x: f64,
14	pub y: f64,
15	pub z: f64,
16	pub alpha: f32,
17}
18
19impl XyzD65 {
20	pub fn new(x: f64, y: f64, z: f64, alpha: f32) -> Self {
21		Self { x, y, z, alpha: alpha.clamp(0.0, 100.0) }
22	}
23}
24
25impl ToAlpha for XyzD65 {
26	fn to_alpha(&self) -> f32 {
27		self.alpha
28	}
29}
30
31impl fmt::Display for XyzD65 {
32	fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
33		let Self { x, y, z, alpha } = self;
34		write!(f, "color(xyz-d65 {} {}% {}%", round_dp(*x, 4), round_dp(*y, 4), round_dp(*z, 4))?;
35		if *alpha < 100.0 {
36			write!(f, " / {}", round_dp(*alpha as f64, 2))?;
37		}
38		write!(f, ")")
39	}
40}