You can not select more than 25 topics Topics must start with a chinese character,a letter or number, can include dashes ('-') and can be up to 35 characters long.

hash.go 794 B

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354
  1. package io2
  2. import (
  3. "hash"
  4. "io"
  5. )
  6. type ReadHasher struct {
  7. hasher hash.Hash
  8. inner io.Reader
  9. }
  10. func NewReadHasher(h hash.Hash, r io.Reader) *ReadHasher {
  11. return &ReadHasher{
  12. hasher: h,
  13. inner: r,
  14. }
  15. }
  16. func (h *ReadHasher) Read(p []byte) (n int, err error) {
  17. n, err = h.inner.Read(p)
  18. if n > 0 {
  19. h.hasher.Write(p[:n])
  20. }
  21. return
  22. }
  23. func (h *ReadHasher) Sum() []byte {
  24. return h.hasher.Sum(nil)
  25. }
  26. type WriteHasher struct {
  27. hasher hash.Hash
  28. inner io.Writer
  29. }
  30. func NewWriteHasher(h hash.Hash, w io.Writer) *WriteHasher {
  31. return &WriteHasher{
  32. hasher: h,
  33. inner: w,
  34. }
  35. }
  36. func (h *WriteHasher) Write(p []byte) (n int, err error) {
  37. n, err = h.inner.Write(p)
  38. if n > 0 {
  39. h.hasher.Write(p[:n])
  40. }
  41. return
  42. }
  43. func (h *WriteHasher) Sum() []byte {
  44. return h.hasher.Sum(nil)
  45. }