gtsocial-umbx

Unnamed repository; edit this file 'description' to name the repository.
Log | Files | Refs | README | LICENSE

hashenc.go (1357B)


      1 package hashenc
      2 
      3 import (
      4 	"hash"
      5 
      6 	"codeberg.org/gruf/go-bytes"
      7 )
      8 
      9 // HashEncoder defines an interface for calculating encoded hash sums of binary data
     10 type HashEncoder interface {
     11 	// EncodeSum calculates the hash sum of src and encodes (at most) Size() into dst
     12 	EncodeSum(dst []byte, src []byte)
     13 
     14 	// EncodedSum calculates the encoded hash sum of src and returns data in a newly allocated bytes.Bytes
     15 	EncodedSum(src []byte) bytes.Bytes
     16 
     17 	// Size returns the expected length of encoded hashes
     18 	Size() int
     19 }
     20 
     21 // New returns a new HashEncoder instance based on supplied hash.Hash and Encoder supplying functions.
     22 func New(hash hash.Hash, enc Encoder) HashEncoder {
     23 	hashSize := hash.Size()
     24 	return &henc{
     25 		hash: hash,
     26 		hbuf: make([]byte, hashSize),
     27 		enc:  enc,
     28 		size: enc.EncodedLen(hashSize),
     29 	}
     30 }
     31 
     32 // henc is the HashEncoder implementation.
     33 type henc struct {
     34 	hash hash.Hash
     35 	hbuf []byte
     36 	enc  Encoder
     37 	size int
     38 }
     39 
     40 func (henc *henc) EncodeSum(dst []byte, src []byte) {
     41 	// Hash supplied bytes
     42 	henc.hash.Reset()
     43 	henc.hash.Write(src)
     44 	henc.hbuf = henc.hash.Sum(henc.hbuf[:0])
     45 
     46 	// Encode the hashsum and return a copy
     47 	henc.enc.Encode(dst, henc.hbuf)
     48 }
     49 
     50 func (henc *henc) EncodedSum(src []byte) bytes.Bytes {
     51 	dst := make([]byte, henc.size)
     52 	henc.EncodeSum(dst, src)
     53 	return bytes.ToBytes(dst)
     54 }
     55 
     56 func (henc *henc) Size() int {
     57 	return henc.size
     58 }