image/
traits.rs

1//! This module provides useful traits that were deprecated in rust
2
3// Note copied from the stdlib under MIT license
4
5use num_traits::{Bounded, Num, NumCast};
6use std::ops::AddAssign;
7
8use crate::color::{ColorType, Luma, LumaA, Rgb, Rgba};
9
10/// Types which are safe to treat as an immutable byte slice in a pixel layout
11/// for image encoding.
12pub trait EncodableLayout: seals::EncodableLayout {
13    /// Get the bytes of this value.
14    fn as_bytes(&self) -> &[u8];
15}
16
17impl EncodableLayout for [u8] {
18    fn as_bytes(&self) -> &[u8] {
19        bytemuck::cast_slice(self)
20    }
21}
22
23impl EncodableLayout for [u16] {
24    fn as_bytes(&self) -> &[u8] {
25        bytemuck::cast_slice(self)
26    }
27}
28
29impl EncodableLayout for [f32] {
30    fn as_bytes(&self) -> &[u8] {
31        bytemuck::cast_slice(self)
32    }
33}
34
35/// The type of each channel in a pixel. For example, this can be `u8`, `u16`, `f32`.
36// TODO rename to `PixelComponent`? Split up into separate traits? Seal?
37pub trait Primitive: Copy + NumCast + Num + PartialOrd<Self> + Clone + Bounded {
38    /// The maximum value for this type of primitive within the context of color.
39    /// For floats, the maximum is `1.0`, whereas the integer types inherit their usual maximum values.
40    const DEFAULT_MAX_VALUE: Self;
41
42    /// The minimum value for this type of primitive within the context of color.
43    /// For floats, the minimum is `0.0`, whereas the integer types inherit their usual minimum values.
44    const DEFAULT_MIN_VALUE: Self;
45}
46
47macro_rules! declare_primitive {
48    ($base:ty: ($from:expr)..$to:expr) => {
49        impl Primitive for $base {
50            const DEFAULT_MAX_VALUE: Self = $to;
51            const DEFAULT_MIN_VALUE: Self = $from;
52        }
53    };
54}
55
56declare_primitive!(usize: (0)..Self::MAX);
57declare_primitive!(u8: (0)..Self::MAX);
58declare_primitive!(u16: (0)..Self::MAX);
59declare_primitive!(u32: (0)..Self::MAX);
60declare_primitive!(u64: (0)..Self::MAX);
61
62declare_primitive!(isize: (Self::MIN)..Self::MAX);
63declare_primitive!(i8: (Self::MIN)..Self::MAX);
64declare_primitive!(i16: (Self::MIN)..Self::MAX);
65declare_primitive!(i32: (Self::MIN)..Self::MAX);
66declare_primitive!(i64: (Self::MIN)..Self::MAX);
67declare_primitive!(f32: (0.0)..1.0);
68declare_primitive!(f64: (0.0)..1.0);
69
70/// An Enlargable::Larger value should be enough to calculate
71/// the sum (average) of a few hundred or thousand Enlargeable values.
72pub trait Enlargeable: Sized + Bounded + NumCast {
73    type Larger: Copy + NumCast + Num + PartialOrd<Self::Larger> + Clone + Bounded + AddAssign;
74
75    fn clamp_from(n: Self::Larger) -> Self {
76        if n > Self::max_value().to_larger() {
77            Self::max_value()
78        } else if n < Self::min_value().to_larger() {
79            Self::min_value()
80        } else {
81            NumCast::from(n).unwrap()
82        }
83    }
84
85    fn to_larger(self) -> Self::Larger {
86        NumCast::from(self).unwrap()
87    }
88}
89
90impl Enlargeable for u8 {
91    type Larger = u32;
92}
93impl Enlargeable for u16 {
94    type Larger = u32;
95}
96impl Enlargeable for u32 {
97    type Larger = u64;
98}
99impl Enlargeable for u64 {
100    type Larger = u128;
101}
102impl Enlargeable for usize {
103    // Note: On 32-bit architectures, u64 should be enough here.
104    type Larger = u128;
105}
106impl Enlargeable for i8 {
107    type Larger = i32;
108}
109impl Enlargeable for i16 {
110    type Larger = i32;
111}
112impl Enlargeable for i32 {
113    type Larger = i64;
114}
115impl Enlargeable for i64 {
116    type Larger = i128;
117}
118impl Enlargeable for isize {
119    // Note: On 32-bit architectures, i64 should be enough here.
120    type Larger = i128;
121}
122impl Enlargeable for f32 {
123    type Larger = f64;
124}
125impl Enlargeable for f64 {
126    type Larger = f64;
127}
128
129/// Linear interpolation without involving floating numbers.
130pub trait Lerp: Bounded + NumCast {
131    type Ratio: Primitive;
132
133    fn lerp(a: Self, b: Self, ratio: Self::Ratio) -> Self {
134        let a = <Self::Ratio as NumCast>::from(a).unwrap();
135        let b = <Self::Ratio as NumCast>::from(b).unwrap();
136
137        let res = a + (b - a) * ratio;
138
139        if res > NumCast::from(Self::max_value()).unwrap() {
140            Self::max_value()
141        } else if res < NumCast::from(0).unwrap() {
142            NumCast::from(0).unwrap()
143        } else {
144            NumCast::from(res).unwrap()
145        }
146    }
147}
148
149impl Lerp for u8 {
150    type Ratio = f32;
151}
152
153impl Lerp for u16 {
154    type Ratio = f32;
155}
156
157impl Lerp for u32 {
158    type Ratio = f64;
159}
160
161impl Lerp for f32 {
162    type Ratio = f32;
163
164    fn lerp(a: Self, b: Self, ratio: Self::Ratio) -> Self {
165        a + (b - a) * ratio
166    }
167}
168
169/// The pixel with an associated `ColorType`.
170/// Not all possible pixels represent one of the predefined `ColorType`s.
171pub trait PixelWithColorType: Pixel + self::private::SealedPixelWithColorType {
172    /// This pixel has the format of one of the predefined `ColorType`s,
173    /// such as `Rgb8`, `La16` or `Rgba32F`.
174    /// This is needed for automatically detecting
175    /// a color format when saving an image as a file.
176    const COLOR_TYPE: ColorType;
177}
178
179impl PixelWithColorType for Rgb<u8> {
180    const COLOR_TYPE: ColorType = ColorType::Rgb8;
181}
182impl PixelWithColorType for Rgb<u16> {
183    const COLOR_TYPE: ColorType = ColorType::Rgb16;
184}
185impl PixelWithColorType for Rgb<f32> {
186    const COLOR_TYPE: ColorType = ColorType::Rgb32F;
187}
188
189impl PixelWithColorType for Rgba<u8> {
190    const COLOR_TYPE: ColorType = ColorType::Rgba8;
191}
192impl PixelWithColorType for Rgba<u16> {
193    const COLOR_TYPE: ColorType = ColorType::Rgba16;
194}
195impl PixelWithColorType for Rgba<f32> {
196    const COLOR_TYPE: ColorType = ColorType::Rgba32F;
197}
198
199impl PixelWithColorType for Luma<u8> {
200    const COLOR_TYPE: ColorType = ColorType::L8;
201}
202impl PixelWithColorType for Luma<u16> {
203    const COLOR_TYPE: ColorType = ColorType::L16;
204}
205impl PixelWithColorType for LumaA<u8> {
206    const COLOR_TYPE: ColorType = ColorType::La8;
207}
208impl PixelWithColorType for LumaA<u16> {
209    const COLOR_TYPE: ColorType = ColorType::La16;
210}
211
212/// Prevents down-stream users from implementing the `Primitive` trait
213mod private {
214    use crate::color::*;
215
216    pub trait SealedPixelWithColorType {}
217    impl SealedPixelWithColorType for Rgb<u8> {}
218    impl SealedPixelWithColorType for Rgb<u16> {}
219    impl SealedPixelWithColorType for Rgb<f32> {}
220
221    impl SealedPixelWithColorType for Rgba<u8> {}
222    impl SealedPixelWithColorType for Rgba<u16> {}
223    impl SealedPixelWithColorType for Rgba<f32> {}
224
225    impl SealedPixelWithColorType for Luma<u8> {}
226    impl SealedPixelWithColorType for LumaA<u8> {}
227
228    impl SealedPixelWithColorType for Luma<u16> {}
229    impl SealedPixelWithColorType for LumaA<u16> {}
230}
231
232/// A generalized pixel.
233///
234/// A pixel object is usually not used standalone but as a view into an image buffer.
235pub trait Pixel: Copy + Clone {
236    /// The scalar type that is used to store each channel in this pixel.
237    type Subpixel: Primitive;
238
239    /// The number of channels of this pixel type.
240    const CHANNEL_COUNT: u8;
241
242    /// Returns the components as a slice.
243    fn channels(&self) -> &[Self::Subpixel];
244
245    /// Returns the components as a mutable slice
246    fn channels_mut(&mut self) -> &mut [Self::Subpixel];
247
248    /// A string that can help to interpret the meaning each channel
249    /// See [gimp babl](http://gegl.org/babl/).
250    const COLOR_MODEL: &'static str;
251
252    /// Returns the channels of this pixel as a 4 tuple. If the pixel
253    /// has less than 4 channels the remainder is filled with the maximum value
254    #[deprecated(since = "0.24.0", note = "Use `channels()` or `channels_mut()`")]
255    fn channels4(
256        &self,
257    ) -> (
258        Self::Subpixel,
259        Self::Subpixel,
260        Self::Subpixel,
261        Self::Subpixel,
262    );
263
264    /// Construct a pixel from the 4 channels a, b, c and d.
265    /// If the pixel does not contain 4 channels the extra are ignored.
266    #[deprecated(
267        since = "0.24.0",
268        note = "Use the constructor of the pixel, for example `Rgba([r,g,b,a])` or `Pixel::from_slice`"
269    )]
270    fn from_channels(
271        a: Self::Subpixel,
272        b: Self::Subpixel,
273        c: Self::Subpixel,
274        d: Self::Subpixel,
275    ) -> Self;
276
277    /// Returns a view into a slice.
278    ///
279    /// Note: The slice length is not checked on creation. Thus the caller has to ensure
280    /// that the slice is long enough to prevent panics if the pixel is used later on.
281    fn from_slice(slice: &[Self::Subpixel]) -> &Self;
282
283    /// Returns mutable view into a mutable slice.
284    ///
285    /// Note: The slice length is not checked on creation. Thus the caller has to ensure
286    /// that the slice is long enough to prevent panics if the pixel is used later on.
287    fn from_slice_mut(slice: &mut [Self::Subpixel]) -> &mut Self;
288
289    /// Convert this pixel to RGB
290    fn to_rgb(&self) -> Rgb<Self::Subpixel>;
291
292    /// Convert this pixel to RGB with an alpha channel
293    fn to_rgba(&self) -> Rgba<Self::Subpixel>;
294
295    /// Convert this pixel to luma
296    fn to_luma(&self) -> Luma<Self::Subpixel>;
297
298    /// Convert this pixel to luma with an alpha channel
299    fn to_luma_alpha(&self) -> LumaA<Self::Subpixel>;
300
301    /// Apply the function ```f``` to each channel of this pixel.
302    fn map<F>(&self, f: F) -> Self
303    where
304        F: FnMut(Self::Subpixel) -> Self::Subpixel;
305
306    /// Apply the function ```f``` to each channel of this pixel.
307    fn apply<F>(&mut self, f: F)
308    where
309        F: FnMut(Self::Subpixel) -> Self::Subpixel;
310
311    /// Apply the function ```f``` to each channel except the alpha channel.
312    /// Apply the function ```g``` to the alpha channel.
313    fn map_with_alpha<F, G>(&self, f: F, g: G) -> Self
314    where
315        F: FnMut(Self::Subpixel) -> Self::Subpixel,
316        G: FnMut(Self::Subpixel) -> Self::Subpixel;
317
318    /// Apply the function ```f``` to each channel except the alpha channel.
319    /// Apply the function ```g``` to the alpha channel. Works in-place.
320    fn apply_with_alpha<F, G>(&mut self, f: F, g: G)
321    where
322        F: FnMut(Self::Subpixel) -> Self::Subpixel,
323        G: FnMut(Self::Subpixel) -> Self::Subpixel;
324
325    /// Apply the function ```f``` to each channel except the alpha channel.
326    fn map_without_alpha<F>(&self, f: F) -> Self
327    where
328        F: FnMut(Self::Subpixel) -> Self::Subpixel,
329    {
330        let mut this = *self;
331        this.apply_with_alpha(f, |x| x);
332        this
333    }
334
335    /// Apply the function ```f``` to each channel except the alpha channel.
336    /// Works in place.
337    fn apply_without_alpha<F>(&mut self, f: F)
338    where
339        F: FnMut(Self::Subpixel) -> Self::Subpixel,
340    {
341        self.apply_with_alpha(f, |x| x);
342    }
343
344    /// Apply the function ```f``` to each channel of this pixel and
345    /// ```other``` pairwise.
346    fn map2<F>(&self, other: &Self, f: F) -> Self
347    where
348        F: FnMut(Self::Subpixel, Self::Subpixel) -> Self::Subpixel;
349
350    /// Apply the function ```f``` to each channel of this pixel and
351    /// ```other``` pairwise. Works in-place.
352    fn apply2<F>(&mut self, other: &Self, f: F)
353    where
354        F: FnMut(Self::Subpixel, Self::Subpixel) -> Self::Subpixel;
355
356    /// Invert this pixel
357    fn invert(&mut self);
358
359    /// Blend the color of a given pixel into ourself, taking into account alpha channels
360    fn blend(&mut self, other: &Self);
361}
362
363/// Private module for supertraits of sealed traits.
364mod seals {
365    pub trait EncodableLayout {}
366
367    impl EncodableLayout for [u8] {}
368    impl EncodableLayout for [u16] {}
369    impl EncodableLayout for [f32] {}
370}