diff options
author | Mission Liao <mission.liao@dexon.org> | 2018-07-31 10:30:30 +0800 |
---|---|---|
committer | GitHub <noreply@github.com> | 2018-07-31 10:30:30 +0800 |
commit | d99bc645ee0138c6ea628f77c6475eec1a61253e (patch) | |
tree | ddf008608cc6fe8f64a46a531d36a6cf4392eeac /core | |
parent | 9261a3b9f3711ba736f2a143456e0b73bdfcfab8 (diff) | |
download | tangerine-consensus-d99bc645ee0138c6ea628f77c6475eec1a61253e.tar.gz tangerine-consensus-d99bc645ee0138c6ea628f77c6475eec1a61253e.tar.zst tangerine-consensus-d99bc645ee0138c6ea628f77c6475eec1a61253e.zip |
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.
Diffstat (limited to 'core')
-rw-r--r-- | core/types/block.go | 15 | ||||
-rw-r--r-- | core/types/block_test.go | 50 |
2 files changed, 65 insertions, 0 deletions
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)) +} |