Use MustNewEncoder instead for version that does not panic.

This commit is contained in:
Kevin Atkinson
2018-08-31 20:08:55 -04:00
parent 2170058ef9
commit 3b3047873d
2 changed files with 25 additions and 21 deletions

View File

@@ -10,24 +10,23 @@ type Encoder struct {
enc Encoding
}
// 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 {
err := CheckEncoding(base)
if err != nil {
panic(err)
}
return Encoder{base}
}
// CheckEncoding checks that an encoding is valid
func CheckEncoding(base Encoding) error {
// NewEncoder create a new Encoder from an Encoding
func NewEncoder(base Encoding) (Encoder, error) {
_, ok := EncodingToStr[base]
if !ok {
return fmt.Errorf("Unsupported multibase encoding: %d", base)
return Encoder{-1}, fmt.Errorf("Unsupported multibase encoding: %d", base)
}
return nil
return Encoder{base}, nil
}
// MustNewEncoder is like NewEncoder but will panic if the encoding is
// invalid.
func MustNewEncoder(base Encoding) Encoder {
_, ok := EncodingToStr[base]
if !ok {
panic("Unsupported multibase encoding")
}
return Encoder{base}
}
// EncoderByName creates an encoder from a string, the string can

View File

@@ -4,10 +4,10 @@ import (
"testing"
)
func TestInvalidEncoding(t *testing.T) {
err := CheckEncoding(Encoding('q'))
func TestInvalidCode(t *testing.T) {
_, err := NewEncoder('q')
if err == nil {
t.Errorf("CheckEncoding('q') expected failure")
t.Error("expected failure")
}
}
@@ -23,7 +23,12 @@ func TestInvalidName(t *testing.T) {
func TestEncoder(t *testing.T) {
for name, code := range Encodings {
encoder := NewEncoder(code)
encoder, err := NewEncoder(code)
if err != nil {
t.Fatal(err)
}
// Make sure the MustNewEncoder doesn't panic
MustNewEncoder(code)
str, err := Encode(code, sampleBytes)
if err != nil {
t.Fatal(err)
@@ -34,13 +39,13 @@ func TestEncoder(t *testing.T) {
}
_, err = EncoderByName(name)
if err != nil {
t.Errorf("EncoderByName(%s) failed: %v", name, err)
t.Fatalf("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)
t.Fatalf("EncoderByName(%s) failed: %v", str[0:1], err)
}
}
}