raw.go 2.38 KB
Newer Older
1 2 3
package merkledag

import (
4
	"fmt"
Steven Allen's avatar
Steven Allen committed
5
	"gx/ipfs/Qmej7nf81hi2x2tvjRBF3mcp74sQyuDH4VMYDGd1YtXjb2/go-block-format"
6

Steven Allen's avatar
Steven Allen committed
7 8
	u "gx/ipfs/QmNiJuT8Ja3hMVpBHXv3Q6dwmperaQ6JjLtpMQgMCD7xvx/go-ipfs-util"
	cid "gx/ipfs/QmcZfnkapfECQGcLZaf9B79NRg7cRa9EnZh4LSbkCzwNvY/go-cid"
9
	ipld "gx/ipfs/Qme5bWv7wtjUNGsK2BNGVUFPKiuxWrsqrtvYwCLRw8YFES/go-ipld-format"
10 11 12 13 14 15
)

type RawNode struct {
	blocks.Block
}

16 17
// NewRawNode creates a RawNode using the default sha2-256 hash
// funcition.
18 19 20 21 22 23 24 25
func NewRawNode(data []byte) *RawNode {
	h := u.Hash(data)
	c := cid.NewCidV1(cid.Raw, h)
	blk, _ := blocks.NewBlockWithCid(data, c)

	return &RawNode{blk}
}

26
// DecodeRawBlock is a block decoder for raw IPLD nodes conforming to `node.DecodeBlockFunc`.
27
func DecodeRawBlock(block blocks.Block) (ipld.Node, error) {
28 29 30 31 32 33 34
	if block.Cid().Type() != cid.Raw {
		return nil, fmt.Errorf("raw nodes cannot be decoded from non-raw blocks: %d", block.Cid().Type())
	}
	// Once you "share" a block, it should be immutable. Therefore, we can just use this block as-is.
	return &RawNode{block}, nil
}

35
var _ ipld.DecodeBlockFunc = DecodeRawBlock
36

37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54
// NewRawNodeWPrefix creates a RawNode with the hash function
// specified in prefix.
func NewRawNodeWPrefix(data []byte, prefix cid.Prefix) (*RawNode, error) {
	prefix.Codec = cid.Raw
	if prefix.Version == 0 {
		prefix.Version = 1
	}
	c, err := prefix.Sum(data)
	if err != nil {
		return nil, err
	}
	blk, err := blocks.NewBlockWithCid(data, c)
	if err != nil {
		return nil, err
	}
	return &RawNode{blk}, nil
}

55
func (rn *RawNode) Links() []*ipld.Link {
56 57 58
	return nil
}

59
func (rn *RawNode) ResolveLink(path []string) (*ipld.Link, []string, error) {
60 61 62 63
	return nil, nil, ErrLinkNotFound
}

func (rn *RawNode) Resolve(path []string) (interface{}, []string, error) {
64 65 66
	return nil, nil, ErrLinkNotFound
}

67
func (rn *RawNode) Tree(p string, depth int) []string {
68 69 70
	return nil
}

71
func (rn *RawNode) Copy() ipld.Node {
72 73 74 75 76 77 78 79 80 81 82
	copybuf := make([]byte, len(rn.RawData()))
	copy(copybuf, rn.RawData())
	nblk, err := blocks.NewBlockWithCid(rn.RawData(), rn.Cid())
	if err != nil {
		// programmer error
		panic("failure attempting to clone raw block: " + err.Error())
	}

	return &RawNode{nblk}
}

83 84 85 86
func (rn *RawNode) Size() (uint64, error) {
	return uint64(len(rn.RawData())), nil
}

87 88
func (rn *RawNode) Stat() (*ipld.NodeStat, error) {
	return &ipld.NodeStat{
89 90 91 92 93
		CumulativeSize: len(rn.RawData()),
		DataSize:       len(rn.RawData()),
	}, nil
}

94
var _ ipld.Node = (*RawNode)(nil)