github.com/m3db/m3@v1.5.0/src/dbnode/digest/buffer.go (about)

     1  // Copyright (c) 2016 Uber Technologies, Inc.
     2  //
     3  // Permission is hereby granted, free of charge, to any person obtaining a copy
     4  // of this software and associated documentation files (the "Software"), to deal
     5  // in the Software without restriction, including without limitation the rights
     6  // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
     7  // copies of the Software, and to permit persons to whom the Software is
     8  // furnished to do so, subject to the following conditions:
     9  //
    10  // The above copyright notice and this permission notice shall be included in
    11  // all copies or substantial portions of the Software.
    12  //
    13  // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
    14  // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
    15  // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
    16  // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
    17  // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
    18  // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
    19  // THE SOFTWARE.
    20  
    21  package digest
    22  
    23  import (
    24  	"encoding/binary"
    25  	"os"
    26  )
    27  
    28  const (
    29  	// DigestLenBytes is the length of generated digests in bytes.
    30  	DigestLenBytes = 4
    31  )
    32  
    33  var (
    34  	// Endianness is little endian
    35  	endianness = binary.LittleEndian
    36  )
    37  
    38  // Buffer is a byte slice that facilitates digest reading and writing.
    39  type Buffer []byte
    40  
    41  // NewBuffer creates a new digest buffer.
    42  func NewBuffer() Buffer {
    43  	return make([]byte, DigestLenBytes)
    44  }
    45  
    46  // WriteDigest writes a digest to the buffer.
    47  func (b Buffer) WriteDigest(digest uint32) {
    48  	endianness.PutUint32(b, digest)
    49  }
    50  
    51  // WriteDigestToFile writes a digest to the file.
    52  func (b Buffer) WriteDigestToFile(fd *os.File, digest uint32) error {
    53  	b.WriteDigest(digest)
    54  	_, err := fd.Write(b)
    55  	return err
    56  }
    57  
    58  // ReadDigest reads the digest from the buffer.
    59  func (b Buffer) ReadDigest() uint32 {
    60  	return endianness.Uint32(b)
    61  }
    62  
    63  // ReadDigestFromFile reads the digest from the file.
    64  func (b Buffer) ReadDigestFromFile(fd *os.File) (uint32, error) {
    65  	_, err := fd.Read(b)
    66  	if err != nil {
    67  		return 0, err
    68  	}
    69  	return b.ReadDigest(), nil
    70  }
    71  
    72  // ToBuffer converts a byte slice to a digest buffer.
    73  func ToBuffer(buf []byte) Buffer {
    74  	return Buffer(buf[:DigestLenBytes])
    75  }