Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fix NewRectFromPoints modifying its inputs #47

Merged
merged 1 commit into from
Oct 14, 2022
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
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