github.com/Cloud-Foundations/Dominator@v0.3.4/lib/objectcache/encoding.go (about)

     1  package objectcache
     2  
     3  import (
     4  	"encoding/binary"
     5  	"fmt"
     6  	"io"
     7  )
     8  
     9  func decode(reader io.Reader) (ObjectCache, error) {
    10  	var numObjects uint64
    11  	if err := binary.Read(reader, binary.BigEndian, &numObjects); err != nil {
    12  		return nil, err
    13  	}
    14  	objectCache := make(ObjectCache, numObjects)
    15  	for index := uint64(0); index < numObjects; index++ {
    16  		hash := &objectCache[index]
    17  		nRead, err := io.ReadFull(reader, (*hash)[:])
    18  		if err != nil {
    19  			return nil, err
    20  		}
    21  		if nRead != len(*hash) {
    22  			return nil, fmt.Errorf("read: %d, expected: %d", nRead, len(hash))
    23  		}
    24  	}
    25  	return objectCache, nil
    26  }
    27  
    28  func (objectCache ObjectCache) encode(writer io.Writer) error {
    29  	numObjects := uint64(len(objectCache))
    30  	if err := binary.Write(writer, binary.BigEndian, numObjects); err != nil {
    31  		return err
    32  	}
    33  	for _, hash := range objectCache {
    34  		nWritten, err := writer.Write(hash[:])
    35  		if err != nil {
    36  			return err
    37  		}
    38  		if nWritten != len(hash) {
    39  			return fmt.Errorf("wrote: %d, expected: %d", nWritten, len(hash))
    40  		}
    41  	}
    42  	return nil
    43  }