feat: add json marshal support to encoding

This commit is contained in:
Derrick Hammer 2024-01-04 04:19:24 -05:00
parent 5e0b9db382
commit 4457dff415
Signed by: pcfreak30
GPG Key ID: C997C339BE476FF2
3 changed files with 49 additions and 0 deletions

View File

@ -3,6 +3,7 @@ package encoding
import (
"bytes"
"encoding/hex"
"encoding/json"
"errors"
"fmt"
"git.lumeweb.com/LumeWeb/libs5-go/internal/bases"
@ -22,6 +23,8 @@ type CID struct {
Size uint32
}
var _ json.Marshaler = (*CID)(nil)
func NewCID(Type types.CIDType, Hash Multihash, Size uint32) *CID {
c := &CID{
Type: Type,
@ -195,6 +198,17 @@ func (cid *CID) HashCode() int {
int(fullBytes[3])<<24
}
func (cid CID) MarshalJSON() ([]byte, error) {
// Delegate to the MarshalJSON method of the encoder
return json.Marshal(cid.Multibase)
}
func (cid *CID) UnmarshalJSON(data []byte) error {
if err := json.Unmarshal(data, &cid.Multibase); err != nil {
return err
}
return nil
}
func CIDFromRegistryPublicKey(pubkey interface{}) (*CID, error) {
return CIDFromHash(pubkey, 0, types.CIDTypeResolver)
}

View File

@ -1,6 +1,7 @@
package encoding
import (
"encoding/json"
"errors"
"git.lumeweb.com/LumeWeb/libs5-go/internal/bases"
"github.com/multiformats/go-multibase"
@ -20,6 +21,8 @@ type multibaseImpl struct {
encoder Encoder
}
var _ json.Marshaler = (*multibaseImpl)(nil)
type Multibase interface {
ToHex() (string, error)
ToBase32() (string, error)
@ -70,3 +73,12 @@ func (m *multibaseImpl) ToBase58() (string, error) {
func (m *multibaseImpl) ToString() (string, error) {
return m.ToBase58()
}
func (b multibaseImpl) MarshalJSON() ([]byte, error) {
url, err := b.ToBase64Url()
if err != nil {
return nil, err
}
return []byte(url), nil
}

View File

@ -2,6 +2,7 @@ package encoding
import (
"bytes"
"encoding/json"
"errors"
"fmt"
"git.lumeweb.com/LumeWeb/libs5-go/internal/bases"
@ -21,6 +22,9 @@ type Multihash struct {
FullBytes []byte
}
var _ json.Marshaler = (*Multihash)(nil)
var _ json.Unmarshaler = (*Multihash)(nil)
func NewMultihash(fullBytes []byte) *Multihash {
return &Multihash{FullBytes: fullBytes}
}
@ -71,6 +75,25 @@ func (m *Multihash) HashCode() MultihashCode {
return utils.HashCode(m.FullBytes[:4])
}
func (b *Multihash) UnmarshalJSON(data []byte) error {
decodedData, err := MultibaseDecodeString(string(data))
if err != nil {
return err
}
b.FullBytes = decodedData
return nil
}
func (b Multihash) MarshalJSON() ([]byte, error) {
url, err := b.ToBase64Url()
if err != nil {
return nil, err
}
return []byte(url), nil
}
func getEncoding(hash string) (multibase.Encoding, error) {
r, _ := utf8.DecodeRuneInString(hash)
enc := multibase.Encoding(r)