mln-rs-style 0.0.21

Part of mln-rs, a MapLibre map renderer written in Rust. Depend on mln-rs instead.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
// Decoding images and encoding PNGs live in //crates/mln_engine/src/image,
// so that this file stays dependency-free.

use std::fmt;
use std::marker::PhantomData;

use geometry::Point;

use crate::size::Size;

#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub enum ImageAlphaMode {
    Unassociated,
    Premultiplied,
    /// Alpha-channel only.
    Exclusive,
}

/// The alpha mode of an [`Image`], as its type parameter.
pub trait AlphaMode {
    const MODE: ImageAlphaMode;
    /// The bytes per pixel: 1 for `Exclusive`, 4 otherwise.
    const CHANNELS: usize;
}

#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
pub struct Unassociated;
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
pub struct Premultiplied;
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
pub struct Exclusive;

impl AlphaMode for Unassociated {
    const MODE: ImageAlphaMode = ImageAlphaMode::Unassociated;
    const CHANNELS: usize = 4;
}
impl AlphaMode for Premultiplied {
    const MODE: ImageAlphaMode = ImageAlphaMode::Premultiplied;
    const CHANNELS: usize = 4;
}
impl AlphaMode for Exclusive {
    const MODE: ImageAlphaMode = ImageAlphaMode::Exclusive;
    const CHANNELS: usize = 1;
}

/// Why an image operation failed.
#[derive(Clone, Copy, Debug, PartialEq, Eq, thiserror::Error)]
pub enum ImageError {
    /// The pixel buffer's length doesn't match the image's size.
    #[error("the pixels don't match the image's size")]
    WrongLength,
    /// The source or destination image has no pixels.
    #[error("the image has no pixels")]
    NoPixels,
    /// The rectangle doesn't fit inside the source or destination image.
    #[error("the rectangle is outside the image")]
    OutsideImage,
}

/// An image: `size` plus `channels * width * height` bytes.
///
/// An empty `data` is an image without pixels, such as the default image.
///
/// An image crosses with its pixels as a payload (serialization/payload.rs),
/// and only images whose pixels fill their size read back.
pub struct Image<M: AlphaMode> {
    pub size: Size,
    pub data: Vec<u8>,
    _mode: PhantomData<M>,
}

impl<M: AlphaMode> mln_wire::Wire for Image<M> {
    fn write(&self, w: &mut mln_wire::Writer) {
        self.size.write(w);
        mln_wire::payload::bytes::write(&self.data, w);
    }

    fn read(r: &mut mln_wire::Reader<'_>) -> Option<Self> {
        let size = Size::read(r)?;
        let data = mln_wire::payload::bytes::read(r)?;
        Image::try_from(ImageParts { size, data }).ok().or_else(|| r.fail("pixels that don't fill their image"))
    }
}

/// What `Image` is read from.
struct ImageParts {
    size: Size,
    data: Vec<u8>,
}

impl<M: AlphaMode> TryFrom<ImageParts> for Image<M> {
    type Error = String;

    fn try_from(ImageParts { size, data }: ImageParts) -> Result<Self, String> {
        // In u64: on wasm32 `bytes()` would wrap for a large size.
        let bytes =
            u64::from(size.width).checked_mul(u64::from(size.height)).and_then(|n| n.checked_mul(M::CHANNELS as u64));
        if bytes != Some(data.len() as u64) {
            return Err(format!("{} bytes for a {}x{} image", data.len(), size.width, size.height));
        }
        Ok(Image::from_vec(size, data))
    }
}

pub type UnassociatedImage = Image<Unassociated>;
pub type PremultipliedImage = Image<Premultiplied>;
pub type AlphaImage = Image<Exclusive>;

impl<M: AlphaMode> Image<M> {
    pub const CHANNELS: usize = M::CHANNELS;

    /// An image of zeroed pixels.
    #[must_use]
    pub fn new(size: Size) -> Self {
        let bytes = M::CHANNELS * size.width as usize * size.height as usize;
        Image { size, data: vec![0; bytes], _mode: PhantomData }
    }

