|
@@ -2,12 +2,15 @@ package codex
|
|
|
|
|
|
import (
|
|
|
"fmt"
|
|
|
+ "math"
|
|
|
"strconv"
|
|
|
)
|
|
|
|
|
|
type CodexLVar struct {
|
|
|
- id string
|
|
|
- PacketLength int
|
|
|
+ id string
|
|
|
+ PacketLength int
|
|
|
+ maxLength int
|
|
|
+ lfmt string
|
|
|
length int
|
|
|
}
|
|
|
|
|
@@ -24,6 +27,8 @@ func (c *CodexLVar) init(cfg map[string]interface{}) {
|
|
|
} else {
|
|
|
panic(fmt.Sprintf("Invalid CodexLVar.Length %+v", cfg))
|
|
|
}
|
|
|
+ c.maxLength = int(math.Pow(10, float64(c.PacketLength))) - 1
|
|
|
+ c.lfmt = fmt.Sprintf("%%0%dd", c.PacketLength)
|
|
|
}
|
|
|
|
|
|
func (c *CodexLVar) ID() string {
|
|
@@ -58,3 +63,24 @@ func (c *CodexLVar) Decode(data []byte, pos int, value interface{}) (int, error)
|
|
|
}
|
|
|
panic(fmt.Sprintf("Invalid value type %+v", value))
|
|
|
}
|
|
|
+
|
|
|
+func (c *CodexLVar) 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 {
|
|
|
+ ppos := pos + c.PacketLength
|
|
|
+ lv := len(v)
|
|
|
+ if lv > c.maxLength {
|
|
|
+ sl := fmt.Sprintf(c.lfmt, c.maxLength)
|
|
|
+ copy(data[pos:ppos], []byte(sl))
|
|
|
+ copy(data[ppos:ppos+c.maxLength], []byte(v[0:c.maxLength]))
|
|
|
+ return ppos + c.maxLength, nil
|
|
|
+ }
|
|
|
+ sl := fmt.Sprintf(c.lfmt, lv)
|
|
|
+ copy(data[pos:ppos], []byte(sl))
|
|
|
+ copy(data[ppos:ppos+lv], []byte(v))
|
|
|
+ return ppos + lv, nil
|
|
|
+ }
|
|
|
+ panic(fmt.Sprintf("Invalid value type [%s] %+v", c.id, vm))
|
|
|
+ }
|
|
|
+ panic(fmt.Sprintf("Invalid value type [%s] %+v", c.id, value))
|
|
|
+}
|