Skip to content

Commit

Permalink
Allow creating Points from Tuples and Arrays (#32)
Browse files Browse the repository at this point in the history
There's a lot of 2d vector/point types, and things like this simplify
interop.

Note: This is only fixed sized, 2-length arrays. &[f64] is not covered
and would need to be cast/copied into a [f64; 2] to work.
  • Loading branch information
Chris--B authored Oct 23, 2023
1 parent 614b537 commit fd14611
Show file tree
Hide file tree
Showing 2 changed files with 36 additions and 0 deletions.
24 changes: 24 additions & 0 deletions src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -55,6 +55,30 @@ impl From<&Point> for robust::Coord<f64> {
}
}

impl From<(f64, f64)> for Point {
fn from((x, y): (f64, f64)) -> Self {
Point { x, y }
}
}

impl From<[f64; 2]> for Point {
fn from([x, y]: [f64; 2]) -> Self {
Point { x, y }
}
}

impl From<Point> for (f64, f64) {
fn from(pt: Point) -> Self {
(pt.x, pt.y)
}
}

impl From<Point> for [f64; 2] {
fn from(pt: Point) -> Self {
[pt.x, pt.y]
}
}

impl Point {
fn dist2(&self, p: &Self) -> f64 {
let dx = self.x - p.x;
Expand Down
12 changes: 12 additions & 0 deletions tests/tests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -177,6 +177,18 @@ fn invalid_nan_sequence() {
triangulate(&points);
}

#[test]
/// The test demonstrates and validates our tuple and array round tripping of `Point`
fn tuple_array_conv() {
// Tuple/Array --> Point
assert_eq!(Into::<Point>::into((1., 2.)), Point { x: 1., y: 2. });
assert_eq!(Into::<Point>::into([1., 2.]), Point { x: 1., y: 2. });

// Point --> Tuple/Array
assert_eq!(Into::<(f64, f64)>::into(Point { x: 1., y: 2. }), (1., 2.));
assert_eq!(Into::<[f64; 2]>::into(Point { x: 1., y: 2. }), [1., 2.]);
}

fn scale_points(points: &[Point], scale: f64) -> Vec<Point> {
let scaled: Vec<Point> = points
.iter()
Expand Down

0 comments on commit fd14611

Please sign in to comment.