grixy 0.6.0-alpha.2

Zero-cost 2D grids for embedded systems and graphics
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
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
//! Transformation operations for grids.
//!
//! [`GridConvertExt`] is automatically implemented for all types that implement reading, or in the
//! case of [`blend`][GridConvertExt::blend], reading _and_ writing from a grid, and provides
//! additional methods for lazily transforming grids (leaving the original grid unchanged, and
//! without any allocations).
//!
//! Operations include:
//!
//! - [`blend`](GridConvertExt::blend): Creates a blended version of the grid, applying a blend function when setting elements.
//! - [`copied`](GridConvertExt::copied): Creates a grid that copies all of its elements.
//! - [`flatten`](GridConvertExt::flatten): Collects the elements of the grid into a new buffer.
//! - [`map`](GridConvertExt::map): Creates a grid that applies a mapping function to its elements.
//! - [`scale`](GridConvertExt::scale): Creates a scaled version of the grid.
//! - [`view`](GridConvertExt::view): Creates a view of the grid over a specified rectangular region.
//!
//! ## Chaining transformations
//!
//! Methods on [`GridConvertExt`] can be chained together to create complex transformations, as
//! they consume the grid and return a new one. This allows for a functional style of programming
//! where each transformation is applied in sequence, without modifying the original grid:
//!
//! ```rust
//! use grixy::prelude::*;
//!
//! let grid = GridBuf::new_filled(3, 3, 1)
//!   .copied()
//!   .map(|x| x * 2)
//!   .view(Rect::from_ltwh(0, 0, 2, 2))
//!   .scale(2);
//!
//! assert_eq!(grid.get(Pos::new(1, 1)), Some(2));
//! ```
//!
//! ## Sharing a grid
//!
//! To share the original grid, you can use `Rc` or `Arc` to wrap it:
//!
//! ```rust
//! // Or alloc::rc::Rc;
//! use std::rc::Rc;
//! use grixy::prelude::*;
//!
//! let rc = Rc::new(GridBuf::new_filled(3, 3, 1));
//!
//! let rf = Rc::clone(&rc);
//! let chained = rf
//!   .copied()
//!   .map(|x| x * 2)
//!   .view(Rect::from_ltwh(0, 0, 2, 2))
//!   .scale(2);
//! assert_eq!(chained.get(Pos::new(1, 1)), Some(2));
//!
//! // Original grid is still accessible
//! assert_eq!(rc.get(Pos::new(1, 1)), Some(&1));
//! ```

use core::marker::PhantomData;

#[cfg(feature = "buffer")]
use crate::ops::{ExactSizeGrid, layout};
use crate::{
    core::Rect,
    ops::{GridRead, GridWrite},
};

mod blended;
pub use blended::Blended;

mod copied;
pub use copied::Copied;

mod mapped;
pub use mapped::Mapped;

mod scaled;
pub use scaled::Scaled;

mod viewed;
pub use viewed::Viewed;

pub mod blend;

/// Extension trait for converting grids into different forms.
pub trait GridConvertExt: GridRead {
    /// Creates a grid that copies all of its elements.
    ///
    /// This is useful when you have a `GridRead<&T>`, but need a `GridRead<T>`.
    ///
    /// ## Examples
    ///
    /// ```rust
    /// use grixy::prelude::*;
    ///
    /// // By default, `GridBuf` returns references to its elements (similar to `Vec`).
    /// let grid = GridBuf::new_filled(3, 3, 1);
    /// assert_eq!(grid.get(Pos::new(1, 1)), Some(&1));
    ///
    /// // We can create a `GridRead` that returns owned copies of the elements.
    /// let copied = grid.copied();
    /// assert_eq!(copied.get(Pos::new(1, 1)), Some(1));
    /// ```
    fn copied<'a, T>(self) -> Copied<T, Self>
    where
        Self: Sized + GridRead<Element<'a> = &'a T> + 'a,
        T: Copy + 'a,
    {
        Copied {
            source: self,
            _element: PhantomData,
        }
    }

