Skip to content

Commit

Permalink
Merge pull request #47 from project-echo/rect-swap
Browse files Browse the repository at this point in the history
Fix NewRectFromPoints modifying its inputs
  • Loading branch information
dhconnelly authored Oct 14, 2022
2 parents ae422b1 + 87a7e50 commit 2851901
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 2851901

Please sign in to comment.