Skip to main content

ferroui_base/utilities/
mapped_array_slice.rs

1// Copyright (c) Six Labors.
2// Licensed under the Apache License, Version 2.0.
3// Ported from: https://github.com/SixLabors/Fonts/
4
5use super::ArraySlice;
6
7/// Provides a mapped view of an underlying slice, selecting arbitrary indices
8/// from the source array.
9pub struct MappedArraySlice<T> {
10    data: ArraySlice<T>,
11    map: ArraySlice<i32>,
12}
13
14impl<T> MappedArraySlice<T> {
15    /// Creates a view of the data slice through the map slice.
16    ///
17    /// In a debug build, panics when the map is longer than the data.
18    pub fn new(data: &ArraySlice<T>, map: &ArraySlice<i32>) -> Self {
19        if cfg!(debug_assertions) && map.length() > data.length() {
20            panic!("Specified argument was out of the range of valid values. (Parameter 'map')");
21        }
22
23        Self { data: data.clone(), map: map.clone() }
24    }
25
26    /// Gets the number of items in the map.
27    pub fn length(&self) -> usize {
28        self.map.length()
29    }
30
31    /// Writes the specified element of the slice.
32    ///
33    /// Panics when the index is not less than [`length`](Self::length).
34    pub fn set(&self, index: usize, value: T) {
35        let mapped = self.map.get(index);
36        self.data.set(mapped as usize, value);
37    }
38}
39
40impl<T: Copy> MappedArraySlice<T> {
41    /// Reads the specified element of the slice.
42    ///
43    /// Panics when the index is not less than [`length`](Self::length).
44    pub fn get(&self, index: usize) -> T {
45        self.data.get(self.map.get(index) as usize)
46    }
47}
48
49#[cfg(test)]
50mod tests {
51    // Not from upstream: the original has no tests of this type.
52    use super::*;
53
54    #[test]
55    fn reads_and_writes_through_the_map() {
56        let data = ArraySlice::new(vec![10, 20, 30, 40]);
57        let map = ArraySlice::new(vec![3, 1]);
58        let target = MappedArraySlice::new(&data, &map);
59
60        assert_eq!(2, target.length());
61        assert_eq!(40, target.get(0));
62        assert_eq!(20, target.get(1));
63
64        target.set(1, 21);
65        assert_eq!(21, data.get(1));
66    }
67}