    pub fn from_slice(size: Size, src: &[u8]) -> Result<Self, ImageError> {
        let mut image = Image { size, data: Vec::new(), _mode: PhantomData };
        if src.len() != image.bytes() {
            return Err(ImageError::WrongLength);
        }
        if image.bytes() != 0 {
            image.data = src.to_vec();
        }
        Ok(image)
    }

    /// Takes the buffer as is, without checking its length against `size`.
    #[must_use]
    pub fn from_vec(size: Size, data: Vec<u8>) -> Self {
        Image { size, data, _mode: PhantomData }
    }

    /// Splits the image into its size and pixel buffer, which can make an
    /// image of another alpha mode.
    #[must_use]
    pub fn into_parts(self) -> (Size, Vec<u8>) {
        (self.size, self.data)
    }

    #[must_use]
    pub fn valid(&self) -> bool {
        !self.size.is_empty() && !self.data.is_empty()
    }

    #[must_use]
    pub fn stride(&self) -> usize {
        M::CHANNELS * self.size.width as usize
    }

    #[must_use]
    pub fn bytes(&self) -> usize {
        self.stride() * self.size.height as usize
    }

    pub fn fill(&mut self, value: u8) {
        if self.valid() {
            let bytes = self.bytes();
            self.data[..bytes].fill(value);
        }
    }

    pub fn resize(&mut self, size: Size) {
        if self.size == size {
            return;
        }
        let mut new_image = Image::<M>::new(size);
        if !size.is_empty() && self.valid() {
            new_image.fill(0);
            let copy_size =
                Size::new(std::cmp::min(self.size.width, size.width), std::cmp::min(self.size.height, size.height));
            // Both rectangles are in bounds by construction.
            Self::copy(self, &mut new_image, Point::new(0, 0), Point::new(0, 0), copy_size)
                .expect("resize copy is in bounds");
        }
        *self = new_image;
    }

    /// Clears the rect area specified by `pt` and `size` from `dst_img`.
    pub fn clear(dst_img: &mut Self, pt: Point<u32>, size: Size) -> Result<(), ImageError> {
        if size.is_empty() {
            return Ok(());
        }

        if !dst_img.valid() {
            return Err(ImageError::NoPixels);
        }

        if size.width > dst_img.size.width
            || size.height > dst_img.size.height
            || pt.x > dst_img.size.width - size.width
            || pt.y > dst_img.size.height - size.height
        {
            return Err(ImageError::OutsideImage);
        }

        let stride = dst_img.stride();
        for y in 0..size.height {
            let dst_offset = (pt.y + y) as usize * stride + pt.x as usize * M::CHANNELS;
            dst_img.data[dst_offset..dst_offset + size.width as usize * M::CHANNELS].fill(0);
        }
        Ok(())
    }

    /// Copy image data within `rect` from `src` to the rectangle of the same
    /// size at `pt` in `dst`. If the specified bounds exceed the bounds of the
    /// source or destination, return `ImageError::OutsideImage`. Borrowing
    /// rules rule out copying within a single image.
    pub fn copy(
        src_img: &Self,
        dst_img: &mut Self,
        src_pt: Point<u32>,
        dst_pt: Point<u32>,
        size: Size,
    ) -> Result<(), ImageError> {
        if size.is_empty() {
            return Ok(());
        }

        if !src_img.valid() {
            return Err(ImageError::NoPixels);
        }

        if !dst_img.valid() {
            return Err(ImageError::NoPixels);
        }

        if size.width > src_img.size.width
            || size.height > src_img.size.height
            || src_pt.x > src_img.size.width - size.width
            || src_pt.y > src_img.size.height - size.height
        {
            return Err(ImageError::OutsideImage);
        }

        if size.width > dst_img.size.width
            || size.height > dst_img.size.height
            || dst_pt.x > dst_img.size.width - size.width
            || dst_pt.y > dst_img.size.height - size.height
        {
            return Err(ImageError::OutsideImage);
        }

        let src_stride = src_img.stride();
        let dst_stride = dst_img.stride();
        let row = size.width as usize * M::CHANNELS;
        for y in 0..size.height {
            let src_offset = (src_pt.y + y) as usize * src_stride + src_pt.x as usize * M::CHANNELS;
            let dst_offset = (dst_pt.y + y) as usize * dst_stride + dst_pt.x as usize * M::CHANNELS;
            dst_img.data[dst_offset..dst_offset + row].copy_from_slice(&src_img.data[src_offset..src_offset + row]);
        }
        Ok(())
    }

