//Cursor represents an iterator that can traverse over all key/value pairs in a tree in hash sorted order.
//Cursors can be obtained from a tree and are valid as long as the tree is valid.
//Keys and values returned from the cursor are only valid for the life of the transaction.
//Changing tree (before committing) while traversing with a cursor may cause it to be invalidated and return unexpected keys and/or values. You must reposition your cursor after mutating data.
// get Cursor which is used as an iterator that can traverse over all key/value pairs in a tree in hash sorted order.
func(t*Tree)Cursor()Cursor{
returnCursor{tree:t}
}
// First moves the cursor to the first item in the tree and returns its key and value. If the tree is empty then an error is returned. The returned key and value are only valid for the life of the tree.
func(c*Cursor)First()(k,v[]byte,errerror){
// the function is iterative and not recursive
returnc.next_internal(node(c.tree.root),false)
}
// Last moves the cursor to the last item in the tree and returns its key and value. If the tree is empty then an error is returned. The returned key and value are only valid for the life of the tree.
func(c*Cursor)Last()(k,v[]byte,errerror){
// the function is iterative and not recursive
returnc.next_internal(node(c.tree.root),true)
}
// this function will descend and reach the next or previous value
// Next moves the cursor to the next item in the tree and returns its key and value.If the tree is empty then an error is returned.If the cursor is at the end of the tree, then an error is returned. The returned key and value are only valid for the life of the tree.
func(c*Cursor)Next()(k,v[]byte,errerror){
try_again:
iflen(c.node_path)==0{
err=ErrNoMoreKeys
return
}
cur_node_index:=len(c.node_path)-1
if!c.left[cur_node_index]||c.node_path[cur_node_index].right==nil{// since we are a right node, we must back track one node
c.node_path=c.node_path[:cur_node_index]
c.left=c.left[:cur_node_index]
gototry_again
}
// we are here means we are on a left node, lets check the right node
// Prev moves the cursor to the prev item in the tree and returns its key and value.If the tree is empty then an error is returned.If the cursor is at the end of the tree, then an error is returned. The returned key and value are only valid for the life of the tree.
func(c*Cursor)Prev()(k,v[]byte,errerror){
try_again:
iflen(c.node_path)==0{
err=ErrNoMoreKeys
return
}
cur_node_index:=len(c.node_path)-1
ifc.left[cur_node_index]||c.node_path[cur_node_index].left==nil{// since we are a right node, we must back track one node
c.node_path=c.node_path[:cur_node_index]
c.left=c.left[:cur_node_index]
gototry_again
}
// we are here means we are on a right node, lets check the left node