htree.go 5.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244
  1. /*
  2. * EliasDB
  3. *
  4. * Copyright 2016 Matthias Ladkau. All rights reserved.
  5. *
  6. * This Source Code Form is subject to the terms of the Mozilla Public
  7. * License, v. 2.0. If a copy of the MPL was not distributed with this
  8. * file, You can obtain one at http://mozilla.org/MPL/2.0/.
  9. */
  10. /*
  11. Package hash provides a HTree implementation to provide key-value storage functionality
  12. for a StorageManager.
  13. The HTree provides a persistent hashtable. Storing values in buckets on
  14. pages as the tree gorws. It is not possible to store nil values. Storing a nil value
  15. is equivalent to removing a key.
  16. As the tree grows each tree level contains pages with links to underlying pages.
  17. The last link is always to a bucket. The default tree has 4 levels each with
  18. 256 possible children. A hash code for the tree has 32 bits = 4 levels * 8 bit.
  19. Hash buckets are on the lowest level of the tree and contain actual keys and
  20. values. The object stores multiple keys and values if there are hash collisions.
  21. In a sparsely populated tree buckets can also be found on the upper levels.
  22. Iterator
  23. Entries in the HTree can be iterated by using an HTreeIterator. The HTree may
  24. change behind the iterator's back. The iterator will try to cope with best
  25. effort and only report an error as a last resort.
  26. Hash function
  27. The HTree uses an implementation of Austin Appleby's MurmurHash3 (32bit) function
  28. as hash function.
  29. Reference implementation: http://code.google.com/p/smhasher/wiki/MurmurHash3
  30. */
  31. package hash
  32. import (
  33. "fmt"
  34. "sync"
  35. "devt.de/krotik/eliasdb/storage"
  36. )
  37. /*
  38. MaxTreeDepth is the maximum number of non-leaf levels in the tree (i.e. the complete tree has
  39. a total of MAX_DEPTH+1 levels)
  40. */
  41. const MaxTreeDepth = 3
  42. /*
  43. PageLevelBits is the number of significant bits per page level
  44. */
  45. const PageLevelBits = 8
  46. /*
  47. MaxPageChildren is the maximum of children per page - (stored in PageLevelBits bits)
  48. */
  49. const MaxPageChildren = 256
  50. /*
  51. MaxBucketElements is the maximum umber of elements a bucket can contain before it
  52. is converted into a page except leaf buckets which grow indefinitely
  53. */
  54. const MaxBucketElements = 8
  55. /*
  56. HTree data structure
  57. */
  58. type HTree struct {
  59. Root *htreePage // Root page of the HTree
  60. mutex *sync.Mutex // Mutex to protect tree operations
  61. }
  62. /*
  63. htreeNode data structure - this object models the
  64. HTree storage structure on disk
  65. */
  66. type htreeNode struct {
  67. tree *HTree // Reference to the HTree which owns this node (not persisted)
  68. loc uint64 // Storage location of this page (not persisted)
  69. sm storage.Manager // StorageManager instance which stores the tree data (not persisted)
  70. Depth byte // Depth of this node
  71. Children []uint64 // Storage locations of children (only used for pages)
  72. Keys [][]byte // Stored keys (only used for buckets)
  73. Values []interface{} // Stored values (only used for buckets)
  74. BucketSize byte // Bucket size (only used for buckets)
  75. }
  76. /*
  77. Fetch a HTree node from the storage.
  78. */
  79. func (n *htreeNode) fetchNode(loc uint64) (*htreeNode, error) {
  80. var node *htreeNode
  81. if obj, _ := n.sm.FetchCached(loc); obj == nil {
  82. var res htreeNode
  83. if err := n.sm.Fetch(loc, &res); err != nil {
  84. return nil, err
  85. }
  86. node = &res
  87. } else {
  88. node = obj.(*htreeNode)
  89. }
  90. return node, nil
  91. }
  92. /*
  93. NewHTree creates a new HTree.
  94. */
  95. func NewHTree(sm storage.Manager) (*HTree, error) {
  96. tree := &HTree{}
  97. // Protect tree creation
  98. cm := &sync.Mutex{}
  99. cm.Lock()
  100. defer cm.Unlock()
  101. tree.Root = newHTreePage(tree, 0)
  102. loc, err := sm.Insert(tree.Root.htreeNode)
  103. if err != nil {
  104. return nil, err
  105. }
  106. tree.Root.loc = loc
  107. tree.Root.sm = sm
  108. tree.mutex = &sync.Mutex{}
  109. return tree, nil
  110. }
  111. /*
  112. LoadHTree fetches a HTree from storage
  113. */
  114. func LoadHTree(sm storage.Manager, loc uint64) (*HTree, error) {
  115. var tree *HTree
  116. // Protect tree creation
  117. cm := &sync.Mutex{}
  118. cm.Lock()
  119. defer cm.Unlock()
  120. if obj, _ := sm.FetchCached(loc); obj == nil {
  121. var res htreeNode
  122. if err := sm.Fetch(loc, &res); err != nil {
  123. return nil, err
  124. }
  125. tree = &HTree{&htreePage{&res}, nil}
  126. } else {
  127. tree = &HTree{&htreePage{obj.(*htreeNode)}, nil}
  128. }
  129. tree.Root.loc = loc
  130. tree.Root.sm = sm
  131. tree.mutex = &sync.Mutex{}
  132. return tree, nil
  133. }
  134. /*
  135. Location returns the HTree location on disk.
  136. */
  137. func (t *HTree) Location() uint64 {
  138. return t.Root.loc
  139. }
  140. /*
  141. Get gets a value for a given key.
  142. */
  143. func (t *HTree) Get(key []byte) (interface{}, error) {
  144. t.mutex.Lock()
  145. defer t.mutex.Unlock()
  146. res, _, err := t.Root.Get(key)
  147. return res, err
  148. }
  149. /*
  150. GetValueAndLocation returns the value and the storage location for a given key.
  151. */
  152. func (t *HTree) GetValueAndLocation(key []byte) (interface{}, uint64, error) {
  153. t.mutex.Lock()
  154. defer t.mutex.Unlock()
  155. res, bucket, err := t.Root.Get(key)
  156. if bucket != nil {
  157. return res, bucket.loc, err
  158. }
  159. return res, 0, err
  160. }
  161. /*
  162. Exists checks if an element exists.
  163. */
  164. func (t *HTree) Exists(key []byte) (bool, error) {
  165. t.mutex.Lock()
  166. defer t.mutex.Unlock()
  167. return t.Root.Exists(key)
  168. }
  169. /*
  170. Put adds or updates a new key / value pair.
  171. */
  172. func (t *HTree) Put(key []byte, value interface{}) (interface{}, error) {
  173. t.mutex.Lock()
  174. defer t.mutex.Unlock()
  175. return t.Root.Put(key, value)
  176. }
  177. /*
  178. Remove removes a key / value pair.
  179. */
  180. func (t *HTree) Remove(key []byte) (interface{}, error) {
  181. t.mutex.Lock()
  182. defer t.mutex.Unlock()
  183. return t.Root.Remove(key)
  184. }
  185. /*
  186. String returns a string representation of this tree.
  187. */
  188. func (t *HTree) String() string {
  189. t.mutex.Lock()
  190. defer t.mutex.Unlock()
  191. return fmt.Sprintf("HTree: %v (%v)\n%v", t.Root.sm.Name(), t.Root.loc, t.Root.String())
  192. }