Debian Codegraph @

trees/btree/serialization.go

raw symbols SCIP
1 // Copyright (c) 2015, Emir Pasic. All rights reserved.
2 // Use of this source code is governed by a BSD-style
3 // license that can be found in the LICENSE file.
4
5 package btree
6
7 import (
8 "encoding/json"
9
10 "github.com/emirpasic/gods/v2/containers"
11 )
12
13 // Assert Serialization implementation
14 var _ containers.JSONSerializer = (*Tree[string, int])(nil)
15 var _ containers.JSONDeserializer = (*Tree[string, int])(nil)
16
17 // ToJSON outputs the JSON representation of the tree.
18 func (tree *Tree[K, V]) ToJSON() ([]byte, error) {
19 elements := make(map[K]V)
20 it := tree.Iterator()
21 for it.Next() {
22 elements[it.Key()] = it.Value()
23 }
24 return json.Marshal(&elements)
25 }
26
27 // FromJSON populates the tree from the input JSON representation.
28 func (tree *Tree[K, V]) FromJSON(data []byte) error {
29 elements := make(map[K]V)
30 err := json.Unmarshal(data, &elements)
31 if err != nil {
32 return err
33 }
34
35 tree.Clear()
36 for key, value := range elements {
37 tree.Put(key, value)
38 }
39
40 return err
41 }
42
43 // UnmarshalJSON @implements json.Unmarshaler
44 func (tree *Tree[K, V]) UnmarshalJSON(bytes []byte) error {
45 return tree.FromJSON(bytes)
46 }
47
48 // MarshalJSON @implements json.Marshaler
49 func (tree *Tree[K, V]) MarshalJSON() ([]byte, error) {
50 return tree.ToJSON()
51 }