replace vec.truncate(0) with vec.clear()
[nihav.git] / nihav-codec-support / src / data / mod.rs
CommitLineData
4b3ceb42
KS
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.
e65c0040 8///
4b3ceb42
KS
9/// # Examples
10///
11/// Create a cache for one line and use top pixel for prediction:
12/// ```
b4d5b851 13/// use nihav_codec_support::data::GenericCache;
4b3ceb42
KS
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/// ```
1fdbd53e 27pub struct GenericCache<T: Copy> {
4b3ceb42 28 /// Number of rows that are processed at once.
1fdbd53e 29 pub height: usize,
4b3ceb42 30 /// Number of elements in one row.
1fdbd53e 31 pub stride: usize,
4b3ceb42 32 /// Start of curent data.
1fdbd53e 33 pub xpos: usize,
4b3ceb42 34 /// Data.
1fdbd53e 35 pub data: Vec<T>,
4b3ceb42 36 /// Default value to fill the cache with.
1fdbd53e
KS
37 pub default: T,
38}
39
40impl<T:Copy> GenericCache<T> {
4b3ceb42 41 /// Constructs a new instance of `GenericCache`.
1fdbd53e
KS
42 pub fn new(height: usize, stride: usize, default: T) -> Self {
43 let mut ret = Self {
44 stride,
45 height,
46 xpos: 0,
ed2bdcd9 47 data: Vec::with_capacity((height + 1) * stride + 1),
1fdbd53e
KS
48 default,
49 };
50 ret.reset();
51 ret
52 }
4b3ceb42 53 /// Reports the total amount of elements stored.
ed2bdcd9 54 pub fn full_size(&self) -> usize { self.stride * (self.height + 1) + 1 }
4b3ceb42 55 /// Resets the cache state.
1fdbd53e 56 pub fn reset(&mut self) {
37952415 57 self.data.clear();
1fdbd53e
KS
58 let size = self.full_size();
59 self.data.resize(size, self.default);
60 self.xpos = self.stride + 1;
61 }
4b3ceb42 62 /// Updates cache state for the next line.
1fdbd53e
KS
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