You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

53 lines
1.2 KiB

7 years ago
  1. package needle
  2. import (
  3. . "github.com/chrislusf/seaweedfs/weed/storage/types"
  4. "github.com/google/btree"
  5. )
  6. //This map assumes mostly inserting increasing keys
  7. type BtreeMap struct {
  8. tree *btree.BTree
  9. }
  10. func NewBtreeMap() *BtreeMap {
  11. return &BtreeMap{
  12. tree: btree.New(32),
  13. }
  14. }
  15. func (cm *BtreeMap) Set(key NeedleId, offset Offset, size uint32) (oldOffset Offset, oldSize uint32) {
  16. found := cm.tree.ReplaceOrInsert(NeedleValue{key, offset, size})
  17. if found != nil {
  18. old := found.(NeedleValue)
  19. return old.Offset, old.Size
  20. }
  21. return
  22. }
  23. func (cm *BtreeMap) Delete(key NeedleId) (oldSize uint32) {
  24. found := cm.tree.Delete(NeedleValue{key, 0, 0})
  25. if found != nil {
  26. old := found.(NeedleValue)
  27. return old.Size
  28. }
  29. return
  30. }
  31. func (cm *BtreeMap) Get(key NeedleId) (*NeedleValue, bool) {
  32. found := cm.tree.Get(NeedleValue{key, 0, 0})
  33. if found != nil {
  34. old := found.(NeedleValue)
  35. return &old, true
  36. }
  37. return nil, false
  38. }
  39. // Visit visits all entries or stop if any error when visiting
  40. func (cm *BtreeMap) Visit(visit func(NeedleValue) error) (ret error) {
  41. cm.tree.Ascend(func(item btree.Item) bool {
  42. needle := item.(NeedleValue)
  43. ret = visit(needle)
  44. return ret == nil
  45. })
  46. return ret
  47. }