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

import (
4
	"fmt"
Jeromy's avatar
Jeromy committed
5
	"github.com/ipfs/go-block-format"
6

Jeromy's avatar
Jeromy committed
7 8 9
	cid "github.com/ipfs/go-cid"
	u "github.com/ipfs/go-ipfs-util"
	ipld "github.com/ipfs/go-ipld-format"
10 11
)

12
// RawNode represents a node which only contains data.
13 14 15 16
type RawNode struct {
	blocks.Block
}

Łukasz Magiera's avatar
Łukasz Magiera committed
17
// NewRawNode creates a RawNode using the default sha2-256 hash function.
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
// NewRawNodeWPrefix creates a RawNode using the provided cid builder
func NewRawNodeWPrefix(data []byte, builder cid.Builder) (*RawNode, error) {
	builder = builder.WithCodec(cid.Raw)
	c, err := builder.Sum(data)
41 42 43 44 45 46 47 48 49 50
	if err != nil {
		return nil, err
	}
	blk, err := blocks.NewBlockWithCid(data, c)
	if err != nil {
		return nil, err
	}
	return &RawNode{blk}, nil
}

51
// Links returns nil.
52
func (rn *RawNode) Links() []*ipld.Link {
53 54 55
	return nil
}

56
// ResolveLink returns an error.
57
func (rn *RawNode) ResolveLink(path []string) (*ipld.Link, []string, error) {
58 59 60
	return nil, nil, ErrLinkNotFound
}

61
// Resolve returns an error.
62
func (rn *RawNode) Resolve(path []string) (interface{}, []string, error) {
63 64 65
	return nil, nil, ErrLinkNotFound
}

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

71
// Copy performs a deep copy of this node and returns it as an ipld.Node
72
func (rn *RawNode) Copy() ipld.Node {
73 74 75 76 77 78 79 80 81 82 83
	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}
}

84
// Size returns the size of this node
85 86 87 88
func (rn *RawNode) Size() (uint64, error) {
	return uint64(len(rn.RawData())), nil
}

89
// Stat returns some Stats about this node.
90 91
func (rn *RawNode) Stat() (*ipld.NodeStat, error) {
	return &ipld.NodeStat{
92 93 94 95 96
		CumulativeSize: len(rn.RawData()),
		DataSize:       len(rn.RawData()),
	}, nil
}

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