replace vec.truncate(0) with vec.clear()
[nihav.git] / nihav-codec-support / src / data / mod.rs
1 //! Auxiliary data structures for codecs.
2
3 /// Line cache.
4 ///
5 /// In the decoding process of many codecs there is a need to store some previously decoded information and only immediate top neighbours are used.
6 /// This can be done by storing either the full information for the whole frame or just the top line and move information for last decoded row to the top every time when row decoding is done.
7 /// `GenericCache` implements the second approach.
8 ///
9 /// # Examples
10 ///
11 /// Create a cache for one line and use top pixel for prediction:
12 /// ```
13 /// use nihav_codec_support::data::GenericCache;
14 ///
15 /// # let width = 640;
16 /// # let height = 480;
17 /// # let mut dst: Vec<u8> = vec![0; width];
18 /// let mut linecache: GenericCache<u8> = GenericCache::new(1, width, 0x80);
19 /// for _ in 0..height {
20 /// for x in 0..width {
21 /// # let delta = 32;
22 /// dst[x] = linecache.data[linecache.xpos + x - linecache.stride] + delta;
23 /// }
24 /// linecache.update_row();
25 /// }
26 /// ```
27 pub struct GenericCache<T: Copy> {
28 /// Number of rows that are processed at once.
29 pub height: usize,
30 /// Number of elements in one row.
31 pub stride: usize,
32 /// Start of curent data.
33 pub xpos: usize,
34 /// Data.
35 pub data: Vec<T>,
36 /// Default value to fill the cache with.
37 pub default: T,
38 }
39
40 impl<T:Copy> GenericCache<T> {
41 /// Constructs a new instance of `GenericCache`.
42 pub fn new(height: usize, stride: usize, default: T) -> Self {
43 let mut ret = Self {
44 stride,
45 height,
46 xpos: 0,
47 data: Vec::with_capacity((height + 1) * stride + 1),
48 default,
49 };
50 ret.reset();
51 ret
52 }
53 /// Reports the total amount of elements stored.
54 pub fn full_size(&self) -> usize { self.stride * (self.height + 1) + 1 }
55 /// Resets the cache state.
56 pub fn reset(&mut self) {
57 self.data.clear();
58 let size = self.full_size();
59 self.data.resize(size, self.default);
60 self.xpos = self.stride + 1;
61 }
62 /// Updates cache state for the next line.
63 pub fn update_row(&mut self) {
64 for i in 0..self.stride {
65 self.data[i] = self.data[self.height * self.stride + i];
66 }
67 self.data.truncate(self.stride);
68 let size = self.full_size();
69 self.data.resize(size, self.default);
70 self.xpos = self.stride + 1;
71 }
72 }
73