github.com/dashpay/godash@v0.0.0-20160726055534-e038a21e0e3d/database/internal/treap/mutable.go (about)

     1  // Copyright (c) 2015-2016 The btcsuite developers
     2  // Copyright (c) 2016 The Dash developers
     3  // Use of this source code is governed by an ISC
     4  // license that can be found in the LICENSE file.
     5  
     6  package treap
     7  
     8  import (
     9  	"bytes"
    10  	"math/rand"
    11  )
    12  
    13  // Mutable represents a treap data structure which is used to hold ordered
    14  // key/value pairs using a combination of binary search tree and heap semantics.
    15  // It is a self-organizing and randomized data structure that doesn't require
    16  // complex operations to maintain balance.  Search, insert, and delete
    17  // operations are all O(log n).
    18  type Mutable struct {
    19  	root  *treapNode
    20  	count int
    21  
    22  	// totalSize is the best estimate of the total size of of all data in
    23  	// the treap including the keys, values, and node sizes.
    24  	totalSize uint64
    25  }
    26  
    27  // Len returns the number of items stored in the treap.
    28  func (t *Mutable) Len() int {
    29  	return t.count
    30  }
    31  
    32  // Size returns a best estimate of the total number of bytes the treap is
    33  // consuming including all of the fields used to represent the nodes as well as
    34  // the size of the keys and values.  Shared values are not detected, so the
    35  // returned size assumes each value is pointing to different memory.
    36  func (t *Mutable) Size() uint64 {
    37  	return t.totalSize
    38  }
    39  
    40  // get returns the treap node that contains the passed key and its parent.  When
    41  // the found node is the root of the tree, the parent will be nil.  When the key
    42  // does not exist, both the node and the parent will be nil.
    43  func (t *Mutable) get(key []byte) (*treapNode, *treapNode) {
    44  	var parent *treapNode
    45  	for node := t.root; node != nil; {
    46  		// Traverse left or right depending on the result of the
    47  		// comparison.
    48  		compareResult := bytes.Compare(key, node.key)
    49  		if compareResult < 0 {
    50  			parent = node
    51  			node = node.left
    52  			continue
    53  		}
    54  		if compareResult > 0 {
    55  			parent = node
    56  			node = node.right
    57  			continue
    58  		}
    59  
    60  		// The key exists.
    61  		return node, parent
    62  	}
    63  
    64  	// A nil node was reached which means the key does not exist.
    65  	return nil, nil
    66  }
    67  
    68  // Has returns whether or not the passed key exists.
    69  func (t *Mutable) Has(key []byte) bool {
    70  	if node, _ := t.get(key); node != nil {
    71  		return true
    72  	}
    73  	return false
    74  }
    75  
    76  // Get returns the value for the passed key.  The function will return nil when
    77  // the key does not exist.
    78  func (t *Mutable) Get(key []byte) []byte {
    79  	if node, _ := t.get(key); node != nil {
    80  		return node.value
    81  	}
    82  	return nil
    83  }
    84  
    85  // relinkGrandparent relinks the node into the treap after it has been rotated
    86  // by changing the passed grandparent's left or right pointer, depending on
    87  // where the old parent was, to point at the passed node.  Otherwise, when there
    88  // is no grandparent, it means the node is now the root of the tree, so update
    89  // it accordingly.
    90  func (t *Mutable) relinkGrandparent(node, parent, grandparent *treapNode) {
    91  	// The node is now the root of the tree when there is no grandparent.
    92  	if grandparent == nil {
    93  		t.root = node
    94  		return
    95  	}
    96  
    97  	// Relink the grandparent's left or right pointer based on which side
    98  	// the old parent was.
    99  	if grandparent.left == parent {
   100  		grandparent.left = node
   101  	} else {
   102  		grandparent.right = node
   103  	}
   104  }
   105  
   106  // Put inserts the passed key/value pair.
   107  func (t *Mutable) Put(key, value []byte) {
   108  	// Use an empty byte slice for the value when none was provided.  This
   109  	// ultimately allows key existence to be determined from the value since
   110  	// an empty byte slice is distinguishable from nil.
   111  	if value == nil {
   112  		value = emptySlice
   113  	}
   114  
   115  	// The node is the root of the tree if there isn't already one.
   116  	if t.root == nil {
   117  		node := newTreapNode(key, value, rand.Int())
   118  		t.count = 1
   119  		t.totalSize = nodeSize(node)
   120  		t.root = node
   121  		return
   122  	}
   123  
   124  	// Find the binary tree insertion point and construct a list of parents
   125  	// while doing so.  When the key matches an entry already in the treap,
   126  	// just update its value and return.
   127  	var parents parentStack
   128  	var compareResult int
   129  	for node := t.root; node != nil; {
   130  		parents.Push(node)
   131  		compareResult = bytes.Compare(key, node.key)
   132  		if compareResult < 0 {
   133  			node = node.left
   134  			continue
   135  		}
   136  		if compareResult > 0 {
   137  			node = node.right
   138  			continue
   139  		}
   140  
   141  		// The key already exists, so update its value.
   142  		t.totalSize -= uint64(len(node.value))
   143  		t.totalSize += uint64(len(value))
   144  		node.value = value
   145  		return
   146  	}
   147  
   148  	// Link the new node into the binary tree in the correct position.
   149  	node := newTreapNode(key, value, rand.Int())
   150  	t.count++
   151  	t.totalSize += nodeSize(node)
   152  	parent := parents.At(0)
   153  	if compareResult < 0 {
   154  		parent.left = node
   155  	} else {
   156  		parent.right = node
   157  	}
   158  
   159  	// Perform any rotations needed to maintain the min-heap.
   160  	for parents.Len() > 0 {
   161  		// There is nothing left to do when the node's priority is
   162  		// greater than or equal to its parent's priority.
   163  		parent = parents.Pop()
   164  		if node.priority >= parent.priority {
   165  			break
   166  		}
   167  
   168  		// Perform a right rotation if the node is on the left side or
   169  		// a left rotation if the node is on the right side.
   170  		if parent.left == node {
   171  			node.right, parent.left = parent, node.right
   172  		} else {
   173  			node.left, parent.right = parent, node.left
   174  		}
   175  		t.relinkGrandparent(node, parent, parents.At(0))
   176  	}
   177  }
   178  
   179  // Delete removes the passed key if it exists.
   180  func (t *Mutable) Delete(key []byte) {
   181  	// Find the node for the key along with its parent.  There is nothing to
   182  	// do if the key does not exist.
   183  	node, parent := t.get(key)
   184  	if node == nil {
   185  		return
   186  	}
   187  
   188  	// When the only node in the tree is the root node and it is the one
   189  	// being deleted, there is nothing else to do besides removing it.
   190  	if parent == nil && node.left == nil && node.right == nil {
   191  		t.root = nil
   192  		t.count = 0
   193  		t.totalSize = 0
   194  		return
   195  	}
   196  
   197  	// Perform rotations to move the node to delete to a leaf position while
   198  	// maintaining the min-heap.
   199  	var isLeft bool
   200  	var child *treapNode
   201  	for node.left != nil || node.right != nil {
   202  		// Choose the child with the higher priority.
   203  		if node.left == nil {
   204  			child = node.right
   205  			isLeft = false
   206  		} else if node.right == nil {
   207  			child = node.left
   208  			isLeft = true
   209  		} else if node.left.priority >= node.right.priority {
   210  			child = node.left
   211  			isLeft = true
   212  		} else {
   213  			child = node.right
   214  			isLeft = false
   215  		}
   216  
   217  		// Rotate left or right depending on which side the child node
   218  		// is on.  This has the effect of moving the node to delete
   219  		// towards the bottom of the tree while maintaining the
   220  		// min-heap.
   221  		if isLeft {
   222  			child.right, node.left = node, child.right
   223  		} else {
   224  			child.left, node.right = node, child.left
   225  		}
   226  		t.relinkGrandparent(child, node, parent)
   227  
   228  		// The parent for the node to delete is now what was previously
   229  		// its child.
   230  		parent = child
   231  	}
   232  
   233  	// Delete the node, which is now a leaf node, by disconnecting it from
   234  	// its parent.
   235  	if parent.right == node {
   236  		parent.right = nil
   237  	} else {
   238  		parent.left = nil
   239  	}
   240  	t.count--
   241  	t.totalSize -= nodeSize(node)
   242  }
   243  
   244  // ForEach invokes the passed function with every key/value pair in the treap
   245  // in ascending order.
   246  func (t *Mutable) ForEach(fn func(k, v []byte) bool) {
   247  	// Add the root node and all children to the left of it to the list of
   248  	// nodes to traverse and loop until they, and all of their child nodes,
   249  	// have been traversed.
   250  	var parents parentStack
   251  	for node := t.root; node != nil; node = node.left {
   252  		parents.Push(node)
   253  	}
   254  	for parents.Len() > 0 {
   255  		node := parents.Pop()
   256  		if !fn(node.key, node.value) {
   257  			return
   258  		}
   259  
   260  		// Extend the nodes to traverse by all children to the left of
   261  		// the current node's right child.
   262  		for node := node.right; node != nil; node = node.left {
   263  			parents.Push(node)
   264  		}
   265  	}
   266  }
   267  
   268  // Reset efficiently removes all items in the treap.
   269  func (t *Mutable) Reset() {
   270  	t.count = 0
   271  	t.totalSize = 0
   272  	t.root = nil
   273  }
   274  
   275  // NewMutable returns a new empty mutable treap ready for use.  See the
   276  // documentation for the Mutable structure for more details.
   277  func NewMutable() *Mutable {
   278  	return &Mutable{}
   279  }