blocks.go 1.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465
  1. package model
  2. import (
  3. "bytes"
  4. "crypto/sha256"
  5. "io"
  6. )
  7. type Block struct {
  8. Offset int64
  9. Size uint32
  10. Hash []byte
  11. }
  12. // Blocks returns the blockwise hash of the reader.
  13. func Blocks(r io.Reader, blocksize int) ([]Block, error) {
  14. var blocks []Block
  15. var offset int64
  16. for {
  17. lr := &io.LimitedReader{r, int64(blocksize)}
  18. hf := sha256.New()
  19. n, err := io.Copy(hf, lr)
  20. if err != nil {
  21. return nil, err
  22. }
  23. if n == 0 {
  24. break
  25. }
  26. b := Block{
  27. Offset: offset,
  28. Size: uint32(n),
  29. Hash: hf.Sum(nil),
  30. }
  31. blocks = append(blocks, b)
  32. offset += int64(n)
  33. }
  34. return blocks, nil
  35. }
  36. // BlockDiff returns lists of common and missing (to transform src into tgt)
  37. // blocks. Both block lists must have been created with the same block size.
  38. func BlockDiff(src, tgt []Block) (have, need []Block) {
  39. if len(tgt) == 0 && len(src) != 0 {
  40. return nil, nil
  41. }
  42. if len(tgt) != 0 && len(src) == 0 {
  43. // Copy the entire file
  44. return nil, tgt
  45. }
  46. for i := range tgt {
  47. if i >= len(src) || bytes.Compare(tgt[i].Hash, src[i].Hash) != 0 {
  48. // Copy differing block
  49. need = append(need, tgt[i])
  50. } else {
  51. have = append(have, tgt[i])
  52. }
  53. }
  54. return have, need
  55. }