File: rle.go

package info (click to toggle)
golang-github-anacrolix-missinggo 2.1.0-4
  • links: PTS, VCS
  • area: main
  • in suites: bullseye, sid
  • size: 836 kB
  • sloc: makefile: 4
file content (46 lines) | stat: -rw-r--r-- 1,175 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
package missinggo

// A RunLengthEncoder counts successive duplicate elements and emits the
// element and the run length when the element changes or the encoder is
// flushed.
type RunLengthEncoder interface {
	// Add a series of identical elements to the stream.
	Append(element interface{}, count uint64)
	// Emit the current element and its count if non-zero without waiting for
	// the element to change.
	Flush()
}

type runLengthEncoder struct {
	eachRun func(element interface{}, count uint64)
	element interface{}
	count   uint64
}

// Creates a new RunLengthEncoder. eachRun is called when an element and its
// count is emitted, per the RunLengthEncoder interface.
func NewRunLengthEncoder(eachRun func(element interface{}, count uint64)) RunLengthEncoder {
	return &runLengthEncoder{
		eachRun: eachRun,
	}
}

func (me *runLengthEncoder) Append(element interface{}, count uint64) {
	if element == me.element {
		me.count += count
		return
	}
	if me.count != 0 {
		me.eachRun(me.element, me.count)
	}
	me.count = count
	me.element = element
}

func (me *runLengthEncoder) Flush() {
	if me.count == 0 {
		return
	}
	me.eachRun(me.element, me.count)
	me.count = 0
}