    /// Creates a grid that applies a mapping function to its elements.
    ///
    /// This is useful when you want to transform the elements of a grid lazily.
    ///
    /// ## Examples
    ///
    /// ```rust
    /// use grixy::prelude::*;
    ///
    /// let grid = GridBuf::new_filled(3, 3, 1);
    /// let mapped = grid.map(|&x| x * 2);
    /// assert_eq!(mapped.get(Pos::new(1, 1)), Some(2));
    /// ```
    fn map<F, T>(self, map_fn: F) -> Mapped<F, Self, T>
    where
        Self: Sized,
        F: Fn(Self::Element<'_>) -> T,
    {
        Mapped {
            source: self,
            map_fn,
            _element: PhantomData,
        }
    }

    /// Creates a view of the grid over a specified rectangular region.
    ///
    /// The view is a lightweight wrapper that allows access to a subset of the grid's elements.
    ///
    /// ## Examples
    ///
    /// ```rust
    /// use grixy::prelude::*;
    ///
    /// let grid = GridBuf::new_filled(3, 3, 1);
    /// let view = grid.view(Rect::from_ltwh(0, 0, 2, 2));
    /// assert_eq!(view.get(Pos::new(1, 1)), Some(&1));
    /// assert_eq!(view.get(Pos::new(2, 2)), None);
    /// ```
    fn view(self, bounds: Rect) -> Viewed<Self>
    where
        Self: Sized,
    {
        Viewed {
            source: self,
            bounds,
        }
    }

    /// Creates a scaled version of the grid.
    ///
    /// The `scale` factor determines how many cells in the original grid correspond to one cell
    /// in the scaled grid. For example, a scale factor of 2 means that each cell in the scaled grid
    /// corresponds to a 2x2 block of cells in the original grid.
    ///
    /// ## Examples
    ///
    /// ```rust
    /// use grixy::prelude::*;
    ///
    /// let grid = GridBuf::new_filled(2, 2, 1);
    /// let scaled = grid.scale(2);
    /// assert_eq!(scaled.get(Pos::new(0, 0)), Some(&1));
    /// assert_eq!(scaled.get(Pos::new(1, 1)), Some(&1));
    /// assert_eq!(scaled.get(Pos::new(2, 2)), Some(&1));
    /// assert_eq!(scaled.get(Pos::new(3, 3)), Some(&1));
    /// assert_eq!(scaled.get(Pos::new(4, 4)), None);
    /// ```
    fn scale(self, factor: usize) -> Scaled<Self>
    where
        Self: Sized,
    {
        Scaled {
            source: self,
            scale: factor,
        }
    }

    /// Collects the elements of the grid into a new buffer.
    ///
    /// This method is only available when the `buffer` feature is enabled.
    ///
    /// ## Examples
    ///
    /// ```rust
    /// use grixy::prelude::*;
    ///
    /// let grid = GridBuf::new_filled(3, 3, 1);
    /// let collected = grid.copied().flatten::<Vec<_>, RowMajor>();
    /// assert_eq!(collected.get(Pos::new(1, 1)), Some(&1));
    /// assert_eq!(collected.get(Pos::new(3, 3)), None);
    /// ```
    #[cfg(feature = "buffer")]
    fn flatten<'a, B, L>(&'a self) -> crate::buf::GridBuf<Self::Element<'a>, B, L>
    where
        B: FromIterator<Self::Element<'a>> + AsRef<[Self::Element<'a>]>,
        L: layout::Linear,
        Self: Sized,
        Self: ExactSizeGrid,
        Self::Element<'a>: Copy,
    {
        use crate::core::Rect;

        let iter = self.iter_rect(Rect::from_ltwh(0, 0, self.width(), self.height()));
        let elem = iter.collect::<B>();
        crate::buf::GridBuf::from_buffer(elem, self.width())
    }

    /// Creates a blended version of this grid, applying a blend function when setting elements.
    ///
    /// This is useful for operations like blending colors or combining values.
    ///
    /// ## Examples
    ///
    /// ```rust
    /// use grixy::prelude::*;
    ///
    /// let mut grid = GridBuf::new_filled(3, 3, 1);
    /// let blend_fn = |current: &i32, new: i32| current + new;
    /// let mut blended = grid.blend(blend_fn);
    ///
    /// blended.set(Pos::new(1, 1), 5).unwrap();
    /// assert_eq!(blended.get(Pos::new(1, 1)), Some(&6));
    /// ```
    fn blend<F>(&mut self, blend_fn: F) -> Blended<'_, Self, F>
    where
        Self: Sized + GridRead + GridWrite,
        F: Fn(
            <Self as GridRead>::Element<'_>,
            <Self as GridWrite>::Element,
        ) -> <Self as GridWrite>::Element,
    {
        Blended {
            source: self,
            blend_fn,
        }
    }
}

