Debian Codegraph @

trees/redblacktree/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 redblacktree
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 tree.Clear()
33 for key, value := range elements {
34 tree.Put(key, value)
35 }
36 }
37 return err
38 }
39
40 // UnmarshalJSON @implements json.Unmarshaler
41 func (tree *Tree[K, V]) UnmarshalJSON(bytes []byte) error {
42 return tree.FromJSON(bytes)
43 }
44
45 // MarshalJSON @implements json.Marshaler
46 func (tree *Tree[K, V]) MarshalJSON() ([]byte, error) {
47 return tree.ToJSON()
48 }