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
// palette.rs   Color palette
//
// Copyright (c) 2019  Douglas P Lau
//
use crate::{Ch8, Format};

/// Color table for use with indexed `Raster`s.
#[derive(Clone)]
pub struct Palette<F>
    where F: Format<Chan = Ch8>
{
    table: Vec<F>,
    threshold_fn: fn(usize) -> F,
}

impl<F> Palette<F>
    where F: Format<Chan = Ch8>
{
    /// Create a new color `Palette`.
    ///
    /// * `capacity` Maximum number of entries.
    pub fn new(capacity: usize) -> Self {
        let table = Vec::with_capacity(capacity);
        let threshold_fn = |_| F::default();
        Palette { table, threshold_fn }
    }
    /// Get the number of entries.
    pub fn len(&self) -> usize {
        self.table.len()
    }
    /// Set the threshold function for matching entries.
    ///
    /// * `threshold_fn` Called when checking whether a color matches an
    ///                  existing entry.  The parameter is the palette table
    ///                  size.  Returns the maximum `Channel`-wise difference
    ///                  to match.
    pub fn set_threshold_fn(&mut self, threshold_fn: fn(usize) -> F) {
        self.threshold_fn = threshold_fn;
    }
    /// Get view of a color slice as a `u8` slice.
    fn u8_slice(colors: &[F]) -> &[u8] {
        unsafe { colors.align_to::<u8>().1 }
    }
    /// Get view of `Palette` as a `u8` slice.
    pub fn as_u8_slice(&self) -> &[u8] {
        Self::u8_slice(&self.table)
    }
    /// Get a `Palette` entry.
    ///
    /// * `i` Index of entry.
    pub fn entry(&self, i: usize) -> Option<F> {
        if i < self.table.len() {
            Some(self.table[i])
        } else {
            None
        }
    }
    /// Set a `Palette` entry.
    ///
    /// The table is searched for the best matching color within the threshold.
    /// If none found, a new entry is added.
    ///
    /// * `clr` Color to lookup or add.
    ///
    /// # Returns
    /// Index of best matching or added entry if successful.  Otherwise, when
    /// no matches are found and the table is full, `None` is returned.
    pub fn set_entry(&mut self, clr: F) -> Option<usize> {
        if let Some((i, dif)) = self.best_match(clr) {
            if dif.within_threshold((self.threshold_fn)(self.table.len())) {
                return Some(i);
            }
        }
        let i = self.table.len();
        if i < self.table.capacity() {
            self.table.push(clr);
            Some(i)
        } else {
            None
        }
    }
    /// Find the best match for a color.
    ///
    /// The first of equal matches will be returned.
    fn best_match(&self, clr: F) -> Option<(usize, F)> {
        let mut best = None;
        for (i, c) in self.table.iter().enumerate() {
            let dif = clr.difference(*c);
            if {
                if let Some((_, d)) = best {
                    dif.within_threshold(d) && dif != d // better
                } else { true }
            } {
                best = Some((i, dif));
            }
        }
        best
    }
    /// Replace a `Palette` entry.
    ///
    /// * `i` Index of entry.
    /// * `clr` Color to replace entry with.
    ///
    /// # Returns
    /// Previous entry, or `None` if index is larger than table size.
    pub fn replace_entry(&mut self, i: usize, clr: F) -> Option<F> {
        if i < self.table.len() {
            let old = self.table[i];
            self.table[i] = clr;
            Some(old)
        } else {
            None
        }
    }
    /// Create a histogram of `Palette` entries.
    ///
    /// * `ent` Slice of entry indices (pixel values).
    pub fn histogram<T>(&self, ent: &[T]) -> Option<Vec<usize>>
        where T: Copy, usize: From<T>
    {
        let mut hist = vec![0; self.table.len()];
        for e in ent {
            let i = usize::from(*e);
            if i < hist.len() {
                hist[i] += 1;
            } else {
                return None;
            }
        }
        Some(hist)
    }
}

#[cfg(test)]
mod test {
    use super::super::*;
    #[test]
    fn fill_16() {
        let mut p = Palette::new(16);
        assert_eq!(p.entry(4), None);
        // test insertion
        for i in 0..16 {
            let idx = p.set_entry(Rgb8::new(i, i, i)).unwrap();
            assert_eq!(i as usize, idx);
        }
        assert_eq!(p.set_entry(Rgb8::new(255, 255, 255)), None);
        // test lookup
        for i in 0..16 {
            let idx = p.set_entry(Rgb8::new(i, i, i)).unwrap();
            assert_eq!(i as usize, idx);
        }
        assert_eq!(p.entry(5), Some(Rgb8::new(5, 5, 5)));
        p.replace_entry(5, Rgb8::new(0x55, 0x55, 0x55));
        let v = vec![
            0x00,0x00,0x00, 0x01,0x01,0x01, 0x02,0x02,0x02, 0x03,0x03,0x03,
            0x04,0x04,0x04, 0x55,0x55,0x55, 0x06,0x06,0x06, 0x07,0x07,0x07,
            0x08,0x08,0x08, 0x09,0x09,0x09, 0x0A,0x0A,0x0A, 0x0B,0x0B,0x0B,
            0x0C,0x0C,0x0C, 0x0D,0x0D,0x0D, 0x0E,0x0E,0x0E, 0x0F,0x0F,0x0F,
        ];
        assert_eq!(p.as_u8_slice(), &v[..]);
    }
    #[test]
    fn check_hist() {
        let mut p = Palette::new(8);
        for i in 0..7 {
            p.set_entry(Rgb8::new(i, i, i));
        }
        let v: Vec<u8> = vec![
            0x00,0x00,0x00,0x00,0x04,0x00,0x00,0x01,0x02,0x04,0x01,0x02,
            0x02,0x04,0x02,0x06,0x04,0x03,0x03,0x03,0x06,0x03,0x01,0x02,
            0x01,0x02,0x04,0x00,0x04,0x00,0x00,0x00,0x00,0x00,0x01,0x02,
            0x00,0x00,0x00,0x02,0x02,0x04,0x01,0x00,0x00,0x00,0x02,0x04,
        ];
        assert_eq!(p.histogram(&v[..]), Some(vec![18, 6, 10, 4, 8, 0, 2]));
    }
    #[test]
    fn matching() {
        let mut p = Palette::new(8);
        assert_eq!(p.set_entry(Rgb8::new(10, 10, 10)), Some(0));
        assert_eq!(p.set_entry(Rgb8::new(20, 20, 20)), Some(1));
        assert_eq!(p.set_entry(Rgb8::new(30, 30, 30)), Some(2));
        assert_eq!(p.set_entry(Rgb8::new(40, 40, 40)), Some(3));
        p.set_threshold_fn(|_| Rgb8::new(4, 5, 6));
        assert_eq!(p.set_entry(Rgb8::new(15, 15, 15)), Some(4));
        p.set_threshold_fn(|_| Rgb8::new(5, 5, 5));
        assert_eq!(p.set_entry(Rgb8::new(35, 35, 35)), Some(2));
    }
}