From 2112a604f1002f9150debafca214a0bf26ede92a Mon Sep 17 00:00:00 2001 From: Tnze Date: Mon, 5 Jul 2021 01:28:07 +0800 Subject: [PATCH] nbt.StringifiedNBT as nbt.NBTEncoder --- nbt/snbt.go | 58 +++++++++++++++++++++++++++++++++++++---- nbt/snbt_decode_test.go | 19 ++++++++++++++ 2 files changed, 72 insertions(+), 5 deletions(-) diff --git a/nbt/snbt.go b/nbt/snbt.go index 7f40fe2..5ce6871 100644 --- a/nbt/snbt.go +++ b/nbt/snbt.go @@ -1,10 +1,58 @@ package nbt -type StringifiedNBT struct { - Name string - Content string +import "io" + +type StringifiedNBT string + +func (n StringifiedNBT) TagType() (tagType byte) { + d := decodeState{data: []byte(n)} + d.scan.reset() + d.scanWhile(scanSkipSpace) + switch d.opcode { + case scanBeginLiteral: + start := d.readIndex() + if d.scanWhile(scanContinue); d.opcode == scanError { + return + } + literal := d.data[start:d.readIndex()] + tagType, _ = parseLiteral(literal) + + case scanBeginCompound: + tagType = TagCompound + + case scanBeginList: + d.scanWhile(scanSkipSpace) + if d.opcode == scanBeginLiteral { + start := d.readIndex() + if d.scanWhile(scanContinue); d.opcode == scanError { + return + } + literal := d.data[start:d.readIndex()] + if d.opcode == scanSkipSpace { + d.scanWhile(scanSkipSpace) + } + if d.opcode == scanListType { + switch literal[0] { + case 'B': + tagType = TagByteArray + case 'I': + tagType = TagIntArray + case 'L': + tagType = TagLongArray + } + } + } else { + tagType = TagList + } + } + return } -func (n *StringifiedNBT) Decode(tagType byte, tagName string, r DecoderReader) error { - panic("unimplemented") +func (n StringifiedNBT) Encode(w io.Writer) error { + d := decodeState{data: []byte(n)} + d.scan.reset() + return writeValue(NewEncoder(w), &d, "") } + +//func (n *StringifiedNBT) Decode(tagType byte, r DecoderReader) error { +//} diff --git a/nbt/snbt_decode_test.go b/nbt/snbt_decode_test.go index a683d18..74af6e4 100644 --- a/nbt/snbt_decode_test.go +++ b/nbt/snbt_decode_test.go @@ -109,3 +109,22 @@ func Test_WriteSNBT_nestingList(t *testing.T) { t.Error("Exceeded the maximum depth of support, but no error was reported") } } + +func TestStringifiedNBT_TagType(t *testing.T) { + for _, v := range []struct { + snbt string + Type byte + }{ + {`123B`, TagByte}, + {`123`, TagInt}, + {`[]`, TagList}, + {`[B;]`, TagByteArray}, + {`[I;]`, TagIntArray}, + {`[L;]`, TagLongArray}, + {`{abc:123B}`, TagCompound}, + } { + if T := StringifiedNBT(v.snbt).TagType(); T != v.Type { + t.Errorf("Parse SNBT TagType error: %s is %d, not %d", v.snbt, v.Type, T) + } + } +}