dagpb.go 1.32 KB
Newer Older
1
package pb
Rod Vagg's avatar
Rod Vagg committed
2

3 4 5 6 7 8
import (
	"sort"

	cid "github.com/ipfs/go-cid"
)

Rod Vagg's avatar
Rod Vagg committed
9 10
// PBLink ...
type PBLink struct {
11
	Hash  *cid.Cid
Rod Vagg's avatar
Rod Vagg committed
12 13 14 15 16 17 18 19 20
	Name  *string
	Tsize *uint64
}

// PBNode ...
type PBNode struct {
	Links []*PBLink
	Data  []byte
}
21 22 23 24 25 26 27 28 29 30 31

func NewPBNode() *PBNode {
	n := &PBNode{Links: make([]*PBLink, 0)}
	return n
}

func NewPBNodeFromData(data []byte) *PBNode {
	n := &PBNode{Data: data, Links: make([]*PBLink, 0)}
	return n
}

Rod Vagg's avatar
Rod Vagg committed
32
type TokenType byte
33

Rod Vagg's avatar
Rod Vagg committed
34 35 36 37 38 39 40 41 42 43
const (
	TypeData    TokenType = 'd'
	TypeLinks   TokenType = '['
	TypeLink    TokenType = 'l'
	TypeLinkEnd TokenType = 'e'
	TypeHash    TokenType = 'h'
	TypeName    TokenType = 'n'
	TypeTSize   TokenType = 's'
	TypeEnd     TokenType = 'x'
)
44

Rod Vagg's avatar
Rod Vagg committed
45 46 47 48 49
type Token struct {
	Type  TokenType
	Bytes []byte
	Cid   *cid.Cid
	Int   uint64
50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74
}

func NewPBLinkFromCid(c cid.Cid) *PBLink {
	l := &PBLink{Hash: &c}
	return l
}

func NewPBLink(name string, c cid.Cid, tsize uint64) *PBLink {
	l := &PBLink{Name: &name, Hash: &c, Tsize: &tsize}
	return l
}

func (node *PBNode) SortLinks() {
	sort.Stable(pbLinkSlice(node.Links))
}

type pbLinkSlice []*PBLink

func (ls pbLinkSlice) Len() int           { return len(ls) }
func (ls pbLinkSlice) Swap(a, b int)      { ls[a], ls[b] = ls[b], ls[a] }
func (ls pbLinkSlice) Less(a, b int) bool { return pbLinkLess(ls[a], ls[b]) }

func pbLinkLess(a *PBLink, b *PBLink) bool {
	return *a.Name < *b.Name
}