leveldb.go 1.7 KB

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