go-hep.org/x/hep@v0.38.1/sio/block.go (about) 1 // Copyright ©2017 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 sio 6 7 import ( 8 "reflect" 9 ) 10 11 var ( 12 blockHeaderSize = uint32(reflect.TypeOf((*blockHeader)(nil)).Elem().Size()) 13 blockDataSize = uint32(reflect.TypeOf((*blockData)(nil)).Elem().Size()) 14 ) 15 16 // Block is the interface implemented by an object that can be 17 // stored to (and loaded from) an SIO stream. 18 type Block interface { 19 Codec 20 Versioner 21 22 Name() string 23 } 24 25 // blockHeader describes the on-disk block data (header part) 26 type blockHeader struct { 27 Len uint32 // length of this block 28 Typ uint32 // block marker 29 } 30 31 // blockData describes the on-disk block data (payload part) 32 type blockData struct { 33 Version uint32 // version of this block 34 NameLen uint32 // length of the block name 35 } 36 37 // genericBlock provides a generic, reflect-based Block implementation 38 type genericBlock struct { 39 rv reflect.Value 40 rt reflect.Type 41 version uint32 42 name string 43 } 44 45 func (blk *genericBlock) Name() string { 46 return blk.name 47 } 48 49 func (blk *genericBlock) VersionSio() uint32 { 50 return blk.version 51 } 52 53 func (blk *genericBlock) MarshalSio(w Writer) error { 54 return bwrite(w, blk.rv.Interface()) 55 } 56 57 func (blk *genericBlock) UnmarshalSio(r Reader) error { 58 return bread(r, blk.rv.Interface()) 59 } 60 61 // userBlock adapts a user-provided Codec implementation into a Block one. 62 type userBlock struct { 63 version uint32 64 name string 65 blk Codec 66 } 67 68 func (blk *userBlock) Name() string { 69 return blk.name 70 } 71 72 func (blk *userBlock) VersionSio() uint32 { 73 return blk.version 74 } 75 76 func (blk *userBlock) MarshalSio(w Writer) error { 77 return blk.blk.MarshalSio(w) 78 } 79 80 func (blk *userBlock) UnmarshalSio(r Reader) error { 81 return blk.blk.UnmarshalSio(r) 82 }