From 32a80aa9af7d0d6475ceeac27d85954da5818aed Mon Sep 17 00:00:00 2001 From: Quentin McGaw Date: Thu, 8 Dec 2022 14:59:39 +0100 Subject: [PATCH] feat(scale): add `MustMarshal` function (#2991) --- pkg/scale/encode.go | 9 +++++++++ pkg/scale/encode_test.go | 20 ++++++++++++++++++++ 2 files changed, 29 insertions(+) diff --git a/pkg/scale/encode.go b/pkg/scale/encode.go index 18f4f387d1..d312b85f91 100644 --- a/pkg/scale/encode.go +++ b/pkg/scale/encode.go @@ -47,6 +47,15 @@ func Marshal(v interface{}) (b []byte, err error) { return } +// MustMarshal runs Marshal and panics on error. +func MustMarshal(v interface{}) (b []byte) { + b, err := Marshal(v) + if err != nil { + panic(err) + } + return b +} + type encodeState struct { io.Writer *fieldScaleIndicesCache diff --git a/pkg/scale/encode_test.go b/pkg/scale/encode_test.go index 519beae934..d8c76f048b 100644 --- a/pkg/scale/encode_test.go +++ b/pkg/scale/encode_test.go @@ -72,6 +72,26 @@ func Test_Encoder_Encode(t *testing.T) { assert.Equal(t, expectedWritten, written) } +func Test_MustMarshal(t *testing.T) { + t.Parallel() + + t.Run("success", func(t *testing.T) { + t.Parallel() + + b := MustMarshal([]byte{1}) + assert.Equal(t, []byte{4, 1}, b) + }) + + t.Run("panics on error", func(t *testing.T) { + t.Parallel() + + const expected = "unsupported type: chan struct {}" + assert.PanicsWithError(t, expected, func() { + MustMarshal(make(chan struct{})) + }) + }) +} + type test struct { name string in interface{}