Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fix hash.Unmarshal when using proto.Unmarshal #1339

Merged
merged 3 commits into from
Sep 16, 2019
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
32 changes: 32 additions & 0 deletions database/process_db_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -63,3 +63,35 @@ func TestProcessDB(t *testing.T) {
require.NoError(t, db.Delete(p.Hash))
})
}

func TestHashIsDifferent(t *testing.T) {
dir, _ := ioutil.TempDir("", "process.db.test")
defer os.Remove(dir)

db, err := NewProcessDB(dir)
require.NoError(t, err)
defer db.Close()

p1 := &process.Process{
Hash: hash.Int(1),
Key: "1",
}

p2 := &process.Process{
Hash: hash.Int(2),
Key: "2",
}

db.Save(p1)
db.Save(p2)

list, err := db.All()
require.NoError(t, err)
require.Len(t, list, 2)

require.Equal(t, list[0].Key, p1.Key)
require.Equal(t, list[0].Hash, p1.Hash)

require.Equal(t, list[1].Key, p2.Key)
require.Equal(t, list[1].Hash, p2.Hash)
}
3 changes: 2 additions & 1 deletion hash/hash.go
Original file line number Diff line number Diff line change
Expand Up @@ -115,7 +115,8 @@ func (h Hash) MarshalTo(data []byte) (int, error) {

// Unmarshal unmarshals slice of bytes into hash. It's used by protobuf.
func (h *Hash) Unmarshal(data []byte) error {
*h = data
*h = make([]byte, len(data))
copy(*h, data)
return nil
}

Expand Down
9 changes: 9 additions & 0 deletions hash/hash_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -92,3 +92,12 @@ func TestUnmarshalJSON(t *testing.T) {
assert.NoError(t, json.Unmarshal([]byte("\"4uQeVj5tqViQh7yWWGStvkEG1Zmhx6uasJtWCJziofM\""), &h))
assert.Equal(t, Int(1), h)
}

func TestUnmarshal(t *testing.T) {
var hash Hash
data := []byte(Int(1))
hash.Unmarshal(data)
// check if unmarshal copy the data
// test if two slises do not share the same address
assert.True(t, &hash[cap(hash)-1] != &data[cap(data)-1])
}