github.com/insolar/vanilla@v0.0.0-20201023172447-248fdf805322/protokit/binary.go (about)

     1  // Copyright 2020 Insolar Network Ltd.
     2  // All rights reserved.
     3  // This material is licensed under the Insolar License version 1.0,
     4  // available at https://github.com/insolar/assured-ledger/blob/master/LICENSE.md.
     5  
     6  package protokit
     7  
     8  import (
     9  	"io"
    10  
    11  	"github.com/insolar/vanilla/throw"
    12  )
    13  
    14  func BinaryProtoSize(n int) int {
    15  	if n > 0 {
    16  		return n + 1
    17  	}
    18  	return n
    19  }
    20  
    21  func BinaryMarshalTo(b []byte, allowEmpty bool, marshalTo func([]byte) (int, error)) (int, error) {
    22  	if len(b) == 0 {
    23  		return marshalTo(nil)
    24  	}
    25  	b[0] = BinaryMarker
    26  	switch n, err := marshalTo(b[1:]); {
    27  	case err != nil:
    28  		return 0, err
    29  	case !allowEmpty && n == 0:
    30  		return 0, nil
    31  	default:
    32  		return n + 1, nil
    33  	}
    34  }
    35  
    36  func BinaryMarshalToSizedBuffer(b []byte, allowEmpty bool, marshalToSizedBuffer func([]byte) (int, error)) (int, error) {
    37  	switch n, err := marshalToSizedBuffer(b[1:]); {
    38  	case err != nil:
    39  		return 0, err
    40  	case !allowEmpty && n == 0:
    41  		return 0, nil
    42  	default:
    43  		n++
    44  		i := len(b) - n
    45  		if i < 0 {
    46  			return 0, io.ErrShortBuffer
    47  		}
    48  		b[i] = BinaryMarker
    49  		return n, nil
    50  	}
    51  }
    52  
    53  func BinaryUnmarshal(b []byte, unmarshal func([]byte) error) error {
    54  	if len(b) == 0 {
    55  		return unmarshal(nil)
    56  	}
    57  	if b[0] != BinaryMarker {
    58  		return throw.FailHere("expected binary marker")
    59  	}
    60  	return unmarshal(b[1:])
    61  }
    62  
    63  const ExplicitEmptyBinaryProtoSize = 1