From d99bc645ee0138c6ea628f77c6475eec1a61253e Mon Sep 17 00:00:00 2001 From: Mission Liao Date: Tue, 31 Jul 2018 10:30:30 +0800 Subject: Add new sorting method for blocks - Add types.ByHeight to sort slice of blocks by their heights. - Add test case for sorting methods of types.Block. --- core/types/block.go | 15 +++++++++++++++ core/types/block_test.go | 50 ++++++++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 65 insertions(+) create mode 100644 core/types/block_test.go (limited to 'core') diff --git a/core/types/block.go b/core/types/block.go index 217ea73..61b6535 100644 --- a/core/types/block.go +++ b/core/types/block.go @@ -87,3 +87,18 @@ func (b ByHash) Less(i int, j int) bool { func (b ByHash) Swap(i int, j int) { b[i], b[j] = b[j], b[i] } + +// ByHeight is the helper type for sorting slice of blocks by height. +type ByHeight []*Block + +func (b ByHeight) Len() int { + return len(b) +} + +func (b ByHeight) Less(i int, j int) bool { + return b[i].Height < b[j].Height +} + +func (b ByHeight) Swap(i int, j int) { + b[i], b[j] = b[j], b[i] +} diff --git a/core/types/block_test.go b/core/types/block_test.go new file mode 100644 index 0000000..feca5b8 --- /dev/null +++ b/core/types/block_test.go @@ -0,0 +1,50 @@ +package types + +import ( + "sort" + "testing" + + "github.com/dexon-foundation/dexon-consensus-core/common" + "github.com/stretchr/testify/suite" +) + +type BlockTestSuite struct { + suite.Suite +} + +func (s *BlockTestSuite) TestSortByHash() { + hash := common.Hash{} + copy(hash[:], "aaaaaa") + b0 := &Block{Hash: hash} + copy(hash[:], "bbbbbb") + b1 := &Block{Hash: hash} + copy(hash[:], "cccccc") + b2 := &Block{Hash: hash} + copy(hash[:], "dddddd") + b3 := &Block{Hash: hash} + + blocks := []*Block{b3, b2, b1, b0} + sort.Sort(ByHash(blocks)) + s.Equal(blocks[0].Hash, b0.Hash) + s.Equal(blocks[1].Hash, b1.Hash) + s.Equal(blocks[2].Hash, b2.Hash) + s.Equal(blocks[3].Hash, b3.Hash) +} + +func (s *BlockTestSuite) TestSortByHeight() { + b0 := &Block{Height: 0} + b1 := &Block{Height: 1} + b2 := &Block{Height: 2} + b3 := &Block{Height: 3} + + blocks := []*Block{b3, b2, b1, b0} + sort.Sort(ByHeight(blocks)) + s.Equal(blocks[0].Hash, b0.Hash) + s.Equal(blocks[1].Hash, b1.Hash) + s.Equal(blocks[2].Hash, b2.Hash) + s.Equal(blocks[3].Hash, b3.Hash) +} + +func TestBlock(t *testing.T) { + suite.Run(t, new(BlockTestSuite)) +} -- cgit v1.2.3