Skip to main content

chromashift/
hsb.rs

1use crate::{Alpha, Number, ToAlpha};
2use core::fmt;
3
4/// An colour represented as Hue, Saturation, and Value expressed in the sRGB colour space.
5/// The components are:
6/// - Hue - a number between 0.0 and 360.0
7/// - Saturation - a number between 0.0 and 100.0
8/// - Value / Brightness - a number between 0.0 and 100.0
9/// - Alpha - a number between 0.0 and 100.0
10#[derive(Debug, Clone, Copy, PartialEq)]
11pub struct Hsv {
12	pub hue: f32,
13	pub saturation: f32,
14	pub value: f32,
15	pub alpha: f32,
16}
17
18impl Hsv {
19	pub fn new(hue: f32, saturation: f32, value: f32, alpha: f32) -> Self {
20		Self {
21			hue: hue.rem_euclid(360.0),
22			saturation: saturation.clamp(0.0, 100.0),
23			value: value.clamp(0.0, 100.0),
24			alpha: alpha.clamp(0.0, 100.0),
25		}
26	}
27}
28
29impl ToAlpha for Hsv {
30	fn to_alpha(&self) -> f32 {
31		self.alpha
32	}
33}
34
35impl fmt::Display for Hsv {
36	fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
37		let Self { hue, saturation, value, alpha } = *self;
38		write!(f, "hsv({} {} {}{})", Number(hue), Number(saturation), Number(value), Alpha(alpha))
39	}
40}