Skip to content

Commit

Permalink
Add From<[C; N]> and Into<[C; N]> for vectors
Browse files Browse the repository at this point in the history
  • Loading branch information
sunsided committed Jul 9, 2024
1 parent 1323548 commit 2ce6de2
Show file tree
Hide file tree
Showing 2 changed files with 119 additions and 0 deletions.
57 changes: 57 additions & 0 deletions src/vector/vector2d.rs
Original file line number Diff line number Diff line change
Expand Up @@ -101,6 +101,36 @@ where
}
}

impl<C> From<Vector2d<C>> for (C, C)
where
C: Component,
{
fn from(vector: Vector2d<C>) -> (C, C) {
(vector.x, vector.y)
}
}

impl<C> From<[C; 2]> for Vector2d<C>
where
C: Component,
{
fn from(vector: [C; 2]) -> Self {
Self {
x: vector[0],
y: vector[1],
}
}
}

impl<C> From<Vector2d<C>> for [C; 2]
where
C: Component,
{
fn from(vector: Vector2d<C>) -> [C; 2] {
vector.to_array()
}
}

impl<C> Index<usize> for Vector2d<C>
where
C: Component,
Expand Down Expand Up @@ -220,3 +250,30 @@ impl From<U16x2> for F32x2 {
}
}
}

#[cfg(test)]
mod tests {
use super::*;

#[test]
fn from_tuple() {
let vec: Vector2d<_> = (1, 2).into();
assert_eq!(vec[0], 1);
assert_eq!(vec[1], 2);

let (x, y) = vec.into();
assert_eq!(x, 1);
assert_eq!(y, 2);
}

#[test]
fn from_array() {
let vec: Vector2d<_> = [1, 2].into();
assert_eq!(vec[0], 1);
assert_eq!(vec[1], 2);

let arr: [_; 2] = vec.into();
assert_eq!(arr[0], 1);
assert_eq!(arr[1], 2);
}
}
62 changes: 62 additions & 0 deletions src/vector/vector3d.rs
Original file line number Diff line number Diff line change
Expand Up @@ -108,6 +108,37 @@ where
}
}

impl<C> From<Vector3d<C>> for (C, C, C)
where
C: Component,
{
fn from(vector: Vector3d<C>) -> (C, C, C) {
(vector.x, vector.y, vector.z)
}
}

impl<C> From<[C; 3]> for Vector3d<C>
where
C: Component,
{
fn from(vector: [C; 3]) -> Self {
Self {
x: vector[0],
y: vector[1],
z: vector[2],
}
}
}

impl<C> From<Vector3d<C>> for [C; 3]
where
C: Component,
{
fn from(vector: Vector3d<C>) -> [C; 3] {
vector.to_array()
}
}

impl<C> Index<usize> for Vector3d<C>
where
C: Component,
Expand Down Expand Up @@ -262,3 +293,34 @@ impl From<Vector3d<F32>> for F32x3 {
}
}
}

#[cfg(test)]
mod tests {
use super::*;

#[test]
fn from_tuple() {
let vec: Vector3d<_> = (1, 2, 3).into();
assert_eq!(vec[0], 1);
assert_eq!(vec[1], 2);
assert_eq!(vec[2], 3);

let (x, y, z) = vec.into();
assert_eq!(x, 1);
assert_eq!(y, 2);
assert_eq!(z, 3);
}

#[test]
fn from_array() {
let vec: Vector3d<_> = [1, 2, 3].into();
assert_eq!(vec[0], 1);
assert_eq!(vec[1], 2);
assert_eq!(vec[2], 3);

let arr: [_; 3] = vec.into();
assert_eq!(arr[0], 1);
assert_eq!(arr[1], 2);
assert_eq!(arr[2], 3);
}
}

0 comments on commit 2ce6de2

Please sign in to comment.