2024-01-04 13:21:19 +00:00
|
|
|
package serialize
|
|
|
|
|
|
|
|
import (
|
|
|
|
"errors"
|
|
|
|
"git.lumeweb.com/LumeWeb/libs5-go/types"
|
|
|
|
"github.com/vmihailenco/msgpack/v5"
|
2024-03-01 04:35:45 +00:00
|
|
|
"slices"
|
2024-01-04 13:21:19 +00:00
|
|
|
)
|
|
|
|
|
2024-03-01 04:36:48 +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
|
|
|
|
}
|
|
|
|
|
2024-03-01 04:35:45 +00:00
|
|
|
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 {
|
2024-03-01 04:35:45 +00:00
|
|
|
return 0, err
|
2024-01-04 13:21:19 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
if val != types.MetadataMagicByte {
|
2024-03-01 04:35:45 +00:00
|
|
|
return 0, errors.New("Invalid magic byte")
|
2024-01-04 13:21:19 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
val, err = enc.DecodeUint8()
|
|
|
|
if err != nil {
|
2024-03-01 04:35:45 +00:00
|
|
|
return 0, err
|
2024-01-04 13:21:19 +00:00
|
|
|
}
|
|
|
|
|
2024-03-01 04:35:45 +00:00
|
|
|
convertedKinds := make([]uint8, len(kinds))
|
|
|
|
for i, v := range kinds {
|
|
|
|
convertedKinds[i] = uint8(v)
|
2024-01-04 13:21:19 +00:00
|
|
|
}
|
|
|
|
|
2024-03-01 04:35:45 +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
|
|
|
}
|