Skip to content

Commit 59dd109

Browse files
committed
Add impl ColorSpace example
Closes #47.
1 parent fac2dbe commit 59dd109

File tree

2 files changed

+49
-0
lines changed

2 files changed

+49
-0
lines changed

CHANGELOG.md

+2
Original file line numberDiff line numberDiff line change
@@ -18,6 +18,7 @@ This release has an [MSRV][] of 1.82.
1818
### Added
1919

2020
* Support for the ACES2065-1 color space. ([#124][] by [@tomcur][])
21+
* A documentation example implementing `ColorSpace`. ([#130][] by [@tomcur][])
2122

2223
### Fixed
2324

@@ -117,6 +118,7 @@ This is the initial release.
117118
[#124]: https://github.com/linebender/color/pull/124
118119
[#128]: https://github.com/linebender/color/pull/128
119120
[#129]: https://github.com/linebender/color/pull/129
121+
[#130]: https://github.com/linebender/color/pull/130
120122

121123
[Unreleased]: https://github.com/linebender/color/compare/v0.2.2...HEAD
122124
[0.2.2]: https://github.com/linebender/color/releases/tag/v0.2.2

color/src/colorspace.rs

+47
Original file line numberDiff line numberDiff line change
@@ -24,6 +24,53 @@ use crate::floatfuncs::FloatFuncs;
2424
///
2525
/// See the [XYZ-D65 color space](`XyzD65`) documentation for some
2626
/// background information on color spaces.
27+
///
28+
/// # Implementing `ColorSpace`
29+
///
30+
/// When implementing a custom color space, take care to set the associated constants correctly.
31+
/// The following is an example implementation of the
32+
/// [Rec. 709](https://www.color.org/chardata/rgb/BT2020.xalter) color space.
33+
///
34+
/// ```rust
35+
/// use core::any::TypeId;
36+
/// use color::{ColorSpace, ColorSpaceLayout};
37+
///
38+
/// /// The Rec. 709 color space, using the electro-optical transfer function
39+
/// /// defined in ITU-R BT.1886.
40+
/// ///
41+
/// /// See https://www.color.org/chardata/rgb/BT709.xalter.
42+
/// #[derive(Clone, Copy, Debug)]
43+
/// pub struct Rec709;
44+
///
45+
/// impl ColorSpace for Rec709 {
46+
/// const IS_LINEAR: bool = false;
47+
///
48+
/// const LAYOUT: ColorSpaceLayout = ColorSpaceLayout::Rectangular;
49+
///
50+
/// const WHITE_COMPONENTS: [f32; 3] = [1., 1., 1.];
51+
///
52+
/// fn to_linear_srgb(src: [f32; 3]) -> [f32; 3] {
53+
/// src.map(|x| x.powf(2.4))
54+
/// }
55+
///
56+
/// fn from_linear_srgb(src: [f32; 3]) -> [f32; 3] {
57+
/// src.map(|x| x.powf(1. / 2.4))
58+
/// }
59+
///
60+
/// fn convert<TargetCS: ColorSpace>(src: [f32; 3]) -> [f32; 3] {
61+
/// if TypeId::of::<Self>() == TypeId::of::<TargetCS>() {
62+
/// src
63+
/// } else {
64+
/// let lin_srgb = Self::to_linear_srgb(src);
65+
/// TargetCS::from_linear_srgb(lin_srgb)
66+
/// }
67+
/// }
68+
///
69+
/// fn clip([r, g, b]: [f32; 3]) -> [f32; 3] {
70+
/// [r.clamp(0., 1.), g.clamp(0., 1.), b.clamp(0., 1.)]
71+
/// }
72+
/// }
73+
/// ```
2774
pub trait ColorSpace: Clone + Copy + 'static {
2875
/// Whether the color space is linear.
2976
///

0 commit comments

Comments
 (0)