lib/protocol: Avoid panic in DeviceIDFromBytes (#6714)
This commit is contained in:
@@ -46,13 +46,13 @@ func DeviceIDFromString(s string) (DeviceID, error) {
|
||||
return n, err
|
||||
}
|
||||
|
||||
func DeviceIDFromBytes(bs []byte) DeviceID {
|
||||
func DeviceIDFromBytes(bs []byte) (DeviceID, error) {
|
||||
var n DeviceID
|
||||
if len(bs) != len(n) {
|
||||
panic("incorrect length of byte slice representing device ID")
|
||||
return n, fmt.Errorf("incorrect length of byte slice representing device ID")
|
||||
}
|
||||
copy(n[:], bs)
|
||||
return n
|
||||
return n, nil
|
||||
}
|
||||
|
||||
// String returns the canonical string representation of the device ID
|
||||
|
||||
@@ -99,8 +99,10 @@ func TestShortIDString(t *testing.T) {
|
||||
|
||||
func TestDeviceIDFromBytes(t *testing.T) {
|
||||
id0, _ := DeviceIDFromString(formatted)
|
||||
id1 := DeviceIDFromBytes(id0[:])
|
||||
if id1.String() != formatted {
|
||||
id1, err := DeviceIDFromBytes(id0[:])
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
} else if id1.String() != formatted {
|
||||
t.Errorf("Wrong device ID, got %q, want %q", id1, formatted)
|
||||
}
|
||||
}
|
||||
@@ -150,7 +152,10 @@ func TestNewDeviceIDMarshalling(t *testing.T) {
|
||||
|
||||
// Verify it's the same
|
||||
|
||||
if DeviceIDFromBytes(msg2.Test) != id0 {
|
||||
id1, err := DeviceIDFromBytes(msg2.Test)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
} else if id1 != id0 {
|
||||
t.Error("Mismatch in old -> new direction")
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user