github.com/datastax/go-cassandra-native-protocol@v0.0.0-20220706104457-5e8aad05cf90/frame/convert.go (about)

     1  // Copyright 2020 DataStax
     2  //
     3  // Licensed under the Apache License, Version 2.0 (the "License");
     4  // you may not use this file except in compliance with the License.
     5  // You may obtain a copy of the License at
     6  //
     7  //      http://www.apache.org/licenses/LICENSE-2.0
     8  //
     9  // Unless required by applicable law or agreed to in writing, software
    10  // distributed under the License is distributed on an "AS IS" BASIS,
    11  // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    12  // See the License for the specific language governing permissions and
    13  // limitations under the License.
    14  
    15  package frame
    16  
    17  import (
    18  	"bytes"
    19  	"fmt"
    20  )
    21  
    22  func (c *codec) ConvertToRawFrame(frame *Frame) (*RawFrame, error) {
    23  	var body bytes.Buffer
    24  	if err := c.EncodeBody(frame.Header, frame.Body, &body); err != nil {
    25  		return nil, fmt.Errorf("cannot encode body: %w", err)
    26  	}
    27  	frame.Header.BodyLength = int32(body.Len())
    28  	return &RawFrame{
    29  		Header: frame.Header,
    30  		Body:   body.Bytes(),
    31  	}, nil
    32  }
    33  
    34  func (c *codec) ConvertFromRawFrame(frame *RawFrame) (*Frame, error) {
    35  	if body, err := c.DecodeBody(frame.Header, bytes.NewBuffer(frame.Body)); err != nil {
    36  		return nil, fmt.Errorf("cannot decode body: %w", err)
    37  	} else {
    38  		return &Frame{
    39  			Header: frame.Header,
    40  			Body:   body,
    41  		}, nil
    42  	}
    43  }