// Copyright 2024 Matthew Rich . All rights reserved. package codec import ( "io" "fmt" "errors" "encoding/json" "gopkg.in/yaml.v3" ) const ( 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 { case FormatYaml, FormatJson, FormatProtoBuf: return nil default: return fmt.Errorf("%w: %s", ErrInvalidFormat, *f) } } func (f *Format) Set(value string) (err error) { if err = (*Format)(&value).Validate(); err == nil { *f = Format(value) } return } func (f *Format) UnmarshalValue(value string) error { switch value { case string(FormatYaml), string(FormatJson), string(FormatProtoBuf): *f = Format(value) return nil default: return ErrInvalidFormat } } 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) } func (f Format) Encoder(w io.Writer) Encoder { return NewEncoder(w, f) } func (f Format) Decoder(r io.Reader) Decoder { return NewDecoder(r, f) } 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) }