metadata.go 1.95 KB
Newer Older
1 2 3 4 5 6 7
package metadata

import (
	"github.com/ipfs/go-graphsync/ipldbridge"
	"github.com/ipld/go-ipld-prime"
)

8 9 10 11 12 13
// Item is a single link traversed in a repsonse
type Item struct {
	Link         ipld.Link
	BlockPresent bool
}

14 15
// Metadata is information about metadata contained in a response, which can be
// serialized back and forth to bytes
16
type Metadata []Item
17 18 19 20 21 22 23 24 25 26

// DecodeMetadata assembles metadata from a raw byte array, first deserializing
// as a node and then assembling into a metadata struct.
func DecodeMetadata(data []byte, ipldBridge ipldbridge.IPLDBridge) (Metadata, error) {
	node, err := ipldBridge.DecodeNode(data)
	if err != nil {
		return nil, err
	}
	decodedData, err := ipldBridge.ExtractData(node, func(simpleNode ipldbridge.SimpleNode) interface{} {
		iterator := simpleNode.ListIterator()
27 28 29 30 31
		var metadata Metadata
		if simpleNode.Length() != -1 {
			metadata = make(Metadata, 0, simpleNode.Length())
		}

32 33 34 35
		for !iterator.Done() {
			_, item := iterator.Next()
			link := item.TraverseField("link").AsLink()
			blockPresent := item.TraverseField("blockPresent").AsBool()
36
			metadata = append(metadata, Item{link, blockPresent})
37 38 39 40 41 42 43 44 45 46 47 48 49
		}
		return metadata
	})
	if err != nil {
		return nil, err
	}
	return decodedData.(Metadata), err
}

// EncodeMetadata encodes metadata to an IPLD node then serializes to raw bytes
func EncodeMetadata(entries Metadata, ipldBridge ipldbridge.IPLDBridge) ([]byte, error) {
	node, err := ipldBridge.BuildNode(func(nb ipldbridge.NodeBuilder) ipld.Node {
		return nb.CreateList(func(lb ipldbridge.ListBuilder, nb ipldbridge.NodeBuilder) {
50
			for _, item := range entries {
51 52
				lb.Append(
					nb.CreateMap(func(mb ipldbridge.MapBuilder, knb ipldbridge.NodeBuilder, vnb ipldbridge.NodeBuilder) {
53 54
						mb.Insert(knb.CreateString("link"), vnb.CreateLink(item.Link))
						mb.Insert(knb.CreateString("blockPresent"), vnb.CreateBool(item.BlockPresent))
55 56 57 58 59 60 61 62 63 64
					}),
				)
			}
		})
	})
	if err != nil {
		return nil, err
	}
	return ipldBridge.EncodeNode(node)
}