Add base
This commit is contained in:
47
codec/binary.go
Normal file
47
codec/binary.go
Normal file
@@ -0,0 +1,47 @@
|
||||
package codec
|
||||
|
||||
import (
|
||||
"encoding"
|
||||
"fmt"
|
||||
)
|
||||
|
||||
var (
|
||||
Binary Codec = &binaryCodec{}
|
||||
)
|
||||
|
||||
type binaryCodec struct{}
|
||||
|
||||
func (*binaryCodec) Name() string {
|
||||
return "binary"
|
||||
}
|
||||
|
||||
func (*binaryCodec) Marshal(v interface{}) ([]byte, error) {
|
||||
// Check for native implementation.
|
||||
if m, ok := v.(encoding.BinaryMarshaler); ok {
|
||||
return m.MarshalBinary()
|
||||
}
|
||||
|
||||
// Otherwise assume byte slice.
|
||||
b, ok := v.([]byte)
|
||||
if !ok {
|
||||
return nil, fmt.Errorf("value not []byte")
|
||||
}
|
||||
|
||||
return b, nil
|
||||
}
|
||||
|
||||
func (*binaryCodec) Unmarshal(b []byte, v interface{}) error {
|
||||
// Check for native implementation.
|
||||
if u, ok := v.(encoding.BinaryUnmarshaler); ok {
|
||||
return u.UnmarshalBinary(b)
|
||||
}
|
||||
|
||||
// Otherwise assume byte slice.
|
||||
bp, ok := v.(*[]byte)
|
||||
if !ok {
|
||||
return fmt.Errorf("value must be *[]byte")
|
||||
}
|
||||
|
||||
*bp = append((*bp)[:0], b...)
|
||||
return nil
|
||||
}
|
20
codec/codec.go
Normal file
20
codec/codec.go
Normal file
@@ -0,0 +1,20 @@
|
||||
package codec
|
||||
|
||||
import "errors"
|
||||
|
||||
var (
|
||||
ErrCodecNotRegistered = errors.New("ceen: codec not registered")
|
||||
|
||||
Default = JSON
|
||||
|
||||
Codecs = map[string]Codec{
|
||||
JSON.Name(): JSON,
|
||||
Binary.Name(): Binary,
|
||||
}
|
||||
)
|
||||
|
||||
type Codec interface {
|
||||
Name() string
|
||||
Marshal(any) ([]byte, error)
|
||||
Unmarshal([]byte, any) error
|
||||
}
|
24
codec/json.go
Normal file
24
codec/json.go
Normal file
@@ -0,0 +1,24 @@
|
||||
package codec
|
||||
|
||||
import "encoding/json"
|
||||
|
||||
var (
|
||||
JSON Codec = &jsonCodec{}
|
||||
)
|
||||
|
||||
type jsonCodec struct{}
|
||||
|
||||
func (*jsonCodec) Name() string {
|
||||
return "json"
|
||||
}
|
||||
|
||||
func (*jsonCodec) Marshal(v any) ([]byte, error) {
|
||||
return json.Marshal(v)
|
||||
|
||||
}
|
||||
func (*jsonCodec) Unmarshal(b []byte, v any) error {
|
||||
if len(b) == 0 {
|
||||
return nil
|
||||
}
|
||||
return json.Unmarshal(b, v)
|
||||
}
|
Reference in New Issue
Block a user