File: blockmap.go

package info (click to toggle)
syncthing 1.29.5~ds1-3
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 22,880 kB
  • sloc: javascript: 37,288; sh: 1,838; xml: 1,115; makefile: 66
file content (64 lines) | stat: -rw-r--r-- 1,651 bytes parent folder | download | duplicates (4)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
// Copyright (C) 2014 The Syncthing Authors.
//
// This Source Code Form is subject to the terms of the Mozilla Public
// License, v. 2.0. If a copy of the MPL was not distributed with this file,
// You can obtain one at https://mozilla.org/MPL/2.0/.

package db

import (
	"encoding/binary"
	"fmt"

	"github.com/syncthing/syncthing/lib/osutil"
)

type BlockFinder struct {
	db *Lowlevel
}

func NewBlockFinder(db *Lowlevel) *BlockFinder {
	return &BlockFinder{
		db: db,
	}
}

func (f *BlockFinder) String() string {
	return fmt.Sprintf("BlockFinder@%p", f)
}

// Iterate takes an iterator function which iterates over all matching blocks
// for the given hash. The iterator function has to return either true (if
// they are happy with the block) or false to continue iterating for whatever
// reason. The iterator finally returns the result, whether or not a
// satisfying block was eventually found.
func (f *BlockFinder) Iterate(folders []string, hash []byte, iterFn func(string, string, int32) bool) bool {
	t, err := f.db.newReadOnlyTransaction()
	if err != nil {
		return false
	}
	defer t.close()

	var key []byte
	for _, folder := range folders {
		key, err = f.db.keyer.GenerateBlockMapKey(key, []byte(folder), hash, nil)
		if err != nil {
			return false
		}
		iter, err := t.NewPrefixIterator(key)
		if err != nil {
			return false
		}

		for iter.Next() && iter.Error() == nil {
			file := string(f.db.keyer.NameFromBlockMapKey(iter.Key()))
			index := int32(binary.BigEndian.Uint32(iter.Value()))
			if iterFn(folder, osutil.NativeFilename(file), index) {
				iter.Release()
				return true
			}
		}
		iter.Release()
	}
	return false
}