blockmap.go 1.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263
  1. // Copyright (C) 2014 The Syncthing Authors.
  2. //
  3. // This Source Code Form is subject to the terms of the Mozilla Public
  4. // License, v. 2.0. If a copy of the MPL was not distributed with this file,
  5. // You can obtain one at https://mozilla.org/MPL/2.0/.
  6. package db
  7. import (
  8. "encoding/binary"
  9. "fmt"
  10. "github.com/syncthing/syncthing/lib/osutil"
  11. "github.com/syndtr/goleveldb/leveldb/util"
  12. )
  13. var blockFinder *BlockFinder
  14. type BlockFinder struct {
  15. db *instance
  16. }
  17. func NewBlockFinder(db *Lowlevel) *BlockFinder {
  18. if blockFinder != nil {
  19. return blockFinder
  20. }
  21. return &BlockFinder{
  22. db: newInstance(db),
  23. }
  24. }
  25. func (f *BlockFinder) String() string {
  26. return fmt.Sprintf("BlockFinder@%p", f)
  27. }
  28. // Iterate takes an iterator function which iterates over all matching blocks
  29. // for the given hash. The iterator function has to return either true (if
  30. // they are happy with the block) or false to continue iterating for whatever
  31. // reason. The iterator finally returns the result, whether or not a
  32. // satisfying block was eventually found.
  33. func (f *BlockFinder) Iterate(folders []string, hash []byte, iterFn func(string, string, int32) bool) bool {
  34. t := f.db.newReadOnlyTransaction()
  35. defer t.close()
  36. var key []byte
  37. for _, folder := range folders {
  38. key = f.db.keyer.GenerateBlockMapKey(key, []byte(folder), hash, nil)
  39. iter := t.NewIterator(util.BytesPrefix(key), nil)
  40. for iter.Next() && iter.Error() == nil {
  41. file := string(f.db.keyer.NameFromBlockMapKey(iter.Key()))
  42. index := int32(binary.BigEndian.Uint32(iter.Value()))
  43. if iterFn(folder, osutil.NativeFilename(file), index) {
  44. iter.Release()
  45. return true
  46. }
  47. }
  48. iter.Release()
  49. }
  50. return false
  51. }