libsixel_rs/quant/
box_vector.rs

1use alloc::vec::Vec;
2
3use crate::std::{
4    cmp,
5    ops::{Index, IndexMut},
6};
7
8/// Sort [BoxVector] by sum.
9pub fn sum_compare(lhs: &Box0, rhs: &Box0) -> cmp::Ordering {
10    rhs.sum.cmp(&lhs.sum)
11}
12
13/// Represents a box of [ColorMap](super::ColorMap) pixels.
14#[derive(Copy, Clone, Debug, Default, PartialEq)]
15#[repr(C)]
16pub struct Box0 {
17    /// Index in the [ColorMap](super::ColorMap).
18    pub ind: usize,
19    /// Colors of this box.
20    pub colors: usize,
21    /// Sum of pixel values.
22    pub sum: usize,
23}
24
25impl Box0 {
26    /// Creates a new [Box0].
27    pub const fn new() -> Self {
28        Self {
29            ind: 0,
30            colors: 0,
31            sum: 0,
32        }
33    }
34
35    /// Creates a new [Box0] with the given parameters.
36    pub const fn create(ind: usize, colors: usize, sum: usize) -> Self {
37        Self { ind, colors, sum }
38    }
39}
40
41/// Represents a list of [Box0].
42#[derive(Clone, Debug, Default, PartialEq)]
43pub struct BoxVector(pub Vec<Box0>);
44
45impl BoxVector {
46    /// Creates a new [BoxVector].
47    pub const fn new() -> Self {
48        Self(Vec::new())
49    }
50
51    /// Creates a new [BoxVector] with a provided capacity.
52    pub fn with_capacity(cap: usize) -> Self {
53        Self(Vec::with_capacity(cap))
54    }
55
56    /// Creates a new [BoxVector] with the give parameters
57    pub fn create(ind: usize, colors: usize, sum: usize) -> Self {
58        Self([Box0::create(ind, colors, sum)].into())
59    }
60
61    /// Gets a reference to the inner [BoxVector] type.
62    pub fn as_inner(&self) -> &Vec<Box0> {
63        &self.0
64    }
65
66    /// Gets a mutable reference to the inner [BoxVector] type.
67    pub fn as_inner_mut(&mut self) -> &mut Vec<Box0> {
68        &mut self.0
69    }
70}
71
72impl AsRef<[Box0]> for BoxVector {
73    fn as_ref(&self) -> &[Box0] {
74        self.0.as_ref()
75    }
76}
77
78impl AsMut<[Box0]> for BoxVector {
79    fn as_mut(&mut self) -> &mut [Box0] {
80        self.0.as_mut()
81    }
82}
83
84impl Index<usize> for BoxVector {
85    type Output = Box0;
86
87    fn index(&self, idx: usize) -> &Self::Output {
88        &self.0[idx]
89    }
90}
91
92impl IndexMut<usize> for BoxVector {
93    fn index_mut(&mut self, idx: usize) -> &mut Self::Output {
94        &mut self.0[idx]
95    }
96}