github.com/mysteriumnetwork/node@v0.0.0-20240516044423-365054f76801/communication/codec_bytes.go (about)

     1  /*
     2   * Copyright (C) 2017 The "MysteriumNetwork/node" Authors.
     3   *
     4   * This program is free software: you can redistribute it and/or modify
     5   * it under the terms of the GNU General Public License as published by
     6   * the Free Software Foundation, either version 3 of the License, or
     7   * (at your option) any later version.
     8   *
     9   * This program is distributed in the hope that it will be useful,
    10   * but WITHOUT ANY WARRANTY; without even the implied warranty of
    11   * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    12   * GNU General Public License for more details.
    13   *
    14   * You should have received a copy of the GNU General Public License
    15   * along with this program.  If not, see <http://www.gnu.org/licenses/>.
    16   */
    17  
    18  package communication
    19  
    20  import (
    21  	"reflect"
    22  
    23  	"github.com/pkg/errors"
    24  )
    25  
    26  // NewCodecBytes returns codec which:
    27  //   - supports only byte payloads
    28  //   - does not perform any fancy encoding/decoding on payloads
    29  func NewCodecBytes() *codecBytes {
    30  	return &codecBytes{}
    31  }
    32  
    33  type codecBytes struct{}
    34  
    35  func (codec *codecBytes) Pack(payloadPtr interface{}) ([]byte, error) {
    36  	if payloadPtr == nil {
    37  		return []byte{}, nil
    38  	}
    39  
    40  	switch payload := payloadPtr.(type) {
    41  	case []byte:
    42  		return payload, nil
    43  
    44  	case byte:
    45  		return []byte{payload}, nil
    46  
    47  	case string:
    48  		return []byte(payload), nil
    49  	}
    50  
    51  	return []byte{}, errors.Errorf("can't pack payload: %#v", payloadPtr)
    52  }
    53  
    54  func (codec *codecBytes) Unpack(data []byte, payloadPtr interface{}) error {
    55  	switch payload := payloadPtr.(type) {
    56  	case *[]byte:
    57  		*payload = data
    58  		return nil
    59  
    60  	default:
    61  		payloadValue := reflect.ValueOf(payloadPtr)
    62  		return errors.Errorf("can't unpack to payload: %s", payloadValue.Type().String())
    63  	}
    64  }