impl<T> GridConvertExt for T where T: GridRead {}

#[cfg(test)]
mod tests {
    extern crate alloc;

    use crate::{
        buf::GridBuf,
        core::{Pos, Rect},
        ops::{GridBase as _, layout::RowMajor},
    };
    use alloc::{vec, vec::Vec};
    use ixy::HasSize as _;

    use super::*;

    #[test]
    fn grid_copied_size() {
        let grid = GridBuf::<u8, _, _>::new(10, 10).copied();
        let (size, _) = grid.size_hint();
        assert_eq!(size.width(), 10);
        assert_eq!(size.height(), 10);
    }

    #[test]
    fn grid_copied_get() {
        let grid = GridBuf::new_filled(3, 3, 1);
        let copied = grid.copied();
        assert_eq!(copied.get(Pos::new(1, 1)), Some(1));
        assert_eq!(copied.get(Pos::new(3, 3)), None);
    }

    #[test]
    fn grid_copied_iter_rect() {
        let grid = GridBuf::new_filled(3, 3, 1);
        let copied = grid.copied();
        let elements: Vec<_> = copied.iter_rect(Rect::from_ltwh(0, 0, 2, 2)).collect();
        assert_eq!(elements, vec![1, 1, 1, 1]);
    }

    #[test]
    fn grid_mapped_size() {
        let grid = GridBuf::<u8, _, _>::new(10, 10);
        let mapped = grid.map(|x| x * 2);
        let (size, _) = mapped.size_hint();
        assert_eq!(size.width(), 10);
        assert_eq!(size.height(), 10);
    }

    #[test]
    fn grid_mapped_get() {
        let grid = GridBuf::new_filled(3, 3, 1);
        let mapped = grid.map(|x| x * 2);
        assert_eq!(mapped.get(Pos::new(1, 1)), Some(2));
        assert_eq!(mapped.get(Pos::new(3, 3)), None);
    }

    #[test]
    fn grid_mapped_iter_rect() {
        let grid = GridBuf::new_filled(3, 3, 1);
        let mapped = grid.map(|x| x * 2);
        let elements: Vec<_> = mapped.iter_rect(Rect::from_ltwh(0, 0, 2, 2)).collect();
        assert_eq!(elements, vec![2, 2, 2, 2]);
    }

    #[test]
    fn grid_view_size() {
        let grid = GridBuf::<u8, _, _>::new(10, 10);
        let view = grid.view(Rect::from_ltwh(0, 0, 5, 5));
        let (size, _) = view.size_hint();
        assert_eq!(size.width(), 5);
        assert_eq!(size.height(), 5);
    }

    #[test]
    fn grid_view_get() {
        let grid = GridBuf::new_filled(3, 3, 1);
        let view = grid.view(Rect::from_ltwh(0, 0, 2, 2));
        assert_eq!(view.get(Pos::new(1, 1)), Some(&1));
        assert_eq!(view.get(Pos::new(2, 2)), None);
    }

    #[test]
    fn grid_view_iter_rect() {
        let grid = GridBuf::new_filled(3, 3, 1);
        let view = grid.view(Rect::from_ltwh(0, 0, 2, 2));
        let elements: Vec<_> = view.iter_rect(Rect::from_ltwh(0, 0, 2, 2)).collect();
        assert_eq!(elements, &[&1, &1, &1, &1]);
    }

