From 8b59dc292b8eb58a5b999dab21902618a3b8c04f Mon Sep 17 00:00:00 2001 From: Eric Myhre Date: Tue, 28 Apr 2020 18:28:20 +0200 Subject: [PATCH] Add two basic examples of usage, as go tests. --- examples_test.go | 47 +++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 47 insertions(+) create mode 100644 examples_test.go diff --git a/examples_test.go b/examples_test.go new file mode 100644 index 0000000..b5d9472 --- /dev/null +++ b/examples_test.go @@ -0,0 +1,47 @@ +package ipld_test + +import ( + "bytes" + "fmt" + "os" + + "github.com/ipld/go-ipld-prime/codec/dagjson" + "github.com/ipld/go-ipld-prime/node/basic" +) + +func ExampleCreateDataAndMarshal() { + + ns := basicnode.Style.Any // Pick a style for the in-memory data. + nb := ns.NewBuilder() // Create a builder. + ma, _ := nb.BeginMap(2) // Begin assembling a map. + 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!) + + dagjson.Encoder(n, os.Stdout) + + // Output: + // { + // "hey": "it works!", + // "yes": true + // } +} + +func ExampleUnmarshalData() { + serial := bytes.NewBufferString(`{"hey":"it works!","yes": true}`) + + ns := basicnode.Style.Any // Pick a stle for the in-memory data. + nb := ns.NewBuilder() // Create a builder. + dagjson.Decoder(nb, serial) // Hand the builder to decoding -- decoding will fill it in! + n := nb.Build() // Call 'Build' to get the resulting Node. (It's immutable!) + + fmt.Printf("the data decoded was a %s kind\n", n.ReprKind()) + fmt.Printf("the length of the node is %d\n", n.Length()) + + // Output: + // the data decoded was a Map kind + // the length of the node is 2 +} -- GitLab