github.com/scottcagno/storage@v1.8.0/pkg/lsmt/mtbl/rbtree-addons.go (about) 1 package mtbl 2 3 import ( 4 "container/list" 5 binaryStd "encoding/binary" 6 "github.com/scottcagno/storage/pkg/lsmt/binary" 7 8 "fmt" 9 "strconv" 10 ) 11 12 func IntToString(key int64) string { 13 return "i" + strconv.FormatInt(key, 10) 14 } 15 16 func StringToInt(key string) int64 { 17 if len(key) != 11 || key[0] != 'i' { 18 return -1 19 } 20 ikey, err := strconv.ParseInt(key[1:], 10, 0) 21 if err != nil { 22 return -1 23 } 24 return ikey 25 } 26 27 func IntToBytes(val int64) []byte { 28 buf := make([]byte, 1+binaryStd.MaxVarintLen64) 29 buf[0] = 'i' 30 _ = binaryStd.PutVarint(buf[1:], val) 31 return buf 32 } 33 34 func BytesToInt(val []byte) int64 { 35 if len(val) != 11 || val[0] != 'i' { 36 return -1 37 } 38 ival, n := binaryStd.Varint(val[1:]) 39 if ival == 0 && n <= 0 { 40 return -1 41 } 42 return ival 43 } 44 45 func (t *rbTree) ToList() (*list.List, error) { 46 if t.count < 1 { 47 return nil, fmt.Errorf("Error: there are not enough entrys in the tree\n") 48 } 49 li := list.New() 50 t.ascend(t.root, t.min(t.root).entry, func(e *binary.Entry) bool { 51 li.PushBack(e) 52 return true 53 }) 54 return li, nil 55 } 56 57 func (t *rbTree) FromList(li *list.List) error { 58 for e := li.Front(); e != nil; e = e.Next() { 59 ent, ok := e.Value.(*binary.Entry) 60 if !ok { 61 return fmt.Errorf("Error: cannot add to tree, element (%T) "+ 62 "does not implement the RBEntry interface\n", ent) 63 } 64 t.putInternal(ent) 65 } 66 return nil 67 }