Skip to content

Commit

Permalink
Merge pull request #3052 from oasisprotocol/yawning/trivial/versioned…
Browse files Browse the repository at this point in the history
…-cbor

go/common/cbor: Add support for generic versioned blobs
  • Loading branch information
Yawning authored Jun 25, 2020
2 parents c2ecca2 + ba0cfb2 commit 5373604
Show file tree
Hide file tree
Showing 3 changed files with 91 additions and 0 deletions.
1 change: 1 addition & 0 deletions .changelog/3052.internal.md
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
go/common/cbor: Add support for generic versioned blobs
51 changes: 51 additions & 0 deletions go/common/cbor/versioned.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,51 @@
package cbor

import (
"errors"
"math"

"github.com/fxamacker/cbor/v2"
)

const invalidVersion = math.MaxUint16

var (
// ErrInvalidVersion is the error returned when a versioned
// serialized blob is either missing, or has an invalid version.
ErrInvalidVersion = errors.New("cbor: missing or invalid version")

decOptionsVersioned = decOptions

decModeVersioned cbor.DecMode
)

// Versioned is a generic versioned serializable data structure.
type Versioned struct {
V uint16 `json:"v"`
}

// GetVersion returns the version of a versioned serializable data
// structure, if any.
func GetVersion(data []byte) (uint16, error) {
vblob := Versioned{
V: invalidVersion,
}
if err := decModeVersioned.Unmarshal(data, &vblob); err != nil {
return 0, err
}
if vblob.V == invalidVersion {
return 0, ErrInvalidVersion
}
return vblob.V, nil
}

func init() {
// Use the untrusted decode options, but ignore unknown fields.
// FIXME: https://github.com/fxamacker/cbor/issues/240
decOptionsVersioned.ExtraReturnErrors = int(cbor.ExtraDecErrorNone)

var err error
if decModeVersioned, err = decOptionsVersioned.DecMode(); err != nil {
panic(err)
}
}
39 changes: 39 additions & 0 deletions go/common/cbor/versioned_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
package cbor

import (
"testing"

"github.com/stretchr/testify/require"
)

func TestVersioned(t *testing.T) {
require := require.New(t)

type a struct {
A string
}

raw := Marshal(&a{
A: "Open still remaineth the earth for great souls.",
})
_, err := GetVersion(raw)
require.Equal(ErrInvalidVersion, err, "missing version should error")

type b struct {
Versioned
a
}

const testVersion uint16 = 451
raw = Marshal(&b{
Versioned: Versioned{
V: testVersion,
},
a: a{
A: "Empty are still many sites for lone ones and twain ones",
},
})
version, err := GetVersion(raw)
require.NoError(err, "versioned blobs should deserialize")
require.Equal(testVersion, version, "the version should be correct")
}

0 comments on commit 5373604

Please sign in to comment.