Debian Codegraph @

queues/circularbuffer/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 circularbuffer
6
7 import (
8 "encoding/json"
9
10 "github.com/emirpasic/gods/v2/containers"
11 )
12
13 // Assert Serialization implementation
14 var _ containers.JSONSerializer = (*Queue[int])(nil)
15 var _ containers.JSONDeserializer = (*Queue[int])(nil)
16
17 // ToJSON outputs the JSON representation of queue's elements.
18 func (queue *Queue[T]) ToJSON() ([]byte, error) {
19 return json.Marshal(queue.values[:queue.maxSize])
20 }
21
22 // FromJSON populates list's elements from the input JSON representation.
23 func (queue *Queue[T]) FromJSON(data []byte) error {
24 var values []T
25 err := json.Unmarshal(data, &values)
26 if err == nil {
27 for _, value := range values {
28 queue.Enqueue(value)
29 }
30 }
31 return err
32 }
33
34 // UnmarshalJSON @implements json.Unmarshaler
35 func (queue *Queue[T]) UnmarshalJSON(bytes []byte) error {
36 return queue.FromJSON(bytes)
37 }
38
39 // MarshalJSON @implements json.Marshaler
40 func (queue *Queue[T]) MarshalJSON() ([]byte, error) {
41 return queue.ToJSON()
42 }