libs5-go/serialize/seralizer.go

49 lines
934 B
Go
Raw Normal View History

2024-01-04 13:21:19 +00:00
package serialize
import (
"errors"
"git.lumeweb.com/LumeWeb/libs5-go/types"
"github.com/vmihailenco/msgpack/v5"
"slices"
2024-01-04 13:21:19 +00:00
)
func InitMarshaller(enc *msgpack.Encoder, kind types.MetadataType) error {
2024-01-04 18:49:23 +00:00
err := enc.EncodeInt(types.MetadataMagicByte)
2024-01-04 13:21:19 +00:00
if err != nil {
return err
}
2024-01-04 18:49:23 +00:00
err = enc.EncodeInt(int64(kind))
2024-01-04 13:21:19 +00:00
if err != nil {
return err
}
return nil
}
func InitUnmarshaller(enc *msgpack.Decoder, kinds ...types.MetadataType) (types.MetadataType, error) {
2024-01-04 13:21:19 +00:00
val, err := enc.DecodeUint8()
if err != nil {
return 0, err
2024-01-04 13:21:19 +00:00
}
if val != types.MetadataMagicByte {
return 0, errors.New("Invalid magic byte")
2024-01-04 13:21:19 +00:00
}
val, err = enc.DecodeUint8()
if err != nil {
return 0, err
2024-01-04 13:21:19 +00:00
}
convertedKinds := make([]uint8, len(kinds))
for i, v := range kinds {
convertedKinds[i] = uint8(v)
2024-01-04 13:21:19 +00:00
}
if !slices.Contains(convertedKinds, val) {
return 0, errors.New("Invalid metadata type")
}
return types.MetadataType(val), nil
2024-01-04 13:21:19 +00:00
}