jx/internal/codec/types.go

88 lines
1.7 KiB
Go
Raw Permalink Normal View History

2024-07-01 07:16:55 +00:00
// Copyright 2024 Matthew Rich <matthewrich.conf@gmail.com>. All rights reserved.
package codec
import (
2024-07-17 08:34:57 +00:00
"io"
"fmt"
2024-07-01 07:16:55 +00:00
"errors"
"encoding/json"
"gopkg.in/yaml.v3"
)
const (
2024-08-18 01:16:02 +00:00
FormatYml Format = "yml"
2024-07-01 07:16:55 +00:00
FormatYaml Format = "yaml"
FormatJson Format = "json"
FormatProtoBuf Format = "protobuf"
)
var ErrInvalidFormat error = errors.New("invalid Format value")
type Format string
func (f *Format) Validate() error {
switch *f {
2024-08-18 01:16:02 +00:00
case FormatYml, FormatYaml, FormatJson, FormatProtoBuf:
2024-07-01 07:16:55 +00:00
return nil
default:
2024-07-17 08:34:57 +00:00
return fmt.Errorf("%w: %s", ErrInvalidFormat, *f)
2024-07-01 07:16:55 +00:00
}
}
func (f *Format) Set(value string) (err error) {
if err = (*Format)(&value).Validate(); err == nil {
2024-08-18 01:16:02 +00:00
err = f.UnmarshalValue(value)
2024-07-01 07:16:55 +00:00
}
return
}
func (f *Format) UnmarshalValue(value string) error {
switch value {
2024-08-18 01:16:02 +00:00
case string(FormatYml):
*f = FormatYaml
2024-07-01 07:16:55 +00:00
case string(FormatYaml), string(FormatJson), string(FormatProtoBuf):
*f = Format(value)
default:
return ErrInvalidFormat
}
2024-08-18 01:16:02 +00:00
return nil
2024-07-01 07:16:55 +00:00
}
func (f *Format) UnmarshalJSON(data []byte) error {
var s string
if unmarshalFormatTypeErr := json.Unmarshal(data, &s); unmarshalFormatTypeErr != nil {
return unmarshalFormatTypeErr
}
return f.UnmarshalValue(s)
}
func (f *Format) UnmarshalYAML(value *yaml.Node) error {
var s string
if err := value.Decode(&s); err != nil {
return err
}
return f.UnmarshalValue(s)
}
2024-07-17 08:34:57 +00:00
func (f Format) Encoder(w io.Writer) Encoder {
return NewEncoder(w, f)
}
func (f Format) Decoder(r io.Reader) Decoder {
return NewDecoder(r, f)
}
2024-08-15 15:12:42 +00:00
func (f Format) StringDecoder(s string) Decoder {
return NewStringDecoder(s, f)
}
2024-07-17 08:34:57 +00:00
func (f Format) Serialize(object any, w io.Writer) error {
return f.Encoder(w).Encode(object)
}
func (f Format) Deserialize(r io.Reader, object any) error {
return f.Decoder(r).Decode(object)
}