Skip to content

Commit

Permalink
fix: Fix to return nil when dict info cannot be read
Browse files Browse the repository at this point in the history
  • Loading branch information
ikawaha committed Jun 9, 2024
1 parent 6384255 commit baf0260
Show file tree
Hide file tree
Showing 2 changed files with 11 additions and 21 deletions.
11 changes: 5 additions & 6 deletions dict/dict_info.go
Original file line number Diff line number Diff line change
Expand Up @@ -13,8 +13,6 @@ type Info struct {
Src string
}

const UndefinedDictName = "unnamed dict"

// ReadDictInfo reads gob encoded dictionary info and returns it.
//
// For backward compatibility, if a dictionary name is not defined or empty, it
Expand All @@ -25,12 +23,13 @@ func ReadDictInfo(r io.Reader) *Info {
}
var name string
dec := gob.NewDecoder(r)
_ = dec.Decode(&name)
if name == "" {
name = UndefinedDictName
if err := dec.Decode(&name); err != nil {
return nil
}
var src string
_ = dec.Decode(&src)
if err := dec.Decode(&src); err != nil {
return nil
}
return &Info{Name: name, Src: src}
}

Expand Down
21 changes: 6 additions & 15 deletions dict/dict_info_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -35,33 +35,24 @@ func TestDictName_bad_input(t *testing.T) {

// Decode gob encoded dictionary name.
got := ReadDictInfo(&gobName)

// Assert be equal to default name.
want := UndefinedDictName
if want != got.Name {
t.Errorf("empty name should return default name. want %v, got %v", want, got.Name)
if got.Name != "" {
t.Errorf("empty name should return empty name. got %v", got)
}
})

t.Run("nil input", func(t *testing.T) {
// Nil input shuold return default name.
got := ReadDictInfo(nil)

// Assert be equal to default name.
want := UndefinedDictName
if want != got.Name {
t.Errorf("nil input should return default name. want %v, got %v", want, got)
if got != nil {
t.Errorf("nil input should return nil. got %v", got)
}
})

t.Run("bad gob data", func(t *testing.T) {
// Bad gob data should return default name.
got := ReadDictInfo(bytes.NewReader([]byte{0x00}))

// Assert be equal to default name.
want := UndefinedDictName
if want != got.Name {
t.Errorf("bad encoded data should return default name. want %v, got %v", want, got)
if got != nil {
t.Errorf("bad gob data should return nil. got %v", got)
}
})
}
Expand Down

0 comments on commit baf0260

Please sign in to comment.