params.go 1000 B

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