github.com/keybase/client/go@v0.0.0-20240309051027-028f7c731f8b/msgpack/msgpack.go (about)

     1  // Copyright 2018 Keybase, Inc. All rights reserved. Use of
     2  // this source code is governed by the included BSD license.
     3  
     4  package msgpack
     5  
     6  import (
     7  	"fmt"
     8  
     9  	"github.com/keybase/client/go/kbcrypto"
    10  	"github.com/keybase/go-codec/codec"
    11  )
    12  
    13  func EncodeCanonical(src interface{}) (dst []byte, err error) {
    14  	ch := kbcrypto.CodecHandle()
    15  	ch.Canonical = true
    16  	err = codec.NewEncoderBytes(&dst, ch).Encode(src)
    17  	return dst, err
    18  }
    19  
    20  func Decode(dst interface{}, src []byte) (err error) {
    21  	ch := kbcrypto.CodecHandle()
    22  	return codec.NewDecoderBytes(src, ch).Decode(dst)
    23  }
    24  
    25  func Encode(src interface{}) (dst []byte, err error) {
    26  	ch := kbcrypto.CodecHandle()
    27  	err = codec.NewEncoderBytes(&dst, ch).Encode(src)
    28  	return dst, err
    29  }
    30  
    31  // Decode data into out, but make sure that all bytes in data are
    32  // used.
    33  func DecodeAll(data []byte, handle *codec.MsgpackHandle, out interface{}) error {
    34  	decoder := codec.NewDecoderBytes(data, handle)
    35  	err := decoder.Decode(out)
    36  	if err != nil {
    37  		return err
    38  	}
    39  
    40  	if decoder.NumBytesRead() != len(data) {
    41  		return fmt.Errorf("Did not consume entire buffer: %d byte(s) left", len(data)-decoder.NumBytesRead())
    42  	}
    43  	return nil
    44  }
    45  
    46  func IsEncodedMsgpackArray(data []byte) bool {
    47  	if len(data) == 0 {
    48  		return false
    49  	}
    50  	b := data[0]
    51  	return (b >= 0x90 && b <= 0x9f) || b == 0xdc || b == 0xdd
    52  }
    53  
    54  func IsJSONObject(data []byte) bool {
    55  	return len(data) > 0 && data[0] == '{'
    56  }