feat: add serialize package

This commit is contained in:
Derrick Hammer 2024-01-04 08:21:19 -05:00
parent c2ed126ab8
commit bebea5a7e1
Signed by: pcfreak30
GPG Key ID: C997C339BE476FF2
2 changed files with 82 additions and 0 deletions

50
serialize/seralizer.go Normal file
View File

@ -0,0 +1,50 @@
package serialize
import (
"errors"
"git.lumeweb.com/LumeWeb/libs5-go/types"
"github.com/vmihailenco/msgpack/v5"
)
/*
func NewSerializer(kind types.MetadataType) *Packer {
p := NewPacker()
_ = p.PackUint8(types.MetadataMagicByte)
_ = p.PackUint8(uint8(types.MetadataTypeDirectory))
return p
}
*/
func InitMarshaller(kind types.MetadataType, enc *msgpack.Encoder) error {
err := enc.EncodeUint8(types.MetadataMagicByte)
if err != nil {
return err
}
err = enc.EncodeUint8(uint8(kind))
if err != nil {
return err
}
return nil
}
func InitUnmarshaller(kind types.MetadataType, enc *msgpack.Decoder) error {
val, err := enc.DecodeUint8()
if err != nil {
return err
}
if val != types.MetadataMagicByte {
return errors.New("Invalid magic byte")
}
val, err = enc.DecodeUint8()
if err != nil {
return err
}
if val != uint8(kind) {
return errors.New("Invalid metadata type")
}
return nil
}

32
serialize/serialize.go Normal file
View File

@ -0,0 +1,32 @@
package serialize
import (
"encoding/base64"
"github.com/multiformats/go-multibase"
)
func UnmarshalBase64UrlJSON(data []byte) ([]byte, error) {
strData := string(data)
if len(strData) >= 2 && strData[0] == '"' && strData[len(strData)-1] == '"' {
strData = strData[1 : len(strData)-1]
}
if strData == "null" {
return nil, nil
}
if strData[0] == 'u' {
_, decoded, err := multibase.Decode(strData)
if err != nil {
return nil, err
}
return decoded, nil
}
decodedData, err := base64.RawURLEncoding.DecodeString(strData)
if err != nil {
return nil, err
}
return decodedData, nil
}