examples_test.go 1.89 KB
Newer Older
1 2 3 4 5
package ipld_test

import (
	"fmt"
	"os"
6
	"strings"
7 8

	"github.com/ipld/go-ipld-prime/codec/dagjson"
9
	basicnode "github.com/ipld/go-ipld-prime/node/basic"
10 11
)

12 13 14 15 16 17
// Example_createDataAndMarshal shows how you can feed data into a NodeBuilder,
// and also how to then hand that to an Encoder.
//
// Often you'll encoding implicitly through a LinkSystem.Store call instead,
// but you can do it directly, too.
func Example_createDataAndMarshal() {
18 19 20
	np := basicnode.Prototype.Any // Pick a prototype: this is how we decide what implementation will store the in-memory data.
	nb := np.NewBuilder()         // Create a builder.
	ma, _ := nb.BeginMap(2)       // Begin assembling a map.
21 22 23 24 25 26 27
	ma.AssembleKey().AssignString("hey")
	ma.AssembleValue().AssignString("it works!")
	ma.AssembleKey().AssignString("yes")
	ma.AssembleValue().AssignBool(true)
	ma.Finish()     // Call 'Finish' on the map assembly to let it know no more data is coming.
	n := nb.Build() // Call 'Build' to get the resulting Node.  (It's immutable!)

Eric Myhre's avatar
Eric Myhre committed
28
	dagjson.Encode(n, os.Stdout)
29 30

	// Output:
31
	// {"hey":"it works!","yes":true}
32 33
}

34 35 36 37 38 39
// Example_unmarshalData shows how you can use a Decoder
// and a NodeBuilder (or NodePrototype) together to do unmarshalling.
//
// Often you'll do this implicitly through a LinkSystem.Load call instead,
// but you can do it directly, too.
func Example_unmarshalData() {
40
	serial := strings.NewReader(`{"hey":"it works!","yes": true}`)
41

42 43
	np := basicnode.Prototype.Any // Pick a stle for the in-memory data.
	nb := np.NewBuilder()         // Create a builder.
Eric Myhre's avatar
Eric Myhre committed
44
	dagjson.Decode(nb, serial)    // Hand the builder to decoding -- decoding will fill it in!
45
	n := nb.Build()               // Call 'Build' to get the resulting Node.  (It's immutable!)
46

47
	fmt.Printf("the data decoded was a %s kind\n", n.Kind())
48 49 50
	fmt.Printf("the length of the node is %d\n", n.Length())

	// Output:
51
	// the data decoded was a map kind
52 53
	// the length of the node is 2
}