Skip to content

Commit

Permalink
Merge pull request #52 from muzzammilshahid/encode-decode-cbor
Browse files Browse the repository at this point in the history
Add functions to encode, decode CBOR
  • Loading branch information
muzzammilshahid authored Jul 8, 2024
2 parents ed1a96d + a8a886f commit f4eef82
Show file tree
Hide file tree
Showing 2 changed files with 39 additions and 0 deletions.
32 changes: 32 additions & 0 deletions serializers/cbor.go
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
package serializers

import (
"fmt"
"reflect"

"github.com/fxamacker/cbor/v2"
Expand Down Expand Up @@ -42,3 +43,34 @@ func (c *CBORSerializer) Deserialize(payload []byte) (messages.Message, error) {
func (c *CBORSerializer) Static() bool {
return false
}

func EncodeCBOR(args []any, kwargs map[string]any) ([]byte, int, error) {
var payload []any
payload = append(payload, args)
payload = append(payload, kwargs)
payloadData, err := cbor.Marshal(payload)
if err != nil {
return nil, 0, err
}

return payloadData, CBORSerializerValue, nil
}

func DecodeCBOR(data []byte) ([]any, map[string]any, error) {
var payload []any
if err := cborEncoder.Unmarshal(data, &payload); err != nil {
return nil, nil, fmt.Errorf("failed to unmarshal cbor payload: %w", err)
}

args, ok := payload[0].([]any)
if !ok {
return nil, nil, fmt.Errorf("invalid args type: %T", payload[0])
}

kwargs, ok := payload[1].(map[string]any)
if !ok {
return nil, nil, fmt.Errorf("invalid kwargs type: %T", payload[1])
}

return args, kwargs, nil
}
7 changes: 7 additions & 0 deletions serializers/helpers.go
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,13 @@ import (
"github.com/xconnio/wampproto-go/messages"
)

const (
JSONSerializerValue = 1
MsgPackSerializerValue = 2
CBORSerializerValue = 3
ProtobufSerializerValue = 16
)

func ToMessage(wampMsg []any) (messages.Message, error) {
messageType, _ := messages.AsInt64(wampMsg[0])
var msg messages.Message
Expand Down

0 comments on commit f4eef82

Please sign in to comment.