blocks.go 1.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475
  1. package main
  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. if len(blocks) == 0 {
  35. // Empty file
  36. blocks = append(blocks, Block{
  37. Offset: 0,
  38. Size: 0,
  39. Hash: []uint8{0xe3, 0xb0, 0xc4, 0x42, 0x98, 0xfc, 0x1c, 0x14, 0x9a, 0xfb, 0xf4, 0xc8, 0x99, 0x6f, 0xb9, 0x24, 0x27, 0xae, 0x41, 0xe4, 0x64, 0x9b, 0x93, 0x4c, 0xa4, 0x95, 0x99, 0x1b, 0x78, 0x52, 0xb8, 0x55},
  40. })
  41. }
  42. return blocks, nil
  43. }
  44. // BlockDiff returns lists of common and missing (to transform src into tgt)
  45. // blocks. Both block lists must have been created with the same block size.
  46. func BlockDiff(src, tgt []Block) (have, need []Block) {
  47. if len(tgt) == 0 && len(src) != 0 {
  48. return nil, nil
  49. }
  50. if len(tgt) != 0 && len(src) == 0 {
  51. // Copy the entire file
  52. return nil, tgt
  53. }
  54. for i := range tgt {
  55. if i >= len(src) || bytes.Compare(tgt[i].Hash, src[i].Hash) != 0 {
  56. // Copy differing block
  57. need = append(need, tgt[i])
  58. } else {
  59. have = append(have, tgt[i])
  60. }
  61. }
  62. return have, need
  63. }