github.com/scottcagno/storage@v1.8.0/pkg/lsmt/trees/rbtree/rbtree-addons.go (about)

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