leveldb.go 1.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485
  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. "bytes"
  9. "fmt"
  10. "github.com/syncthing/syncthing/lib/protocol"
  11. "github.com/syndtr/goleveldb/leveldb"
  12. "github.com/syndtr/goleveldb/leveldb/opt"
  13. )
  14. const (
  15. KeyTypeDevice = iota
  16. KeyTypeGlobal
  17. KeyTypeBlock
  18. KeyTypeDeviceStatistic
  19. KeyTypeFolderStatistic
  20. KeyTypeVirtualMtime
  21. KeyTypeFolderIdx
  22. KeyTypeDeviceIdx
  23. KeyTypeIndexID
  24. KeyTypeFolderMeta
  25. KeyTypeMiscData
  26. )
  27. func (l VersionList) String() string {
  28. var b bytes.Buffer
  29. var id protocol.DeviceID
  30. b.WriteString("{")
  31. for i, v := range l.Versions {
  32. if i > 0 {
  33. b.WriteString(", ")
  34. }
  35. copy(id[:], v.Device)
  36. fmt.Fprintf(&b, "{%v, %v}", v.Version, id)
  37. }
  38. b.WriteString("}")
  39. return b.String()
  40. }
  41. type fileList []protocol.FileInfo
  42. func (l fileList) Len() int {
  43. return len(l)
  44. }
  45. func (l fileList) Swap(a, b int) {
  46. l[a], l[b] = l[b], l[a]
  47. }
  48. func (l fileList) Less(a, b int) bool {
  49. return l[a].Name < l[b].Name
  50. }
  51. type dbReader interface {
  52. Get([]byte, *opt.ReadOptions) ([]byte, error)
  53. }
  54. // Flush batches to disk when they contain this many records.
  55. const batchFlushSize = 64
  56. func getFile(db dbReader, key []byte) (protocol.FileInfo, bool) {
  57. bs, err := db.Get(key, nil)
  58. if err == leveldb.ErrNotFound {
  59. return protocol.FileInfo{}, false
  60. }
  61. if err != nil {
  62. l.Debugln("surprise error:", err)
  63. return protocol.FileInfo{}, false
  64. }
  65. var f protocol.FileInfo
  66. err = f.Unmarshal(bs)
  67. if err != nil {
  68. l.Debugln("unmarshal error:", err)
  69. return protocol.FileInfo{}, false
  70. }
  71. return f, true
  72. }