webgl_matrix/
slice_ops.rs

1use std::f32;
2
3#[inline]
4/// Performs element-wise multiplication and places the result into `lhs`
5///
6/// Terminates at the end of the shorter sequence.
7pub fn mul(lhs: &mut [f32], rhs: &[f32]) {
8    for (l, r) in lhs.iter_mut().zip(rhs.iter()) {
9        *l *= r;
10    }
11}
12
13#[inline]
14/// Performs element-wise addition and places the result into `lhs`
15///
16/// Terminates at the end of the shorter sequence.
17pub fn add(lhs: &mut [f32], rhs: &[f32]) {
18    for (l, r) in lhs.iter_mut().zip(rhs.iter()) {
19        *l += r;
20    }
21}
22
23#[inline]
24/// Performs element-wise substraction and places the result into `lhs`
25///
26/// Terminates at the end of the shorter sequence.
27pub fn sub(lhs: &mut [f32], rhs: &[f32]) {
28    for (l, r) in lhs.iter_mut().zip(rhs.iter()) {
29        *l -= r;
30    }
31}
32
33#[inline]
34/// Multiplies the given sequence element-wise with the given constant factor
35pub fn scale(seq: &mut [f32], factor: f32) {
36    for i in seq.iter_mut() {
37        *i *= factor;
38    }
39}
40
41#[inline]
42/// Calculates the magnitude of the given sequence, same as sqrt(`mag2(seq)`)
43pub fn mag(seq: &[f32]) -> f32 {
44    mag2(seq).sqrt()
45}
46
47#[inline]
48/// Calculates the squared magnitude of the given sequence, i.e. `seq[0] * seq[0] + seq[1] * seq[1] + ...`
49pub fn mag2(seq: &[f32]) -> f32 {
50    let mut sum = 0.0;
51    for i in seq.iter() {
52        sum += i * i;
53    }
54    sum
55}
56
57#[inline]
58/// Calculates the standard dot product of the two sequences.
59///
60/// Terminates at the end of the shorter sequence.
61pub fn dot(lhs: &[f32], rhs: &[f32]) -> f32 {
62    let mut sum = 0.0;
63    for (i1, i2) in lhs.iter().zip(rhs.iter()) {
64        sum += i1 * i2;
65    }
66    sum
67}