syncthing/scanner/blocks.go

84 lines
1.9 KiB
Go
Raw Normal View History

2014-07-13 00:45:33 +02:00
// Copyright (C) 2014 Jakob Borg and Contributors (see the CONTRIBUTORS file).
// All rights reserved. Use of this source code is governed by an MIT-style
// license that can be found in the LICENSE file.
2014-06-01 22:50:14 +02:00
package scanner
2014-03-02 23:58:14 +01:00
import (
"bytes"
"crypto/sha256"
"io"
2014-07-12 23:06:48 +02:00
"github.com/calmh/syncthing/protocol"
2014-03-02 23:58:14 +01:00
)
2014-05-15 05:26:55 +02:00
const StandardBlockSize = 128 * 1024
2014-03-02 23:58:14 +01:00
// Blocks returns the blockwise hash of the reader.
2014-07-12 23:06:48 +02:00
func Blocks(r io.Reader, blocksize int) ([]protocol.BlockInfo, error) {
var blocks []protocol.BlockInfo
2014-03-02 23:58:14 +01:00
var offset int64
for {
lr := &io.LimitedReader{R: r, N: int64(blocksize)}
hf := sha256.New()
n, err := io.Copy(hf, lr)
if err != nil {
return nil, err
}
if n == 0 {
break
}
2014-07-12 23:06:48 +02:00
b := protocol.BlockInfo{
2014-03-02 23:58:14 +01:00
Size: uint32(n),
2014-07-12 23:06:48 +02:00
Offset: offset,
2014-03-02 23:58:14 +01:00
Hash: hf.Sum(nil),
}
blocks = append(blocks, b)
offset += int64(n)
}
if len(blocks) == 0 {
// Empty file
2014-07-12 23:06:48 +02:00
blocks = append(blocks, protocol.BlockInfo{
2014-03-02 23:58:14 +01:00
Offset: 0,
Size: 0,
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},
})
}
return blocks, nil
}
// BlockDiff returns lists of common and missing (to transform src into tgt)
// blocks. Both block lists must have been created with the same block size.
2014-07-12 23:06:48 +02:00
func BlockDiff(src, tgt []protocol.BlockInfo) (have, need []protocol.BlockInfo) {
2014-03-02 23:58:14 +01:00
if len(tgt) == 0 && len(src) != 0 {
return nil, nil
}
2014-07-12 23:06:48 +02:00
// Set the Offset field on each target block
var offset int64
for i := range tgt {
tgt[i].Offset = offset
offset += int64(tgt[i].Size)
}
2014-03-02 23:58:14 +01:00
if len(tgt) != 0 && len(src) == 0 {
// Copy the entire file
return nil, tgt
}
for i := range tgt {
if i >= len(src) || bytes.Compare(tgt[i].Hash, src[i].Hash) != 0 {
// Copy differing block
need = append(need, tgt[i])
} else {
have = append(have, tgt[i])
}
}
return have, need
}