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.
This commit is contained in:
Kevin Atkinson
2018-08-31 15:06:09 -04:00
parent ecd5d58562
commit ac3d23441b
2 changed files with 21 additions and 23 deletions

View File

@@ -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

View File

@@ -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)
}
}
}