Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Factor out common run building code into a reusable type.
Signed-off-by: Jon Seymour <jon@wildducktheories.com>
- Loading branch information
1 parent
b5852f1
commit 6bde168
Showing
2 changed files
with
57 additions
and
65 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,48 @@ | ||
package modbus | ||
|
||
import ( | ||
"github.com/crabmusket/gosunspec/spi" | ||
) | ||
|
||
// runBuilder breaks a sequence of points into a sequence of runs, where each run | ||
// of points is strictly adjacent | ||
type runBuilder struct { | ||
runs [][]spi.PointSPI | ||
run []spi.PointSPI | ||
} | ||
|
||
func newRunBuilder() *runBuilder { | ||
run := []spi.PointSPI{} | ||
return &runBuilder{ | ||
run: run, | ||
runs: [][]spi.PointSPI{run}, | ||
} | ||
} | ||
|
||
func (r *runBuilder) spawn(p spi.PointSPI) { | ||
r.run = []spi.PointSPI{p} | ||
r.runs = append(r.runs, r.run) | ||
|
||
} | ||
|
||
func (r *runBuilder) adjacent(p spi.PointSPI) bool { | ||
if len(r.run) == 0 { | ||
return true | ||
} else { | ||
last := r.run[len(r.run)-1] | ||
return last.Offset()+last.Length() == p.Offset() | ||
} | ||
} | ||
|
||
func (r *runBuilder) extend(p spi.PointSPI) { | ||
r.run = append(r.run, p) | ||
r.runs[len(r.runs)-1] = r.run | ||
} | ||
|
||
func (r *runBuilder) add(p spi.PointSPI) { | ||
if r.adjacent(p) { | ||
r.extend(p) | ||
} else { | ||
r.spawn(p) | ||
} | ||
} |