blockmap.go 1.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364
  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. )
  12. type BlockFinder struct {
  13. db *Lowlevel
  14. }
  15. func NewBlockFinder(db *Lowlevel) *BlockFinder {
  16. return &BlockFinder{
  17. db: db,
  18. }
  19. }
  20. func (f *BlockFinder) String() string {
  21. return fmt.Sprintf("BlockFinder@%p", f)
  22. }
  23. // Iterate takes an iterator function which iterates over all matching blocks
  24. // for the given hash. The iterator function has to return either true (if
  25. // they are happy with the block) or false to continue iterating for whatever
  26. // reason. The iterator finally returns the result, whether or not a
  27. // satisfying block was eventually found.
  28. func (f *BlockFinder) Iterate(folders []string, hash []byte, iterFn func(string, string, int32) bool) bool {
  29. t, err := f.db.newReadOnlyTransaction()
  30. if err != nil {
  31. return false
  32. }
  33. defer t.close()
  34. var key []byte
  35. for _, folder := range folders {
  36. key, err = f.db.keyer.GenerateBlockMapKey(key, []byte(folder), hash, nil)
  37. if err != nil {
  38. return false
  39. }
  40. iter, err := t.NewPrefixIterator(key)
  41. if err != nil {
  42. return false
  43. }
  44. for iter.Next() && iter.Error() == nil {
  45. file := string(f.db.keyer.NameFromBlockMapKey(iter.Key()))
  46. index := int32(binary.BigEndian.Uint32(iter.Value()))
  47. if iterFn(folder, osutil.NativeFilename(file), index) {
  48. iter.Release()
  49. return true
  50. }
  51. }
  52. iter.Release()
  53. }
  54. return false
  55. }