github.com/mutagen-io/mutagen@v0.18.0-rc1/pkg/stream/hashed_writer.go (about) 1 package stream 2 3 import ( 4 "hash" 5 "io" 6 ) 7 8 // hashedWriter is the io.Writer implementation underlying NewHashedWriter. 9 type hashedWriter struct { 10 // writer is the underlying writer. 11 writer io.Writer 12 // hasher is the associated hash function. 13 hasher hash.Hash 14 } 15 16 // NewHashedWriter creates a new io.Writer that attaches a hash function to an 17 // existing writer, ensuring that the hash processes all bytes that are 18 // successfully written to the associated writer. 19 func NewHashedWriter(writer io.Writer, hasher hash.Hash) io.Writer { 20 return &hashedWriter{writer, hasher} 21 } 22 23 // Write implements io.Writer.Write. 24 func (w *hashedWriter) Write(data []byte) (int, error) { 25 // Write to the underlying writer. 26 n, err := w.writer.Write(data) 27 28 // Write the corresponding bytes to the hasher. This write can't fail, so we 29 // can safely assume that all provided bytes are processed. 30 w.hasher.Write(data[:n]) 31 32 // Done. 33 return n, err 34 }