|
1 | 1 | package rot13adl_test
|
2 | 2 |
|
3 | 3 | import (
|
| 4 | + "bytes" |
4 | 5 | "fmt"
|
5 | 6 | "strings"
|
6 | 7 |
|
@@ -38,6 +39,39 @@ func ExampleUnmarshallingToADL() {
|
38 | 39 | // adl view value: "a cool string"
|
39 | 40 | }
|
40 | 41 |
|
| 42 | +func ExampleCreatingViaADL() { |
| 43 | + // Create a NodeBuilder for the ADL -- the high-level synthesized thing (not the substrate). |
| 44 | + nb := rot13adl.Prototype.Node.NewBuilder() |
| 45 | + |
| 46 | + // Create a ADL node via its builder. This is just like creating any other node in IPLD. |
| 47 | + nb.AssignString("woohoo") |
| 48 | + n := nb.Build() |
| 49 | + |
| 50 | + // We can inspect the synthetic ADL node like any other node! |
| 51 | + fmt.Printf("adl node kind: %v\n", n.ReprKind()) |
| 52 | + fmt.Printf("adl view value: %q\n", must.String(n)) |
| 53 | + |
| 54 | + // We can get the substrate view and examine that as a node too. |
| 55 | + // (This requires a cast to see that we have an ADL, though. Not all IPLD nodes have a 'Substrate' property.) |
| 56 | + substrateNode := n.(rot13adl.R13String).Substrate() |
| 57 | + fmt.Printf("substrate node kind: %v\n", substrateNode.ReprKind()) |
| 58 | + fmt.Printf("substrate value: %q\n", must.String(substrateNode)) |
| 59 | + |
| 60 | + // To marshal the ADL, just use marshal methods on its substrate as normal: |
| 61 | + var marshalBuffer bytes.Buffer |
| 62 | + err := dagjson.Marshal(substrateNode, json.NewEncoder(&marshalBuffer, json.EncodeOptions{})) |
| 63 | + fmt.Printf("marshalled: %v\n", marshalBuffer.String()) |
| 64 | + fmt.Printf("marshal error: %v\n", err) |
| 65 | + |
| 66 | + // Output: |
| 67 | + // adl node kind: string |
| 68 | + // adl view value: "woohoo" |
| 69 | + // substrate node kind: string |
| 70 | + // substrate value: "jbbubb" |
| 71 | + // marshalled: "jbbubb" |
| 72 | + // marshal error: <nil> |
| 73 | +} |
| 74 | + |
41 | 75 | // It's worth noting that the builders for an ADL substrate node still return the substrate.
|
42 | 76 | // (This is interesting in contrast to Schemas, where codegenerated representation-level builders
|
43 | 77 | // yield the type-level node values (and not the representation level node).)
|
|
0 commit comments