    fn pixels(&self) -> &[u8] {
        let bytes = self.bytes();
        self.data.get(..bytes).unwrap_or(&self.data)
    }
}

impl<M: AlphaMode> Default for Image<M> {
    fn default() -> Self {
        Image { size: Size::default(), data: Vec::new(), _mode: PhantomData }
    }
}

impl<M: AlphaMode> Clone for Image<M> {
    fn clone(&self) -> Self {
        Image { size: self.size, data: self.data.clone(), _mode: PhantomData }
    }
}

/// Images are equal when their sizes and pixels are; bytes of `data` past the
/// pixels don't count.
impl<M: AlphaMode> PartialEq for Image<M> {
    fn eq(&self, other: &Self) -> bool {
        self.size == other.size && self.pixels() == other.pixels()
    }
}

impl<M: AlphaMode> Eq for Image<M> {}

impl<M: AlphaMode> fmt::Debug for Image<M> {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("Image")
            .field("mode", &M::MODE)
            .field("size", &self.size)
            .field("data.len()", &self.data.len())
            .finish()
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    // Ports TEST(Image, Resize) from test/util/image.test.cpp.
    // gtest: Image.Resize
    #[test]
    fn resize() {
        let mut image = AlphaImage::new(Size::new(0, 0));

        image.resize(Size::new(1, 1));
        assert_eq!(image.size, Size::new(1, 1));

        image.fill(100);
        image.resize(Size::new(2, 1));
        assert_eq!(image.size, Size::new(2, 1));
        assert_eq!(image.data[0], 100);
        assert_eq!(image.data[1], 0);

        image.resize(Size::new(0, 0));
        assert_eq!(image.size, Size::new(0, 0));
    }

    // Ports TEST(Image, Copy) from test/util/image.test.cpp.
    // gtest: Image.Copy
    #[test]
    fn copy() {
        let src5 = PremultipliedImage::new(Size::new(5, 5));
        let mut dst5 = PremultipliedImage::new(Size::new(5, 5));
        let src10 = PremultipliedImage::new(Size::new(10, 10));
        let mut dst10 = PremultipliedImage::new(Size::new(10, 10));
        let p = |x, y| Point::new(x, y);
        let s = Size::new;
        let out_of_range = |r: Result<(), ImageError>| matches!(r, Err(ImageError::OutsideImage));

        assert!(out_of_range(PremultipliedImage::copy(&src5, &mut dst10, p(0, 0), p(0, 0), s(6, 1))));
        assert!(out_of_range(PremultipliedImage::copy(&src5, &mut dst10, p(0, 0), p(0, 0), s(1, 6))));
        assert!(out_of_range(PremultipliedImage::copy(&src5, &mut dst10, p(1, 1), p(0, 0), s(5, 1))));
        assert!(out_of_range(PremultipliedImage::copy(&src5, &mut dst10, p(1, 1), p(0, 0), s(1, 5))));

        assert!(out_of_range(PremultipliedImage::copy(&src10, &mut dst5, p(0, 0), p(0, 0), s(6, 1))));
        assert!(out_of_range(PremultipliedImage::copy(&src10, &mut dst5, p(0, 0), p(0, 0), s(1, 6))));
        assert!(out_of_range(PremultipliedImage::copy(&src10, &mut dst5, p(0, 0), p(1, 1), s(5, 1))));
        assert!(out_of_range(PremultipliedImage::copy(&src10, &mut dst5, p(0, 0), p(1, 1), s(1, 5))));

        let max = u32::MAX;

        let src10b = src10.clone();
        assert!(out_of_range(PremultipliedImage::copy(&src10b, &mut dst10, p(max, 0), p(0, 0), s(1, 1))));
        assert!(out_of_range(PremultipliedImage::copy(&src10b, &mut dst10, p(0, max), p(0, 0), s(1, 1))));
        assert!(out_of_range(PremultipliedImage::copy(&src10b, &mut dst10, p(0, 0), p(max, 0), s(1, 1))));
        assert!(out_of_range(PremultipliedImage::copy(&src10b, &mut dst10, p(0, 0), p(0, max), s(1, 1))));

        assert!(out_of_range(PremultipliedImage::copy(&src10b, &mut dst10, p(1, 0), p(0, 0), s(max, 1))));
        assert!(out_of_range(PremultipliedImage::copy(&src10b, &mut dst10, p(0, 1), p(0, 0), s(1, max))));
        assert!(out_of_range(PremultipliedImage::copy(&src10b, &mut dst10, p(0, 0), p(1, 0), s(max, 1))));
        assert!(out_of_range(PremultipliedImage::copy(&src10b, &mut dst10, p(0, 0), p(0, 1), s(1, max))));
    }

