Debian Codegraph @

ansi/sixel/repeat.go

raw
1 package sixel
2
3 import (
4 "fmt"
5 "io"
6 "strings"
7 )
8
9 // ErrInvalidRepeat is returned when a Repeat is invalid.
10 var ErrInvalidRepeat = fmt.Errorf("invalid repeat")
11
12 // WriteRepeat writes a Repeat to a writer. A repeat character is in the range
13 // of '?' (0x3F) to '~' (0x7E).
14 func WriteRepeat(w io.Writer, count int, char byte) (int, error) {
15 return fmt.Fprintf(w, "%c%d%c", RepeatIntroducer, count, char) //nolint:wrapcheck
16 }
17
18 // Repeat represents a Sixel repeat introducer.
19 type Repeat struct {
20 Count int
21 Char byte
22 }
23
24 // WriteTo writes a Repeat to a writer.
25 func (r Repeat) WriteTo(w io.Writer) (int64, error) {
26 n, err := WriteRepeat(w, r.Count, r.Char)
27 return int64(n), err
28 }
29
30 // String returns the Repeat as a string.
31 func (r Repeat) String() string {
32 var b strings.Builder
33 r.WriteTo(&b) //nolint:errcheck,gosec
34 return b.String()
35 }
36
37 // DecodeRepeat decodes a Repeat from a byte slice. It returns the Repeat and
38 // the number of bytes read.
39 func DecodeRepeat(data []byte) (r Repeat, n int) {
40 if len(data) == 0 || data[0] != RepeatIntroducer {
41 return r, n
42 }
43
44 if len(data) < 3 { // The minimum length is 3: the introducer, a digit, and a character.
45 return r, n
46 }
47
48 for n = 1; n < len(data); n++ {
49 if data[n] >= '0' && data[n] <= '9' {
50 r.Count = r.Count*10 + int(data[n]-'0')
51 } else {
52 r.Char = data[n]
53 n++ // Include the character in the count.
54 break
55 }
56 }
57
58 return r, n
59 }