codex_string.go 1.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162
  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. }
  42. func (c *CodexString) Encode(data []byte, pos int, value interface{}) (int, error) {
  43. if vm, ok := value.(map[string]interface{}); ok {
  44. if v, ok := vm[c.id].(string); ok {
  45. lv := len(v)
  46. if lv > c.length {
  47. copy(data[pos:pos+lv], []byte(v[0:c.length]))
  48. return pos + c.length, nil
  49. }
  50. copy(data[pos:pos+lv], []byte(v))
  51. return pos + c.length, nil
  52. }
  53. panic(fmt.Sprintf("Invalid value type [%s] %+v", c.id, vm))
  54. }
  55. panic(fmt.Sprintf("Invalid value type [%s] %+v", c.id, value))
  56. }