/
codecs.go
88 lines (70 loc) · 2.57 KB
/
codecs.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
75
76
77
78
79
80
81
82
83
84
85
86
87
88
// SPDX-FileCopyrightText: 2022 SAP SE or an SAP affiliate company and Open Component Model contributors.
//
// SPDX-License-Identifier: Apache-2.0
package compdesc
import (
"encoding/json"
"sigs.k8s.io/yaml"
)
// Codec describes an encoding for en object.
type Codec interface {
Decoder
StrictDecoder
Encoder
}
// CodecWrapper is a simple struct that implements the Codec interface.
type CodecWrapper struct {
Decoder
StrictDecoder
Encoder
}
// ApplyEncodeOption applies the configured codec.
func (o CodecWrapper) ApplyEncodeOption(options *EncodeOptions) {
options.Codec = o
}
// ApplyDecodeOption applies the configured codec.
func (o CodecWrapper) ApplyDecodeOption(options *DecodeOptions) {
options.Codec = o
}
// Decoder defines a decoder for an object.
type Decoder interface {
Decode(data []byte, obj interface{}) error
}
// StrictDecoder defines a decoder for an object.
type StrictDecoder interface {
DecodeStrict(data []byte, obj interface{}) error
}
// Encoder defines a encoder for an object.
type Encoder interface {
Encode(obj interface{}) ([]byte, error)
}
// DecoderFunc is a simple function that implements the Decoder interface.
type DecoderFunc func(data []byte, obj interface{}) error
// Decode is the Decode implementation of the Decoder interface.
func (e DecoderFunc) Decode(data []byte, obj interface{}) error {
return e(data, obj)
}
// StrictDecoderFunc is a simple function that implements the StrictDecoder interface.
type StrictDecoderFunc func(data []byte, obj interface{}) error
// StrictDecode is the Decode implementation of the Decoder interface.
func (e StrictDecoderFunc) DecodeStrict(data []byte, obj interface{}) error {
return e(data, obj)
}
// EncoderFunc is a simple function that implements the Encoder interface.
type EncoderFunc func(obj interface{}) ([]byte, error)
// Encode is the Encode implementation of the Encoder interface.
func (e EncoderFunc) Encode(obj interface{}) ([]byte, error) {
return e(obj)
}
// DefaultYAMLCodec implements Codec interface with the yaml decoder encoder.
var DefaultYAMLCodec = CodecWrapper{
Decoder: DecoderFunc(func(data []byte, obj interface{}) error { return yaml.Unmarshal(data, obj) }),
StrictDecoder: StrictDecoderFunc(func(data []byte, obj interface{}) error { return yaml.UnmarshalStrict(data, obj) }),
Encoder: EncoderFunc(yaml.Marshal),
}
// DefaultJSONCodec implements Codec interface with the json decoder encoder.
var DefaultJSONCodec = CodecWrapper{
Decoder: DecoderFunc(json.Unmarshal),
StrictDecoder: StrictDecoderFunc(json.Unmarshal),
Encoder: EncoderFunc(json.Marshal),
}