File: repeat.go

package info (click to toggle)
golang-github-charmbracelet-x 0.0~git20251028.0cf22f8%2Bds-3
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 2,940 kB
  • sloc: sh: 124; makefile: 5
file content (59 lines) | stat: -rw-r--r-- 1,404 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
47
48
49
50
51
52
53
54
55
56
57
58
59
package sixel

import (
	"fmt"
	"io"
	"strings"
)

// ErrInvalidRepeat is returned when a Repeat is invalid.
var ErrInvalidRepeat = fmt.Errorf("invalid repeat")

// WriteRepeat writes a Repeat to a writer. A repeat character is in the range
// of '?' (0x3F) to '~' (0x7E).
func WriteRepeat(w io.Writer, count int, char byte) (int, error) {
	return fmt.Fprintf(w, "%c%d%c", RepeatIntroducer, count, char) //nolint:wrapcheck
}

// Repeat represents a Sixel repeat introducer.
type Repeat struct {
	Count int
	Char  byte
}

// WriteTo writes a Repeat to a writer.
func (r Repeat) WriteTo(w io.Writer) (int64, error) {
	n, err := WriteRepeat(w, r.Count, r.Char)
	return int64(n), err
}

// String returns the Repeat as a string.
func (r Repeat) String() string {
	var b strings.Builder
	r.WriteTo(&b) //nolint:errcheck,gosec
	return b.String()
}

// DecodeRepeat decodes a Repeat from a byte slice. It returns the Repeat and
// the number of bytes read.
func DecodeRepeat(data []byte) (r Repeat, n int) {
	if len(data) == 0 || data[0] != RepeatIntroducer {
		return r, n
	}

	if len(data) < 3 { // The minimum length is 3: the introducer, a digit, and a character.
		return r, n
	}

	for n = 1; n < len(data); n++ {
		if data[n] >= '0' && data[n] <= '9' {
			r.Count = r.Count*10 + int(data[n]-'0')
		} else {
			r.Char = data[n]
			n++ // Include the character in the count.
			break
		}
	}

	return r, n
}