package codex import ( "fmt" ) type CodexString struct { id string length int } func (c *CodexString) init(cfg map[string]interface{}) { if v, ok := cfg["id"].(string); ok { c.id = v } else { panic(fmt.Sprintf("Invalid CodexString.ID %+v", cfg)) } if v, ok := cfg["length"].(int); ok { c.length = v } else { panic(fmt.Sprintf("Invalid CodexString.Length %+v", cfg)) } } func (c *CodexString) ID() string { return c.id } func (c *CodexString) decode(data []byte, pos int) (string, int, error) { ppos := pos + c.length if len(data) >= ppos { return string(data[pos:ppos]), ppos, nil } return "", pos, fmt.Errorf("incomplete packet field %s %d < %d", c.id, len(data), ppos) } func (c *CodexString) Decode(data []byte, pos int, value interface{}) (int, error) { var err error if vm, ok := value.(map[string]interface{}); ok { vm[c.id], pos, err = c.decode(data, pos) if err != nil { return pos, err } return pos, nil } panic(fmt.Sprintf("Invalid value type %+v", value)) } func (c *CodexString) Encode(data []byte, pos int, value interface{}) (int, error) { if vm, ok := value.(map[string]interface{}); ok { if v, ok := vm[c.id].(string); ok { lv := len(v) if lv > c.length { copy(data[pos:pos+lv], []byte(v[0:c.length])) return pos + c.length, nil } copy(data[pos:pos+lv], []byte(v)) return pos + c.length, nil } panic(fmt.Sprintf("Invalid value type [%s] %+v", c.id, vm)) } panic(fmt.Sprintf("Invalid value type [%s] %+v", c.id, value)) }