2019-04-19 04:43:36 +00:00
|
|
|
package needle_map
|
2017-05-27 05:51:25 +00:00
|
|
|
|
|
|
|
import (
|
2018-07-08 09:28:04 +00:00
|
|
|
. "github.com/chrislusf/seaweedfs/weed/storage/types"
|
2018-07-22 00:39:10 +00:00
|
|
|
"github.com/google/btree"
|
2017-05-27 05:51:25 +00:00
|
|
|
)
|
|
|
|
|
|
|
|
//This map assumes mostly inserting increasing keys
|
|
|
|
type BtreeMap struct {
|
|
|
|
tree *btree.BTree
|
|
|
|
}
|
|
|
|
|
|
|
|
func NewBtreeMap() *BtreeMap {
|
|
|
|
return &BtreeMap{
|
|
|
|
tree: btree.New(32),
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2018-07-08 09:28:04 +00:00
|
|
|
func (cm *BtreeMap) Set(key NeedleId, offset Offset, size uint32) (oldOffset Offset, oldSize uint32) {
|
2017-05-27 05:51:25 +00:00
|
|
|
found := cm.tree.ReplaceOrInsert(NeedleValue{key, offset, size})
|
|
|
|
if found != nil {
|
|
|
|
old := found.(NeedleValue)
|
|
|
|
return old.Offset, old.Size
|
|
|
|
}
|
|
|
|
return
|
|
|
|
}
|
|
|
|
|
2018-07-08 09:28:04 +00:00
|
|
|
func (cm *BtreeMap) Delete(key NeedleId) (oldSize uint32) {
|
2019-04-09 02:40:56 +00:00
|
|
|
found := cm.tree.Delete(NeedleValue{key, Offset{}, 0})
|
2017-05-27 05:51:25 +00:00
|
|
|
if found != nil {
|
|
|
|
old := found.(NeedleValue)
|
|
|
|
return old.Size
|
|
|
|
}
|
|
|
|
return
|
|
|
|
}
|
2018-07-08 09:28:04 +00:00
|
|
|
func (cm *BtreeMap) Get(key NeedleId) (*NeedleValue, bool) {
|
2019-04-09 02:40:56 +00:00
|
|
|
found := cm.tree.Get(NeedleValue{key, Offset{}, 0})
|
2017-05-27 05:51:25 +00:00
|
|
|
if found != nil {
|
|
|
|
old := found.(NeedleValue)
|
|
|
|
return &old, true
|
|
|
|
}
|
|
|
|
return nil, false
|
|
|
|
}
|
|
|
|
|
|
|
|
// Visit visits all entries or stop if any error when visiting
|
2019-05-19 05:46:24 +00:00
|
|
|
func (cm *BtreeMap) AscendingVisit(visit func(NeedleValue) error) (ret error) {
|
2017-05-27 05:51:25 +00:00
|
|
|
cm.tree.Ascend(func(item btree.Item) bool {
|
|
|
|
needle := item.(NeedleValue)
|
|
|
|
ret = visit(needle)
|
|
|
|
return ret == nil
|
|
|
|
})
|
|
|
|
return ret
|
|
|
|
}
|