blocks.go 1.5 KB

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