/
block_generator.go
46 lines (39 loc) · 1.1 KB
/
block_generator.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
// Package blocksutil provides utility functions for working
// with Blocks.
package blocksutil
import (
"fmt"
"github.com/ipfs/go-block-format"
cid "github.com/ipfs/go-cid"
u "github.com/ipfs/go-ipfs-util"
)
// NewBlockGenerator returns an object capable of
// producing blocks.
func NewBlockGenerator() BlockGenerator {
return BlockGenerator{}
}
func NewBlock(data []byte) *blocks.BasicBlock {
b, _ := blocks.NewBlockWithCid(data, cid.NewCidV1(cid.Raw, u.Hash(data)))
return b
}
// BlockGenerator generates BasicBlocks on demand.
// For each instace of BlockGenerator,
// each new block is different from the previous,
// although two different instances will produce the same.
type BlockGenerator struct {
seq int
}
// Next generates a new BasicBlock.
func (bg *BlockGenerator) Next() *blocks.BasicBlock {
bg.seq++
return NewBlock([]byte(fmt.Sprint(bg.seq)))
}
// Blocks generates as many BasicBlocks as specified by n.
func (bg *BlockGenerator) Blocks(n int) []blocks.Block {
blocks := make([]blocks.Block, 0, n)
for i := 0; i < n; i++ {
b := bg.Next()
blocks = append(blocks, b)
}
return blocks
}