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.

52 lines
1.1 KiB

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