syncthing/lib/db/blockmap.go

64 lines
1.6 KiB
Go
Raw Normal View History

2014-11-16 20:13:20 +00:00
// Copyright (C) 2014 The Syncthing Authors.
2014-10-06 20:57:33 +00:00
//
2015-03-07 20:36:35 +00:00
// 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/.
2014-10-06 20:57:33 +00:00
package db
2014-10-06 20:57:33 +00:00
import (
"encoding/binary"
"fmt"
2014-10-06 20:57:33 +00:00
2015-08-06 09:29:25 +00:00
"github.com/syncthing/syncthing/lib/osutil"
2014-10-06 20:57:33 +00:00
"github.com/syndtr/goleveldb/leveldb/util"
)
var blockFinder *BlockFinder
type BlockFinder struct {
db *instance
2014-10-06 20:57:33 +00:00
}
func NewBlockFinder(db *Lowlevel) *BlockFinder {
2014-10-06 20:57:33 +00:00
if blockFinder != nil {
return blockFinder
}
return &BlockFinder{
db: newInstance(db),
2014-10-06 20:57:33 +00:00
}
}
func (f *BlockFinder) String() string {
return fmt.Sprintf("BlockFinder@%p", f)
2014-10-06 20:57:33 +00:00
}
2015-04-28 20:32:10 +00:00
// 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.
2015-09-04 10:01:00 +00:00
func (f *BlockFinder) Iterate(folders []string, hash []byte, iterFn func(string, string, int32) bool) bool {
t := f.db.newReadOnlyTransaction()
defer t.close()
var key []byte
2014-10-06 20:57:33 +00:00
for _, folder := range folders {
key = f.db.keyer.GenerateBlockMapKey(key, []byte(folder), hash, nil)
iter := t.NewIterator(util.BytesPrefix(key), nil)
2014-10-06 20:57:33 +00:00
for iter.Next() && iter.Error() == nil {
file := string(f.db.keyer.NameFromBlockMapKey(iter.Key()))
index := int32(binary.BigEndian.Uint32(iter.Value()))
2014-11-05 23:41:51 +00:00
if iterFn(folder, osutil.NativeFilename(file), index) {
iter.Release()
2014-10-06 20:57:33 +00:00
return true
}
}
iter.Release()
2014-10-06 20:57:33 +00:00
}
return false
}