Skip to main content

pdfboss_write/
color.rs

1//! Device color values for content generation. The first public color
2//! vocabulary in the workspace — the render crate keeps its own private
3//! read-side `ColorSpace`.
4
5use pdfboss_core::content::Op;
6
7/// A device color: gray, RGB or CMYK, components in `0.0..=1.0`.
8#[derive(Debug, Clone, Copy, PartialEq)]
9pub enum Color {
10    /// DeviceGray.
11    Gray(f32),
12    /// DeviceRGB.
13    Rgb(f32, f32, f32),
14    /// DeviceCMYK.
15    Cmyk(f32, f32, f32, f32),
16}
17
18impl Color {
19    /// Black in DeviceGray.
20    pub const BLACK: Color = Color::Gray(0.0);
21    /// White in DeviceGray.
22    pub const WHITE: Color = Color::Gray(1.0);
23
24    /// The operator that selects this color for filling (`g`/`rg`/`k`).
25    pub(crate) fn fill_op(self) -> Op {
26        match self {
27            Color::Gray(gray) => Op::SetFillGray(gray),
28            Color::Rgb(r, g, b) => Op::SetFillRGB(r, g, b),
29            Color::Cmyk(c, m, y, k) => Op::SetFillCMYK(c, m, y, k),
30        }
31    }
32
33    /// The operator that selects this color for stroking (`G`/`RG`/`K`).
34    pub(crate) fn stroke_op(self) -> Op {
35        match self {
36            Color::Gray(gray) => Op::SetStrokeGray(gray),
37            Color::Rgb(r, g, b) => Op::SetStrokeRGB(r, g, b),
38            Color::Cmyk(c, m, y, k) => Op::SetStrokeCMYK(c, m, y, k),
39        }
40    }
41}
42
43#[cfg(test)]
44mod tests {
45    use super::*;
46
47    #[test]
48    fn fill_op_maps_each_variant() {
49        assert_eq!(Color::Gray(0.25).fill_op(), Op::SetFillGray(0.25));
50        assert_eq!(
51            Color::Rgb(0.1, 0.2, 0.3).fill_op(),
52            Op::SetFillRGB(0.1, 0.2, 0.3)
53        );
54        assert_eq!(
55            Color::Cmyk(0.1, 0.2, 0.3, 0.4).fill_op(),
56            Op::SetFillCMYK(0.1, 0.2, 0.3, 0.4)
57        );
58        assert_eq!(Color::BLACK.fill_op(), Op::SetFillGray(0.0));
59        assert_eq!(Color::WHITE.fill_op(), Op::SetFillGray(1.0));
60    }
61
62    #[test]
63    fn stroke_op_maps_each_variant() {
64        assert_eq!(Color::Gray(0.75).stroke_op(), Op::SetStrokeGray(0.75));
65        assert_eq!(
66            Color::Rgb(0.4, 0.5, 0.6).stroke_op(),
67            Op::SetStrokeRGB(0.4, 0.5, 0.6)
68        );
69        assert_eq!(
70            Color::Cmyk(0.5, 0.6, 0.7, 0.8).stroke_op(),
71            Op::SetStrokeCMYK(0.5, 0.6, 0.7, 0.8)
72        );
73    }
74}