Unverified Commit 534767cc authored by Whyrusleeping's avatar Whyrusleeping Committed by GitHub

Merge pull request #39 from Stebalien/feat/validate

Add a validate function.
parents 958ddffe 829e0e1a
package typegen
import (
"bytes"
"fmt"
"io"
)
// ValidateCBOR validates that a byte array is a single valid CBOR object.
func ValidateCBOR(b []byte) error {
// The code here is basically identical to the previous function, it
// just doesn't copy.
br := bytes.NewReader(b)
// Allocate some scratch space.
scratch := make([]byte, maxHeaderSize)
for remaining := uint64(1); remaining > 0; remaining-- {
maj, extra, err := CborReadHeaderBuf(br, scratch)
if err != nil {
return err
}
switch maj {
case MajUnsignedInt, MajNegativeInt, MajOther:
// nothing fancy to do
case MajByteString, MajTextString:
if extra > ByteArrayMaxLen {
return maxLengthError
}
if uint64(br.Len()) < extra {
return io.ErrUnexpectedEOF
}
if _, err := br.Seek(int64(extra), io.SeekCurrent); err != nil {
return err
}
case MajTag:
remaining++
case MajArray:
if extra > MaxLength {
return maxLengthError
}
remaining += extra
case MajMap:
if extra > MaxLength {
return maxLengthError
}
remaining += extra * 2
default:
return fmt.Errorf("unhandled deferred cbor type: %d", maj)
}
}
if br.Len() > 0 {
return fmt.Errorf("unexpected %d unread bytes", br.Len())
}
return nil
}
package typegen
import (
"bytes"
"testing"
)
func TestValidateShort(t *testing.T) {
var buf bytes.Buffer
if err := WriteMajorTypeHeader(&buf, MajByteString, 100); err != nil {
t.Fatal("failed to write header")
}
if err := ValidateCBOR(buf.Bytes()); err == nil {
t.Fatal("expected an error checking truncated cbor")
}
}
func TestValidateDouble(t *testing.T) {
var buf bytes.Buffer
if err := WriteBool(&buf, false); err != nil {
t.Fatal(err)
}
if err := WriteBool(&buf, false); err != nil {
t.Fatal(err)
}
if err := ValidateCBOR(buf.Bytes()); err == nil {
t.Fatal("expected an error checking cbor with two objects")
}
}
func TestValidate(t *testing.T) {
var buf bytes.Buffer
if err := WriteBool(&buf, false); err != nil {
t.Fatal(err)
}
if err := ValidateCBOR(buf.Bytes()); err != nil {
t.Fatal(err)
}
}
Markdown is supported
0% or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment