Skip to content

Commit

Permalink
Fix NewRectFromPoints modifying its inputs
Browse files Browse the repository at this point in the history
Fixes #46
  • Loading branch information
magnushiie committed Oct 14, 2022
1 parent ae422b1 commit 87a7e50
Show file tree
Hide file tree
Showing 2 changed files with 17 additions and 6 deletions.
14 changes: 13 additions & 1 deletion geom.go
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,12 @@ func (err DistError) Error() string {
// Point represents a point in n-dimensional Euclidean space.
type Point []float64

func (p Point) Copy() Point {
result := make(Point, len(p))
copy(result, p)
return result
}

// Dist computes the Euclidean distance between two points p and q.
func (p Point) dist(q Point) float64 {
if len(p) != len(q) {
Expand Down Expand Up @@ -188,9 +194,15 @@ func NewRectFromPoints(minPoint, maxPoint Point) (r Rect, err error) {
return
}

//checking that min and max points is swapping
// check that min and max point coordinates require swapping
copied := false
for i, p := range minPoint {
if minPoint[i] > maxPoint[i] {
if !copied {
minPoint = minPoint.Copy()
maxPoint = maxPoint.Copy()
copied = true
}
minPoint[i] = maxPoint[i]
maxPoint[i] = p
}
Expand Down
9 changes: 4 additions & 5 deletions geom_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -59,14 +59,13 @@ func TestNewRectFromPointsWithSwapPoints(t *testing.T) {

rect, err := NewRectFromPoints(q, p)
if err != nil {
t.Errorf("Error on NewRect(%v, %v): %v", p, q, err)
t.Errorf("Error on NewRect(%v, %v): %v", q, p, err)
}

// we must swap p and q because in function it was swapped
if d := p.dist(rect.q); d > EPS {
t.Errorf("Expected p == rect.p")
if d := p.dist(rect.p); d > EPS {
t.Errorf("Expected p == rect.")
}
if d := q.dist(rect.p); d > EPS {
if d := q.dist(rect.q); d > EPS {
t.Errorf("Expected q == rect.q")
}
}
Expand Down

0 comments on commit 87a7e50

Please sign in to comment.