    // Ports TEST(Image, Move): a Rust move leaves nothing behind to inspect;
    // `std::mem::take` is the equivalent of the C++ moved-from state.
    // gtest: Image.Move
    #[test]
    fn move_() {
        let mut rgba = UnassociatedImage::new(Size::new(1, 1));
        rgba.data.copy_from_slice(&[255, 254, 253, 128]);

        let moved = std::mem::take(&mut rgba);

        assert_eq!(rgba.size.width, 0);
        assert_eq!(rgba.data, Vec::<u8>::new());
        assert_eq!(moved.data[1], 254);
        assert_eq!(moved.size.width, 1);
    }

    // Not in the C++ suite: the remaining Image members.
    #[test]
    fn construct_clear_equality() {
        let image = PremultipliedImage::new(Size::new(2, 3));
        assert_eq!((image.bytes(), image.stride()), (24, 8));
        assert!(image.valid() && image.data.iter().all(|&b| b == 0));
        assert_eq!(AlphaImage::new(Size::new(2, 3)).bytes(), 6);
        assert!(!PremultipliedImage::default().valid());
        assert!(!PremultipliedImage::new(Size::new(0, 3)).valid());
        assert_eq!(PremultipliedImage::from_slice(Size::new(1, 1), &[1, 2, 3]), Err(ImageError::WrongLength));
        assert_eq!(PremultipliedImage::from_slice(Size::new(1, 1), &[1, 2, 3, 4]).unwrap().data, vec![1, 2, 3, 4]);

        let mut image = PremultipliedImage::new(Size::new(3, 3));
        image.fill(7);
        PremultipliedImage::clear(&mut image, Point::new(1, 1), Size::new(2, 2)).unwrap();
        assert_eq!(&image.data[0..16], &[7; 16]);
        assert_eq!(&image.data[16..24], &[0; 8]);
        assert_eq!(&image.data[24..28], &[7; 4]);
        assert_eq!(&image.data[28..36], &[0; 8]);
        assert!(matches!(
            PremultipliedImage::clear(&mut image, Point::new(2, 2), Size::new(2, 2)),
            Err(ImageError::OutsideImage)
        ));
        let mut empty = PremultipliedImage::default();
        assert!(matches!(
            PremultipliedImage::clear(&mut empty, Point::new(0, 0), Size::new(1, 1)),
            Err(ImageError::NoPixels)
        ));
        PremultipliedImage::clear(&mut empty, Point::new(0, 0), Size::new(0, 1)).unwrap();

        let mut src = UnassociatedImage::new(Size::new(4, 4));
        let mut dst = UnassociatedImage::new(Size::new(4, 4));
        src.fill(0xFF);
        UnassociatedImage::copy(&src, &mut dst, Point::new(0, 0), Point::new(1, 1), Size::new(2, 2)).unwrap();
        for y in 0..4usize {
            for x in 0..4usize {
                let inside = (1..3).contains(&x) && (1..3).contains(&y);
                let px = &dst.data[(y * 4 + x) * 4..(y * 4 + x) * 4 + 4];
                assert_eq!(px, if inside { &[0xFF; 4] } else { &[0; 4] }, "({x}, {y})");
            }
        }

        let a = PremultipliedImage::from_vec(Size::new(1, 1), vec![1, 2, 3, 4]);
        assert_eq!(a, PremultipliedImage::from_vec(Size::new(1, 1), vec![1, 2, 3, 4]));
        assert_ne!(a, PremultipliedImage::from_vec(Size::new(1, 1), vec![1, 2, 3, 5]));
    }
}