From ac3d23441b195be0508184a532fbfb355e3e2111 Mon Sep 17 00:00:00 2001 From: Kevin Atkinson Date: Fri, 31 Aug 2018 15:06:09 -0400 Subject: [PATCH] Don't return an error on NewEncoder, panic on invalid encodings instead. Most of the time this method will be used with a constant and the error will be thrown away anyway. By not returning an error we can use this function to initialize global variables. The function EncoderByName should be used when working with user provided input and we care about the error. --- encoder.go | 10 ++++++---- encoder_test.go | 34 +++++++++++++++------------------- 2 files changed, 21 insertions(+), 23 deletions(-) diff --git a/encoder.go b/encoder.go index d1f87f0..9323b57 100644 --- a/encoder.go +++ b/encoder.go @@ -10,13 +10,15 @@ type Encoder struct { enc Encoding } -// NewEncoder create a new Encoder from an Encoding -func NewEncoder(base Encoding) (Encoder, error) { +// 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. +func NewEncoder(base Encoding) Encoder { _, ok := EncodingToStr[base] if !ok { - return Encoder{-1}, fmt.Errorf("Unsupported multibase encoding: %d", base) + panic(fmt.Errorf("Unsupported multibase encoding: %d", base)) } - return Encoder{base}, nil + return Encoder{base} } // EncoderByName creates an encoder from a string, the string can diff --git a/encoder_test.go b/encoder_test.go index d09c805..6274e44 100644 --- a/encoder_test.go +++ b/encoder_test.go @@ -4,13 +4,6 @@ import ( "testing" ) -func TestInvalidPrefix(t *testing.T) { - _, err := NewEncoder('q') - if err == nil { - t.Error("expected failure") - } -} - func TestInvalidName(t *testing.T) { values := []string{"invalid", "", "q"} for _, val := range values { @@ -21,23 +14,26 @@ func TestInvalidName(t *testing.T) { } } -func TestPrefix(t *testing.T) { - for str, base := range Encodings { - prefix, err := NewEncoder(base) - if err != nil { - t.Fatalf("NewEncoder(%c) failed: %v", base, err) - } - str1, err := Encode(base, sampleBytes) +func TestEncoder(t *testing.T) { + for name, code := range Encodings { + encoder := NewEncoder(code) + str, err := Encode(code, sampleBytes) if err != nil { t.Fatal(err) } - str2 := prefix.Encode(sampleBytes) - if str1 != str2 { - t.Errorf("encoded string mismatch: %s != %s", str1, str2) + str2 := encoder.Encode(sampleBytes) + if str != str2 { + t.Errorf("encoded string mismatch: %s != %s", str, str2) } - _, err = EncoderByName(str) + _, err = EncoderByName(name) if err != nil { - t.Fatalf("NewEncoder(%s) failed: %v", str, err) + t.Errorf("EncoderByName(%s) failed: %v", name, err) + } + // Test that an encoder can be created from the single letter + // prefix + _, err = EncoderByName(str[0:1]) + if err != nil { + t.Errorf("EncoderByName(%s) failed: %v", str[0:1], err) } } }