From 2170058ef98bc1e5186780d59e0a4512ef4b7cce Mon Sep 17 00:00:00 2001 From: Kevin Atkinson Date: Fri, 31 Aug 2018 18:17:03 -0400 Subject: [PATCH] Add CheckEncoding function. --- encoder.go | 21 +++++++++++++++------ encoder_test.go | 7 +++++++ 2 files changed, 22 insertions(+), 6 deletions(-) diff --git a/encoder.go b/encoder.go index 9323b57..f4d35a1 100644 --- a/encoder.go +++ b/encoder.go @@ -10,17 +10,26 @@ type Encoder struct { enc Encoding } -// NewEncoder create a new Encoder from an Encoding. It will panic is -// the encoding is invalid. To check for a valid encoding use the -// EncodingToStr map. +// NewEncoder create a new Encoder from an Encoding. It will panic if +// the encoding is invalid. To check for a valid encoding use +// CheckEncoding. func NewEncoder(base Encoding) Encoder { - _, ok := EncodingToStr[base] - if !ok { - panic(fmt.Errorf("Unsupported multibase encoding: %d", base)) + err := CheckEncoding(base) + if err != nil { + panic(err) } return Encoder{base} } +// CheckEncoding checks that an encoding is valid +func CheckEncoding(base Encoding) error { + _, ok := EncodingToStr[base] + if !ok { + return fmt.Errorf("Unsupported multibase encoding: %d", base) + } + return nil +} + // EncoderByName creates an encoder from a string, the string can // either be the multibase name or single character multibase prefix func EncoderByName(str string) (Encoder, error) { diff --git a/encoder_test.go b/encoder_test.go index 6274e44..39f1009 100644 --- a/encoder_test.go +++ b/encoder_test.go @@ -4,6 +4,13 @@ import ( "testing" ) +func TestInvalidEncoding(t *testing.T) { + err := CheckEncoding(Encoding('q')) + if err == nil { + t.Errorf("CheckEncoding('q') expected failure") + } +} + func TestInvalidName(t *testing.T) { values := []string{"invalid", "", "q"} for _, val := range values {