Quoted string

This commit is contained in:
Tnze
2021-05-26 02:15:45 +08:00
parent 00fcdb4b14
commit 3b2f81ea1f
2 changed files with 34 additions and 10 deletions

View File

@ -1,5 +1,9 @@
package nbt package nbt
import (
"strings"
)
type decodeState struct { type decodeState struct {
data []byte data []byte
off int // next read offset in data off int // next read offset in data
@ -33,16 +37,12 @@ func writeLiteral(e *Encoder, d *decodeState, tagName string) error {
start := d.readIndex() start := d.readIndex()
d.scanWhile(scanContinue) d.scanWhile(scanContinue)
literal := d.data[start:d.readIndex()] literal := d.data[start:d.readIndex()]
switch v := parseLiteral(literal); v.(type) {
switch literal[0] { case string:
case '"', '\'': // TAG_String str := v.(string)
str := literal // TODO: Parse string e.writeTag(TagString, tagName)
e.writeTag(TagString, "")
e.writeInt16(int16(len(str))) e.writeInt16(int16(len(str)))
e.w.Write(str) e.w.Write([]byte(str))
default:
e.w.Write(literal) // TODO: Parse other literal
} }
return nil return nil
} }
@ -119,3 +119,27 @@ func (d *decodeState) scanWhile(op int) {
d.off = len(data) + 1 // mark processed EOF with len+1 d.off = len(data) + 1 // mark processed EOF with len+1
d.opcode = d.scan.eof() d.opcode = d.scan.eof()
} }
// parseLiteral parse an SNBT literal, might be
// TAG_String, TAG_Int, TAG_Float, ... etc.
// so returned value is one of string, int32, float32 ...
func parseLiteral(literal []byte) interface{} {
switch literal[0] {
case '"', '\'': // Quoted String
var sb strings.Builder
for i := 1; ; i++ {
c := literal[i]
switch c {
case literal[0]:
return sb.String()
case '\\':
i++
c = literal[i]
}
sb.WriteByte(c)
}
default:
}
panic(phasePanicMsg)
}

View File

@ -8,7 +8,7 @@ import (
func TestEncoder_WriteSNBT(t *testing.T) { func TestEncoder_WriteSNBT(t *testing.T) {
var buf bytes.Buffer var buf bytes.Buffer
e := NewEncoder(&buf) e := NewEncoder(&buf)
if err := e.WriteSNBT(`{ abc: a123}`); err != nil { if err := e.WriteSNBT(`{ "abc": "a123"}`); err != nil {
t.Fatal(err) t.Fatal(err)
} }
t.Log(buf.Bytes()) t.Log(buf.Bytes())