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
#[inline]
pub fn copy_u8_to_i32(src: &[u8], dest: &mut [i32]) {
let dest = &mut dest[0..src.len()]; for (value, dest) in src.iter().copied().zip(dest.iter_mut()) {
*dest = i32::from(value);
}
}
pub fn square(src: &[i32], dest: &mut [u32]) {
for (value, dest) in src.iter().copied().zip(dest.iter_mut()) {
*dest = i32::pow(value, 2) as u32;
}
}
pub unsafe fn abs(src: *const i32, dest: *mut i32, length: usize) {
for i in 0..length as isize {
let value = *src.offset(i);
*dest.offset(i) = if value >= 0 { value } else { -value };
}
}
pub unsafe fn vector_add(left: *const i32, right: *const i32, dest: *mut i32, length: usize) {
for i in 0..length as isize {
*dest.offset(i) = *left.offset(i) + *right.offset(i);
}
}
pub unsafe fn vector_sub(left: *const i32, right: *const i32, dest: *mut i32, length: usize) {
for i in 0..length as isize {
*dest.offset(i) = *left.offset(i) - *right.offset(i);
}
}
pub fn vector_inner_product(left: &[f32], right: &[f32]) -> f32 {
left.iter()
.copied()
.zip(right.iter().copied())
.map(|(l, r)| l * r)
.sum()
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_square() {
let mut vec = vec![1, 2, 3];
square(&[1, 2, 3], &mut vec);
assert_eq!(vec![1, 4, 9], vec);
}
#[test]
fn test_abs() {
let mut vec = vec![-1, 2, -3];
unsafe { abs(vec.as_ptr(), vec.as_mut_ptr(), vec.len()) };
assert_eq!(vec![1, 2, 3], vec);
}
#[test]
fn test_vector_add() {
let mut vec = vec![1, 2, 3];
unsafe { vector_add(vec.as_ptr(), vec.as_ptr(), vec.as_mut_ptr(), vec.len()) };
assert_eq!(vec![2, 4, 6], vec);
}
#[test]
fn test_vector_sub() {
let mut vec = vec![1, 2, 3];
unsafe { vector_sub(vec.as_ptr(), vec.as_ptr(), vec.as_mut_ptr(), vec.len()) };
assert_eq!(vec![0, 0, 0], vec);
}
#[test]
fn test_vector_inner_product() {
let vec = vec![1.0, 2.0, 3.0];
let result = vector_inner_product(&vec, &vec);
assert_eq!(14.0, result);
}
}