-
Notifications
You must be signed in to change notification settings - Fork 0
/
flatpack_extern_test.go
74 lines (63 loc) · 1.83 KB
/
flatpack_extern_test.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
/* Copyright 2017 Google Inc.
* https://github.com/NeilFraser/CodeCity
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package flatpack_test
import (
"encoding/json"
"github.com/cpcallen/flatpack"
"github.com/cpcallen/testutil"
)
func Example() {
// Some complicated data with shared substructure and cycles:
type cons struct{ car, cdr interface{} }
var m = make(map[string]interface{})
var stuff = &cons{
car: cons{car: "hello", cdr: 42},
cdr: &cons{car: m, cdr: nil},
}
m["foo"] = stuff
m["bar"] = stuff
stuff.cdr.(*cons).cdr = stuff.cdr
// Create Flatpack and store stuff in it:
var f = flatpack.New()
f.Pack("stuff", stuff)
f.Seal()
// Convert it to JSON:
b, e := json.MarshalIndent(f, "", " ")
if e != nil {
panic(e)
}
// Register types of stuff we will ask Unpack() to reconstruct
// (this must include all types it may find in interfaces):
flatpack.RegisterTypeOf(cons{})
flatpack.RegisterTypeOf(m)
// Convert JSON back to Flatpack:
var f2 *flatpack.Flatpack // N.B.: not using New()
e = json.Unmarshal(b, &f2)
if e != nil {
panic(e)
}
// Unpack stuff:
v, err := f.Unpack("stuff")
if err != nil {
panic(err)
}
var stuff2 *cons = v.(*cons)
// Verify stuff2 is an exact (but disjoint) copy of stuff:
if !testutil.RecEqual(stuff, stuff2, true) {
panic(testutil.Diff(stuff, stuff2))
}
// Output:
}