go-hep.org/x/hep@v0.38.1/rio/block.go (about)

     1  // Copyright ©2015 The go-hep Authors. All rights reserved.
     2  // Use of this source code is governed by a BSD-style
     3  // license that can be found in the LICENSE file.
     4  
     5  package rio
     6  
     7  import (
     8  	"bytes"
     9  	"reflect"
    10  )
    11  
    12  // Block manages and desribes a block of data
    13  type Block struct {
    14  	raw rioBlock
    15  	typ reflect.Type
    16  }
    17  
    18  func newBlock(name string, version Version) Block {
    19  	block := Block{
    20  		raw: rioBlock{
    21  			Header: rioHeader{
    22  				Len:   0,
    23  				Frame: blkFrame,
    24  			},
    25  			Version: version,
    26  			Name:    name,
    27  		},
    28  	}
    29  
    30  	return block
    31  }
    32  
    33  // Name returns the name of this block
    34  func (blk *Block) Name() string {
    35  	return blk.raw.Name
    36  }
    37  
    38  // RioVersion returns the rio-binary version of the block
    39  func (blk *Block) RioVersion() Version {
    40  	return blk.raw.Version
    41  }
    42  
    43  // Write writes data to the Writer, in the rio format
    44  func (blk *Block) Write(data any) error {
    45  	var err error
    46  
    47  	buf := new(bytes.Buffer) // FIXME(sbinet): use a sync.Pool
    48  	enc := encoder{w: buf}
    49  	err = enc.Encode(data)
    50  	if err != nil {
    51  		return err
    52  	}
    53  
    54  	blk.raw.Data = buf.Bytes()
    55  	blk.raw.Header.Len = uint32(len(blk.raw.Data))
    56  	return nil
    57  }
    58  
    59  // Read reads data from the Reader, in the rio format
    60  func (blk *Block) Read(data any) error {
    61  	var err error
    62  	buf := bytes.NewReader(blk.raw.Data) // FIXME(sbinet): use a sync.Pool
    63  	dec := decoder{r: buf}
    64  	err = dec.Decode(data)
    65  	if err != nil {
    66  		return err
    67  	}
    68  	return err
    69  }