/
block_visitor.go
43 lines (38 loc) · 1.04 KB
/
block_visitor.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
package helpers
import (
"github.com/sevenrats/boxo/fetcher"
"github.com/ipfs/go-cid"
"github.com/ipld/go-ipld-prime"
cidlink "github.com/ipld/go-ipld-prime/linking/cid"
)
// BlockResult specifies a node at the top of a block boundary
type BlockResult struct {
Node ipld.Node
Link ipld.Link
}
// BlockCallback is a callback for visiting blocks
type BlockCallback func(BlockResult) error
// OnBlocks produces a fetch call back that only gets called when visiting blocks during a fetch
func OnBlocks(bv BlockCallback) fetcher.FetchCallback {
return func(fr fetcher.FetchResult) error {
if fr.LastBlockPath.String() == fr.Path.String() {
return bv(BlockResult{
Node: fr.Node,
Link: fr.LastBlockLink,
})
}
return nil
}
}
// OnUniqueBlocks is a callback that only gets called visiting each block once
func OnUniqueBlocks(bv BlockCallback) fetcher.FetchCallback {
set := cid.NewSet()
return OnBlocks(func(br BlockResult) error {
c := br.Link.(cidlink.Link).Cid
if set.Has(c) {
return nil
}
set.Add(c)
return bv(br)
})
}