    #[test]
    fn grid_scaled_size() {
        let grid = GridBuf::<u8, _, _>::new(10, 10);
        let scaled = grid.scale(2);
        let (size, _) = scaled.size_hint();
        assert_eq!(size.width(), 20);
        assert_eq!(size.height(), 20);
    }

    #[test]
    fn grid_scaled_get() {
        let grid = GridBuf::<_, _, RowMajor>::from_buffer(vec![1, 2, 3, 4], 2);
        let scaled = grid.scale(2);
        assert_eq!(scaled.get(Pos::new(1, 1)), Some(&1));
        assert_eq!(scaled.get(Pos::new(2, 2)), Some(&4));
        assert_eq!(scaled.get(Pos::new(3, 3)), Some(&4));
        assert_eq!(scaled.get(Pos::new(4, 4)), None);
    }

    #[test]
    fn grid_scaled_iter_rect() {
        let grid = GridBuf::<_, _, RowMajor>::from_buffer(vec![1, 2, 3, 4], 2);
        let scaled = grid.scale(2);
        let elements: Vec<_> = scaled.iter_rect(Rect::from_ltwh(0, 0, 4, 4)).collect();

        #[rustfmt::skip]
        assert_eq!(elements, &[
            &1, &1, &2, &2,
            &1, &1, &2, &2,
            &3, &3, &4, &4,
            &3, &3, &4, &4,
        ]);
    }

    #[test]
    fn grid_blended_size() {
        let mut grid = GridBuf::<u8, _, _>::new(10, 10);
        let mut blended = grid.blend(|current, new| current + new);
        blended.set(Pos::new(1, 1), 5).unwrap();
        let (size, _) = blended.size_hint();
        assert_eq!(size.width(), 10);
        assert_eq!(size.height(), 10);
    }

    #[test]
    fn grid_write_blended_set() {
        let mut grid = GridBuf::new_filled(3, 3, 0);
        let mut blended = grid.blend(|current, new| current + new);
        blended.set(Pos::new(1, 1), 5).unwrap();
        assert_eq!(blended.get(Pos::new(1, 1)), Some(&5));
        blended.set(Pos::new(1, 1), 3).unwrap();
        assert_eq!(blended.get(Pos::new(1, 1)), Some(&8));
    }

    #[test]
    fn grid_write_blended_iter_rect() {
        let mut grid = GridBuf::new_filled(3, 3, 0);
        let mut blended = grid.blend(|current, new| current + new);
        blended.set(Pos::new(1, 1), 5).unwrap();
        blended.set(Pos::new(2, 2), 3).unwrap();
        let elements: Vec<_> = blended.iter_rect(Rect::from_ltwh(0, 0, 3, 3)).collect();
        assert_eq!(elements, vec![&0, &0, &0, &0, &5, &0, &0, &0, &3]);
    }

    #[test]
    fn grid_chained_operations() {
        let grid = GridBuf::new_filled(3, 3, 1)
            .copied()
            .map(|x| x * 2)
            .view(Rect::from_ltwh(0, 0, 2, 2))
            .scale(2);

        assert_eq!(grid.get(Pos::new(1, 1)), Some(2));
    }

    #[test]
    fn grid_rc() {
        use alloc::rc::Rc;

        let rc = Rc::new(GridBuf::new_filled(3, 3, 1));
        let rf = Rc::clone(&rc);
        let chained = rf
            .copied()
            .map(|x| x * 2)
            .view(Rect::from_ltwh(0, 0, 2, 2))
            .scale(2);
        assert_eq!(chained.get(Pos::new(1, 1)), Some(2));
    }

    #[test]
    fn grid_arc() {
        use alloc::sync::Arc;

        let arc = Arc::new(GridBuf::new_filled(3, 3, 1));
        let af = Arc::clone(&arc);
        let chained = af
            .copied()
            .map(|x| x * 2)
            .view(Rect::from_ltwh(0, 0, 2, 2))
            .scale(2);
        assert_eq!(chained.get(Pos::new(1, 1)), Some(2));
    }
}