github.com/gitbundle/modules@v0.0.0-20231025071548-85b91c5c3b01/packages/hashed_buffer.go (about)

     1  // Copyright 2023 The GitBundle Inc. All rights reserved.
     2  // Copyright 2017 The Gitea Authors. All rights reserved.
     3  // Use of this source code is governed by a MIT-style
     4  // license that can be found in the LICENSE file.
     5  
     6  package packages
     7  
     8  import (
     9  	"io"
    10  
    11  	"github.com/gitbundle/modules/util/filebuffer"
    12  )
    13  
    14  // HashedSizeReader provide methods to read, sum hashes and a Size method
    15  type HashedSizeReader interface {
    16  	io.Reader
    17  	HashSummer
    18  	Size() int64
    19  }
    20  
    21  // HashedBuffer is buffer which calculates multiple checksums
    22  type HashedBuffer struct {
    23  	*filebuffer.FileBackedBuffer
    24  
    25  	hash *MultiHasher
    26  
    27  	combinedWriter io.Writer
    28  }
    29  
    30  // NewHashedBuffer creates a hashed buffer with a specific maximum memory size
    31  func NewHashedBuffer(maxMemorySize int) (*HashedBuffer, error) {
    32  	b, err := filebuffer.New(maxMemorySize)
    33  	if err != nil {
    34  		return nil, err
    35  	}
    36  
    37  	hash := NewMultiHasher()
    38  
    39  	combinedWriter := io.MultiWriter(b, hash)
    40  
    41  	return &HashedBuffer{
    42  		b,
    43  		hash,
    44  		combinedWriter,
    45  	}, nil
    46  }
    47  
    48  // CreateHashedBufferFromReader creates a hashed buffer and copies the provided reader data into it.
    49  func CreateHashedBufferFromReader(r io.Reader, maxMemorySize int) (*HashedBuffer, error) {
    50  	b, err := NewHashedBuffer(maxMemorySize)
    51  	if err != nil {
    52  		return nil, err
    53  	}
    54  
    55  	_, err = io.Copy(b, r)
    56  	if err != nil {
    57  		return nil, err
    58  	}
    59  
    60  	return b, nil
    61  }
    62  
    63  // Write implements io.Writer
    64  func (b *HashedBuffer) Write(p []byte) (int, error) {
    65  	return b.combinedWriter.Write(p)
    66  }
    67  
    68  // Sums gets the MD5, SHA1, SHA256 and SHA512 checksums of the data
    69  func (b *HashedBuffer) Sums() (hashMD5, hashSHA1, hashSHA256, hashSHA512 []byte) {
    70  	return b.hash.Sums()
    71  }