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

3
import (
Rod Vagg's avatar
Rod Vagg committed
4
	"bytes"
5 6 7 8 9
	"sort"

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

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

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

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
}

33 34 35 36
type linkBuilder struct {
	link *PBLink
}

Rod Vagg's avatar
Rod Vagg committed
37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52
func (lb *linkBuilder) SetHash(hash *cid.Cid) error {
	lb.link.Hash = hash
	return nil
}

func (lb *linkBuilder) SetName(name *string) error {
	lb.link.Name = name
	return nil
}

func (lb *linkBuilder) SetTsize(tsize uint64) error {
	lb.link.Tsize = &tsize
	return nil
}

func (lb *linkBuilder) Done() error { return nil }
53 54 55 56 57

type nodeBuilder struct {
	node *PBNode
}

Rod Vagg's avatar
Rod Vagg committed
58 59 60 61 62 63
func (nb *nodeBuilder) SetData(data []byte) error {
	nb.node.Data = data
	return nil
}

func (nb *nodeBuilder) AddLink() (PBLinkBuilder, error) {
64 65
	nb.mklinks()
	nb.node.Links = append(nb.node.Links, &PBLink{})
Rod Vagg's avatar
Rod Vagg committed
66
	return &linkBuilder{nb.node.Links[len(nb.node.Links)-1]}, nil
67
}
Rod Vagg's avatar
Rod Vagg committed
68

69 70 71 72 73
func (nb *nodeBuilder) mklinks() {
	if nb.node.Links == nil {
		nb.node.Links = make([]*PBLink, 0)
	}
}
Rod Vagg's avatar
Rod Vagg committed
74 75

func (nb *nodeBuilder) Done() error {
76
	nb.mklinks()
Rod Vagg's avatar
Rod Vagg committed
77
	return nil
78 79
}

Rod Vagg's avatar
Rod Vagg committed
80
func UnmarshalPBNode(byts []byte) (*PBNode, error) {
81 82
	nb := nodeBuilder{NewPBNode()}

Rod Vagg's avatar
Rod Vagg committed
83
	if err := Unmarshal(bytes.NewReader(byts), &nb); err != nil {
84 85
		return nil, err
	}
Rod Vagg's avatar
Rod Vagg committed
86 87
	nb.Done()
	return nb.node, nil
88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112
}

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
}