blocks.go 1.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667
  1. package main
  2. import (
  3. "bytes"
  4. "crypto/sha256"
  5. "io"
  6. )
  7. type BlockList []Block
  8. type Block struct {
  9. Offset uint64
  10. Length uint32
  11. Hash []byte
  12. }
  13. // Blocks returns the blockwise hash of the reader.
  14. func Blocks(r io.Reader, blocksize int) (BlockList, error) {
  15. var blocks BlockList
  16. var offset uint64
  17. for {
  18. lr := &io.LimitedReader{r, 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. Length: uint32(n),
  30. Hash: hf.Sum(nil),
  31. }
  32. blocks = append(blocks, b)
  33. offset += uint64(n)
  34. }
  35. return blocks, nil
  36. }
  37. // To returns the list of blocks necessary to transform src into dst.
  38. // Both block lists must have been created with the same block size.
  39. func (src BlockList) To(tgt BlockList) (have, need BlockList) {
  40. if len(tgt) == 0 && len(src) != 0 {
  41. return nil, nil
  42. }
  43. if len(tgt) != 0 && len(src) == 0 {
  44. // Copy the entire file
  45. return nil, tgt
  46. }
  47. for i := range tgt {
  48. if i >= len(src) || bytes.Compare(tgt[i].Hash, src[i].Hash) != 0 {
  49. // Copy differing block
  50. need = append(need, tgt[i])
  51. } else {
  52. have = append(have, tgt[i])
  53. }
  54. }
  55. return have, need
  56. }