codex_string.go 1.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546
  1. package codex
  2. import (
  3. "fmt"
  4. )
  5. type CodexString struct {
  6. id string
  7. length int
  8. }
  9. func (c *CodexString) init(cfg map[string]interface{}) {
  10. if v, ok := cfg["id"].(string); ok {
  11. c.id = v
  12. } else {
  13. panic(fmt.Sprintf("Invalid CodexString.ID %+v", cfg))
  14. }
  15. if v, ok := cfg["length"].(int); ok {
  16. c.length = v
  17. } else {
  18. panic(fmt.Sprintf("Invalid CodexString.Length %+v", cfg))
  19. }
  20. }
  21. func (c *CodexString) ID() string {
  22. return c.id
  23. }
  24. func (c *CodexString) decode(data []byte, pos int) (string, int, error) {
  25. ppos := pos + c.length
  26. if len(data) >= ppos {
  27. return string(data[pos:ppos]), ppos, nil
  28. }
  29. return "", pos, fmt.Errorf("incomplete packet field %s %d < %d", c.id, len(data), ppos)
  30. }
  31. func (c *CodexString) Decode(data []byte, pos int, value interface{}) (int, error) {
  32. var err error
  33. if vm, ok := value.(map[string]interface{}); ok {
  34. vm[c.id], pos, err = c.decode(data, pos)
  35. if err != nil {
  36. return pos, err
  37. }
  38. return pos, nil
  39. }
  40. panic(fmt.Sprintf("Invalid value type %+v", value))
  41. }