2018-09-20 23:55:06 +00:00
|
|
|
// Copyright (c) 2015, Emir Pasic. All rights reserved.
|
|
|
|
// Use of this source code is governed by a BSD-style
|
|
|
|
// license that can be found in the LICENSE file.
|
|
|
|
|
|
|
|
package linkedhashset
|
|
|
|
|
|
|
|
import (
|
|
|
|
"encoding/json"
|
2024-01-07 00:06:17 +00:00
|
|
|
|
|
|
|
"github.com/emirpasic/gods/v2/containers"
|
2018-09-20 23:55:06 +00:00
|
|
|
)
|
|
|
|
|
2022-04-13 13:04:39 +00:00
|
|
|
// Assert Serialization implementation
|
2024-01-07 00:06:17 +00:00
|
|
|
var _ containers.JSONSerializer = (*Set[int])(nil)
|
|
|
|
var _ containers.JSONDeserializer = (*Set[int])(nil)
|
2018-09-20 23:55:06 +00:00
|
|
|
|
2018-09-21 02:45:26 +00:00
|
|
|
// ToJSON outputs the JSON representation of the set.
|
2024-01-07 00:06:17 +00:00
|
|
|
func (set *Set[T]) ToJSON() ([]byte, error) {
|
2018-09-20 23:55:06 +00:00
|
|
|
return json.Marshal(set.Values())
|
|
|
|
}
|
|
|
|
|
2018-09-21 02:45:26 +00:00
|
|
|
// FromJSON populates the set from the input JSON representation.
|
2024-01-07 00:06:17 +00:00
|
|
|
func (set *Set[T]) FromJSON(data []byte) error {
|
|
|
|
var elements []T
|
2018-09-20 23:55:06 +00:00
|
|
|
err := json.Unmarshal(data, &elements)
|
|
|
|
if err == nil {
|
|
|
|
set.Clear()
|
|
|
|
set.Add(elements...)
|
|
|
|
}
|
|
|
|
return err
|
|
|
|
}
|
2021-04-08 07:19:55 +00:00
|
|
|
|
2022-04-12 02:31:44 +00:00
|
|
|
// UnmarshalJSON @implements json.Unmarshaler
|
2024-01-07 00:06:17 +00:00
|
|
|
func (set *Set[T]) UnmarshalJSON(bytes []byte) error {
|
2021-04-08 07:19:55 +00:00
|
|
|
return set.FromJSON(bytes)
|
|
|
|
}
|
|
|
|
|
2022-04-12 02:31:44 +00:00
|
|
|
// MarshalJSON @implements json.Marshaler
|
2024-01-07 00:06:17 +00:00
|
|
|
func (set *Set[T]) MarshalJSON() ([]byte, error) {
|
2021-04-08 07:19:55 +00:00
|
|
|
return set.ToJSON()
|
|
|
|
}
|