cover: fix sorting of profile segment boundaries

This is a backport of CL 116976 from cmd/cover in the go repository.

Updates #25767.

Change-Id: I54b8bbfa975141684661edf46081dbd9a304a641
Reviewed-on: https://go-review.googlesource.com/c/tools/+/249619
Run-TryBot: Rebecca Stambler <rstambler@golang.org>
gopls-CI: kokoro <noreply+kokoro@google.com>
TryBot-Result: Go Bot <gobot@golang.org>
Trust: Jay Conrod <jayconrod@google.com>
Trust: Robert Findley <rfindley@google.com>
Trust: Bryan C. Mills <bcmills@google.com>
Reviewed-by: Bryan C. Mills <bcmills@google.com>
diff --git a/cover/profile.go b/cover/profile.go
index 0bb3541..5719577 100644
--- a/cover/profile.go
+++ b/cover/profile.go
@@ -194,6 +194,7 @@
 	Start  bool    // Is this the start of a block?
 	Count  int     // Event count from the cover profile.
 	Norm   float64 // Count normalized to [0..1].
+	Index  int     // Order in input file.
 }
 
 // Boundaries returns a Profile as a set of Boundary objects within the provided src.
@@ -209,8 +210,10 @@
 	divisor := math.Log(float64(max))
 
 	// boundary returns a Boundary, populating the Norm field with a normalized Count.
+	index := 0
 	boundary := func(offset int, start bool, count int) Boundary {
-		b := Boundary{Offset: offset, Start: start, Count: count}
+		b := Boundary{Offset: offset, Start: start, Count: count, Index: index}
+		index++
 		if !start || count == 0 {
 			return b
 		}
@@ -250,7 +253,9 @@
 func (b boundariesByPos) Swap(i, j int) { b[i], b[j] = b[j], b[i] }
 func (b boundariesByPos) Less(i, j int) bool {
 	if b[i].Offset == b[j].Offset {
-		return !b[i].Start && b[j].Start
+		// Boundaries at the same offset should be ordered according to
+		// their original position.
+		return b[i].Index < b[j].Index
 	}
 	return b[i].Offset < b[j].Offset
 }