vendor/github.com/charmbracelet/x/ansi/params.go

45 lines · 1000 bytes

 1package ansi
 2
 3import (
 4	"bytes"
 5)
 6
 7// Params parses and returns a list of control sequence parameters.
 8//
 9// Parameters are positive integers separated by semicolons. Empty parameters
10// default to zero. Parameters can have sub-parameters separated by colons.
11//
12// Any non-parameter bytes are ignored. This includes bytes that are not in the
13// range of 0x30-0x3B.
14//
15// See ECMA-48 § 5.4.1.
16func Params(p []byte) [][]uint {
17	if len(p) == 0 {
18		return [][]uint{}
19	}
20
21	// Filter out non-parameter bytes i.e. non 0x30-0x3B.
22	p = bytes.TrimFunc(p, func(r rune) bool {
23		return r < 0x30 || r > 0x3B
24	})
25
26	parts := bytes.Split(p, []byte{';'})
27	params := make([][]uint, len(parts))
28	for i, part := range parts {
29		sparts := bytes.Split(part, []byte{':'})
30		params[i] = make([]uint, len(sparts))
31		for j, spart := range sparts {
32			params[i][j] = bytesToUint16(spart)
33		}
34	}
35
36	return params
37}
38
39func bytesToUint16(b []byte) uint {
40	var n uint
41	for _, c := range b {
42		n = n*10 + uint(c-'0')
43	}
44	return n
45}