76 lines
2.1 KiB
Go
76 lines
2.1 KiB
Go
package tape
|
|
|
|
import "fmt"
|
|
import "bytes"
|
|
import "testing"
|
|
import "reflect"
|
|
import tu "git.tebibyte.media/sashakoshka/hopp/internal/testutil"
|
|
|
|
func encAny(value any) ([]byte, Tag, int, error) {
|
|
tag, err := TagAny(value)
|
|
if err != nil { return nil, 0, 0, err }
|
|
buffer := bytes.Buffer { }
|
|
encoder := NewEncoder(&buffer)
|
|
n, err := EncodeAny(encoder, value, tag)
|
|
if err != nil { return nil, 0, n, err }
|
|
encoder.Flush()
|
|
return buffer.Bytes(), tag, n, nil
|
|
}
|
|
|
|
func decAny(data []byte) (Tag, any, int, error) {
|
|
destination := map[uint16] any { }
|
|
tag, err := TagAny(destination)
|
|
if err != nil { return 0, nil, 0, err }
|
|
n, err := DecodeAnyInto(NewDecoder(bytes.NewBuffer(data)), &destination, tag)
|
|
if err != nil { return 0, nil, n, err }
|
|
return tag, destination, n, nil
|
|
}
|
|
|
|
func testEncodeAny(test *testing.T, value any, correctTag Tag, correctBytes tu.Snake) error {
|
|
bytes, tag, n, err := encAny(value)
|
|
if err != nil { return err }
|
|
test.Log("n: ", n)
|
|
test.Log("tag: ", tag)
|
|
test.Log("got: ", tu.HexBytes(bytes))
|
|
test.Log("correct:", correctBytes)
|
|
if tag != correctTag {
|
|
return fmt.Errorf("tag not equal: %v != %v", tag, correctTag)
|
|
}
|
|
if ok, n := correctBytes.Check(bytes); !ok {
|
|
return fmt.Errorf("bytes not equal at index %d", n)
|
|
}
|
|
if n != len(bytes) {
|
|
return fmt.Errorf("n not equal: %d != %d", n, len(bytes))
|
|
}
|
|
return nil
|
|
}
|
|
|
|
func testEncodeDecodeAny(test *testing.T, value, correctValue any) error {
|
|
if correctValue == nil {
|
|
correctValue = value
|
|
}
|
|
|
|
test.Log("encoding...")
|
|
bytes, tag, n, err := encAny(value)
|
|
if err != nil { return err }
|
|
test.Log("n: ", n)
|
|
test.Log("tag:", tag)
|
|
test.Log("got:", tu.HexBytes(bytes))
|
|
test.Log("decoding...", tag)
|
|
if n != len(bytes) {
|
|
return fmt.Errorf("n not equal: %d != %d", n, len(bytes))
|
|
}
|
|
|
|
_, decoded, n, err := decAny(bytes)
|
|
if err != nil { return err }
|
|
test.Log("got: ", tu.Describe(decoded))
|
|
test.Log("correct:", tu.Describe(correctValue))
|
|
if !reflect.DeepEqual(decoded, correctValue) {
|
|
return fmt.Errorf("values not equal")
|
|
}
|
|
if n != len(bytes) {
|
|
return fmt.Errorf("n not equal: %d != %d", n, len(bytes))
|
|
}
|
|
return nil
|
|
}
|