|
| 1 | +/* |
| 2 | + * Copyright (c) 2024 Mikhail Knyazhev <[email protected]>. All rights reserved. |
| 3 | + * Use of this source code is governed by a BSD 3-Clause license that can be found in the LICENSE file. |
| 4 | + */ |
| 5 | + |
| 6 | +package codec |
| 7 | + |
| 8 | +import ( |
| 9 | + "encoding/json" |
| 10 | + |
| 11 | + "go.osspkg.com/errors" |
| 12 | + "go.osspkg.com/syncing" |
| 13 | + "gopkg.in/yaml.v3" |
| 14 | +) |
| 15 | + |
| 16 | +const ( |
| 17 | + EncoderYAML = ".yaml" |
| 18 | + EncoderJSON = ".json" |
| 19 | +) |
| 20 | + |
| 21 | +var ( |
| 22 | + errBadFormat = errors.New("format is not a supported") |
| 23 | + |
| 24 | + _default = newEncoders(). |
| 25 | + Add(".yml", yaml.Marshal, yaml.Unmarshal, mapMerge). |
| 26 | + Add(EncoderYAML, yaml.Marshal, yaml.Unmarshal, mapMerge). |
| 27 | + Add(EncoderJSON, json.Marshal, json.Unmarshal, mapMerge) |
| 28 | +) |
| 29 | + |
| 30 | +type ( |
| 31 | + Codec struct { |
| 32 | + Encode func(in interface{}) ([]byte, error) |
| 33 | + Decode func(b []byte, out interface{}) error |
| 34 | + Merge func(dst map[string]interface{}, src map[string]interface{}) error |
| 35 | + } |
| 36 | + encoders struct { |
| 37 | + list map[string]Codec |
| 38 | + mux syncing.Lock |
| 39 | + } |
| 40 | +) |
| 41 | + |
| 42 | +func newEncoders() *encoders { |
| 43 | + return &encoders{ |
| 44 | + list: make(map[string]Codec, 10), |
| 45 | + mux: syncing.NewLock(), |
| 46 | + } |
| 47 | +} |
| 48 | + |
| 49 | +func AddCodec(ext string, c Codec) { |
| 50 | + _default.Add(ext, c.Encode, c.Decode, c.Merge) |
| 51 | +} |
| 52 | + |
| 53 | +func (v *encoders) Add( |
| 54 | + ext string, |
| 55 | + enc func(interface{}) ([]byte, error), |
| 56 | + dec func([]byte, interface{}) error, |
| 57 | + merge func(map[string]interface{}, map[string]interface{}) error, |
| 58 | +) *encoders { |
| 59 | + v.mux.Lock(func() { |
| 60 | + v.list[ext] = Codec{ |
| 61 | + Encode: enc, |
| 62 | + Decode: dec, |
| 63 | + Merge: merge, |
| 64 | + } |
| 65 | + }) |
| 66 | + return v |
| 67 | +} |
| 68 | + |
| 69 | +func (v *encoders) Get(ext string) (c Codec, err error) { |
| 70 | + v.mux.RLock(func() { |
| 71 | + var ok bool |
| 72 | + if c, ok = v.list[ext]; !ok { |
| 73 | + err = errBadFormat |
| 74 | + return |
| 75 | + } |
| 76 | + }) |
| 77 | + return |
| 78 | +} |
0 commit comments