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
use dtype::DtypeCompatible;
use error::Error;
pub struct Buffer<'a, T>
where
T: 'a + DtypeCompatible,
{
data: &'a mut [T],
}
impl<'a, T> Buffer<'a, T>
where
T: 'a + DtypeCompatible,
{
pub fn new(data: &'a mut [T]) -> Self {
Buffer { data }
}
pub fn update(&mut self, data: &[T]) -> Result<(), Error> {
if self.data.len() != data.len() {
return Err(Error::InvalidBufferSize);
}
self.data.copy_from_slice(data);
Ok(())
}
pub fn as_slice(&self) -> &[T] {
self.data
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn update_buffer_success() {
let mut v: Vec<f32> = vec![0., 1., 2.];
let mut buffer = Buffer::new(&mut v);
let v = vec![10., 11., 12.];
buffer.update(&v).unwrap();
assert_eq!(buffer.as_slice(), v.as_slice());
}
#[test]
fn update_buffer_fail() {
let mut v: Vec<f32> = vec![Default::default(); 3];
let mut buffer = Buffer::new(&mut v);
let v = vec![Default::default(); 4];
assert_matches!(buffer.update(&v).err().unwrap(), Error::InvalidBufferSize);
}
}