Skip to main content

angle_sc/
vector2d.rs

1// Copyright (c) 2026 Ken Barker
2
3// Permission is hereby granted, free of charge, to any person obtaining a copy
4// of this software and associated documentation files (the "Software"),
5// to deal in the Software without restriction, including without limitation the
6// rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
7// sell copies of the Software, and to permit persons to whom the Software is
8// furnished to do so, subject to the following conditions:
9
10// The above copyright notice and this permission notice shall be included in
11// all copies or substantial portions of the Software.
12
13// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
14// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
15// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
16// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
17// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
18// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
19// THE SOFTWARE.
20
21//! The `vector2d` module contains 2D vector functions.
22
23use num_traits::Float;
24
25/// 2D vector dot product function: a . b.
26///
27/// * `a_0`, `a_1` the first vector values.
28/// * `b_0`, `b_1` the second vector values.
29///
30/// * returns the dot product of the 2D vectors.
31#[must_use]
32pub fn dot_product<T: Float>(a_0: T, a_1: T, b_0: T, b_1: T) -> T {
33    a_0 * b_0 + a_1 * b_1
34}
35
36/// 2D vector perp product function: a x b.
37///
38/// * `a_0`, `a_1` the first vector values.
39/// * `b_0`, `b_1` the second vector values.
40///
41/// * returns the perp product of the 2D vectors.
42#[must_use]
43pub fn perp_product<T: Float>(a_0: T, a_1: T, b_0: T, b_1: T) -> T {
44    dot_product(a_0, a_1, b_1, -b_0)
45}
46
47#[cfg(test)]
48mod tests {
49    use super::*;
50
51    #[test]
52    fn test_dot_product() {
53        assert_eq!(1.0, dot_product(1.0, 0.0, 1.0, 0.0));
54        assert_eq!(0.0, dot_product(1.0, 0.0, 0.0, 1.0));
55        assert_eq!(0.0, dot_product(0.0, 1.0, 1.0, 0.0));
56    }
57
58    #[test]
59    fn test_perp_product() {
60        assert_eq!(0.0, perp_product(1.0, 0.0, 1.0, 0.0));
61        assert_eq!(1.0, perp_product(1.0, 0.0, 0.0, 1.0));
62        assert_eq!(-1.0, perp_product(0.0, 1.0, 1.0, 0.0));
63    }
64}