bucket.go 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748
  1. package bolt
  2. import (
  3. "bytes"
  4. "fmt"
  5. "unsafe"
  6. )
  7. const (
  8. // MaxKeySize is the maximum length of a key, in bytes.
  9. MaxKeySize = 32768
  10. // MaxValueSize is the maximum length of a value, in bytes.
  11. MaxValueSize = (1 << 31) - 2
  12. )
  13. const (
  14. maxUint = ^uint(0)
  15. minUint = 0
  16. maxInt = int(^uint(0) >> 1)
  17. minInt = -maxInt - 1
  18. )
  19. const bucketHeaderSize = int(unsafe.Sizeof(bucket{}))
  20. const (
  21. minFillPercent = 0.1
  22. maxFillPercent = 1.0
  23. )
  24. // DefaultFillPercent is the percentage that split pages are filled.
  25. // This value can be changed by setting Bucket.FillPercent.
  26. const DefaultFillPercent = 0.5
  27. // Bucket represents a collection of key/value pairs inside the database.
  28. type Bucket struct {
  29. *bucket
  30. tx *Tx // the associated transaction
  31. buckets map[string]*Bucket // subbucket cache
  32. page *page // inline page reference
  33. rootNode *node // materialized node for the root page.
  34. nodes map[pgid]*node // node cache
  35. // Sets the threshold for filling nodes when they split. By default,
  36. // the bucket will fill to 50% but it can be useful to increase this
  37. // amount if you know that your write workloads are mostly append-only.
  38. //
  39. // This is non-persisted across transactions so it must be set in every Tx.
  40. FillPercent float64
  41. }
  42. // bucket represents the on-file representation of a bucket.
  43. // This is stored as the "value" of a bucket key. If the bucket is small enough,
  44. // then its root page can be stored inline in the "value", after the bucket
  45. // header. In the case of inline buckets, the "root" will be 0.
  46. type bucket struct {
  47. root pgid // page id of the bucket's root-level page
  48. sequence uint64 // monotonically incrementing, used by NextSequence()
  49. }
  50. // newBucket returns a new bucket associated with a transaction.
  51. func newBucket(tx *Tx) Bucket {
  52. var b = Bucket{tx: tx, FillPercent: DefaultFillPercent}
  53. if tx.writable {
  54. b.buckets = make(map[string]*Bucket)
  55. b.nodes = make(map[pgid]*node)
  56. }
  57. return b
  58. }
  59. // Tx returns the tx of the bucket.
  60. func (b *Bucket) Tx() *Tx {
  61. return b.tx
  62. }
  63. // Root returns the root of the bucket.
  64. func (b *Bucket) Root() pgid {
  65. return b.root
  66. }
  67. // Writable returns whether the bucket is writable.
  68. func (b *Bucket) Writable() bool {
  69. return b.tx.writable
  70. }
  71. // Cursor creates a cursor associated with the bucket.
  72. // The cursor is only valid as long as the transaction is open.
  73. // Do not use a cursor after the transaction is closed.
  74. func (b *Bucket) Cursor() *Cursor {
  75. // Update transaction statistics.
  76. b.tx.stats.CursorCount++
  77. // Allocate and return a cursor.
  78. return &Cursor{
  79. bucket: b,
  80. stack: make([]elemRef, 0),
  81. }
  82. }
  83. // Bucket retrieves a nested bucket by name.
  84. // Returns nil if the bucket does not exist.
  85. // The bucket instance is only valid for the lifetime of the transaction.
  86. func (b *Bucket) Bucket(name []byte) *Bucket {
  87. if b.buckets != nil {
  88. if child := b.buckets[string(name)]; child != nil {
  89. return child
  90. }
  91. }
  92. // Move cursor to key.
  93. c := b.Cursor()
  94. k, v, flags := c.seek(name)
  95. // Return nil if the key doesn't exist or it is not a bucket.
  96. if !bytes.Equal(name, k) || (flags&bucketLeafFlag) == 0 {
  97. return nil
  98. }
  99. // Otherwise create a bucket and cache it.
  100. var child = b.openBucket(v)
  101. if b.buckets != nil {
  102. b.buckets[string(name)] = child
  103. }
  104. return child
  105. }
  106. // Helper method that re-interprets a sub-bucket value
  107. // from a parent into a Bucket
  108. func (b *Bucket) openBucket(value []byte) *Bucket {
  109. var child = newBucket(b.tx)
  110. // If this is a writable transaction then we need to copy the bucket entry.
  111. // Read-only transactions can point directly at the mmap entry.
  112. if b.tx.writable {
  113. child.bucket = &bucket{}
  114. *child.bucket = *(*bucket)(unsafe.Pointer(&value[0]))
  115. } else {
  116. child.bucket = (*bucket)(unsafe.Pointer(&value[0]))
  117. }
  118. // Save a reference to the inline page if the bucket is inline.
  119. if child.root == 0 {
  120. child.page = (*page)(unsafe.Pointer(&value[bucketHeaderSize]))
  121. }
  122. return &child
  123. }
  124. // CreateBucket creates a new bucket at the given key and returns the new bucket.
  125. // Returns an error if the key already exists, if the bucket name is blank, or if the bucket name is too long.
  126. // The bucket instance is only valid for the lifetime of the transaction.
  127. func (b *Bucket) CreateBucket(key []byte) (*Bucket, error) {
  128. if b.tx.db == nil {
  129. return nil, ErrTxClosed
  130. } else if !b.tx.writable {
  131. return nil, ErrTxNotWritable
  132. } else if len(key) == 0 {
  133. return nil, ErrBucketNameRequired
  134. }
  135. // Move cursor to correct position.
  136. c := b.Cursor()
  137. k, _, flags := c.seek(key)
  138. // Return an error if there is an existing key.
  139. if bytes.Equal(key, k) {
  140. if (flags & bucketLeafFlag) != 0 {
  141. return nil, ErrBucketExists
  142. } else {
  143. return nil, ErrIncompatibleValue
  144. }
  145. }
  146. // Create empty, inline bucket.
  147. var bucket = Bucket{
  148. bucket: &bucket{},
  149. rootNode: &node{isLeaf: true},
  150. FillPercent: DefaultFillPercent,
  151. }
  152. var value = bucket.write()
  153. // Insert into node.
  154. key = cloneBytes(key)
  155. c.node().put(key, key, value, 0, bucketLeafFlag)
  156. // Since subbuckets are not allowed on inline buckets, we need to
  157. // dereference the inline page, if it exists. This will cause the bucket
  158. // to be treated as a regular, non-inline bucket for the rest of the tx.
  159. b.page = nil
  160. return b.Bucket(key), nil
  161. }
  162. // CreateBucketIfNotExists creates a new bucket if it doesn't already exist and returns a reference to it.
  163. // Returns an error if the bucket name is blank, or if the bucket name is too long.
  164. // The bucket instance is only valid for the lifetime of the transaction.
  165. func (b *Bucket) CreateBucketIfNotExists(key []byte) (*Bucket, error) {
  166. child, err := b.CreateBucket(key)
  167. if err == ErrBucketExists {
  168. return b.Bucket(key), nil
  169. } else if err != nil {
  170. return nil, err
  171. }
  172. return child, nil
  173. }
  174. // DeleteBucket deletes a bucket at the given key.
  175. // Returns an error if the bucket does not exists, or if the key represents a non-bucket value.
  176. func (b *Bucket) DeleteBucket(key []byte) error {
  177. if b.tx.db == nil {
  178. return ErrTxClosed
  179. } else if !b.Writable() {
  180. return ErrTxNotWritable
  181. }
  182. // Move cursor to correct position.
  183. c := b.Cursor()
  184. k, _, flags := c.seek(key)
  185. // Return an error if bucket doesn't exist or is not a bucket.
  186. if !bytes.Equal(key, k) {
  187. return ErrBucketNotFound
  188. } else if (flags & bucketLeafFlag) == 0 {
  189. return ErrIncompatibleValue
  190. }
  191. // Recursively delete all child buckets.
  192. child := b.Bucket(key)
  193. err := child.ForEach(func(k, v []byte) error {
  194. if v == nil {
  195. if err := child.DeleteBucket(k); err != nil {
  196. return fmt.Errorf("delete bucket: %s", err)
  197. }
  198. }
  199. return nil
  200. })
  201. if err != nil {
  202. return err
  203. }
  204. // Remove cached copy.
  205. delete(b.buckets, string(key))
  206. // Release all bucket pages to freelist.
  207. child.nodes = nil
  208. child.rootNode = nil
  209. child.free()
  210. // Delete the node if we have a matching key.
  211. c.node().del(key)
  212. return nil
  213. }
  214. // Get retrieves the value for a key in the bucket.
  215. // Returns a nil value if the key does not exist or if the key is a nested bucket.
  216. // The returned value is only valid for the life of the transaction.
  217. func (b *Bucket) Get(key []byte) []byte {
  218. k, v, flags := b.Cursor().seek(key)
  219. // Return nil if this is a bucket.
  220. if (flags & bucketLeafFlag) != 0 {
  221. return nil
  222. }
  223. // If our target node isn't the same key as what's passed in then return nil.
  224. if !bytes.Equal(key, k) {
  225. return nil
  226. }
  227. return v
  228. }
  229. // Put sets the value for a key in the bucket.
  230. // If the key exist then its previous value will be overwritten.
  231. // Supplied value must remain valid for the life of the transaction.
  232. // Returns an error if the bucket was created from a read-only transaction, if the key is blank, if the key is too large, or if the value is too large.
  233. func (b *Bucket) Put(key []byte, value []byte) error {
  234. if b.tx.db == nil {
  235. return ErrTxClosed
  236. } else if !b.Writable() {
  237. return ErrTxNotWritable
  238. } else if len(key) == 0 {
  239. return ErrKeyRequired
  240. } else if len(key) > MaxKeySize {
  241. return ErrKeyTooLarge
  242. } else if int64(len(value)) > MaxValueSize {
  243. return ErrValueTooLarge
  244. }
  245. // Move cursor to correct position.
  246. c := b.Cursor()
  247. k, _, flags := c.seek(key)
  248. // Return an error if there is an existing key with a bucket value.
  249. if bytes.Equal(key, k) && (flags&bucketLeafFlag) != 0 {
  250. return ErrIncompatibleValue
  251. }
  252. // Insert into node.
  253. key = cloneBytes(key)
  254. c.node().put(key, key, value, 0, 0)
  255. return nil
  256. }
  257. // Delete removes a key from the bucket.
  258. // If the key does not exist then nothing is done and a nil error is returned.
  259. // Returns an error if the bucket was created from a read-only transaction.
  260. func (b *Bucket) Delete(key []byte) error {
  261. if b.tx.db == nil {
  262. return ErrTxClosed
  263. } else if !b.Writable() {
  264. return ErrTxNotWritable
  265. }
  266. // Move cursor to correct position.
  267. c := b.Cursor()
  268. _, _, flags := c.seek(key)
  269. // Return an error if there is already existing bucket value.
  270. if (flags & bucketLeafFlag) != 0 {
  271. return ErrIncompatibleValue
  272. }
  273. // Delete the node if we have a matching key.
  274. c.node().del(key)
  275. return nil
  276. }
  277. // NextSequence returns an autoincrementing integer for the bucket.
  278. func (b *Bucket) NextSequence() (uint64, error) {
  279. if b.tx.db == nil {
  280. return 0, ErrTxClosed
  281. } else if !b.Writable() {
  282. return 0, ErrTxNotWritable
  283. }
  284. // Materialize the root node if it hasn't been already so that the
  285. // bucket will be saved during commit.
  286. if b.rootNode == nil {
  287. _ = b.node(b.root, nil)
  288. }
  289. // Increment and return the sequence.
  290. b.bucket.sequence++
  291. return b.bucket.sequence, nil
  292. }
  293. // ForEach executes a function for each key/value pair in a bucket.
  294. // If the provided function returns an error then the iteration is stopped and
  295. // the error is returned to the caller. The provided function must not modify
  296. // the bucket; this will result in undefined behavior.
  297. func (b *Bucket) ForEach(fn func(k, v []byte) error) error {
  298. if b.tx.db == nil {
  299. return ErrTxClosed
  300. }
  301. c := b.Cursor()
  302. for k, v := c.First(); k != nil; k, v = c.Next() {
  303. if err := fn(k, v); err != nil {
  304. return err
  305. }
  306. }
  307. return nil
  308. }
  309. // Stat returns stats on a bucket.
  310. func (b *Bucket) Stats() BucketStats {
  311. var s, subStats BucketStats
  312. pageSize := b.tx.db.pageSize
  313. s.BucketN += 1
  314. if b.root == 0 {
  315. s.InlineBucketN += 1
  316. }
  317. b.forEachPage(func(p *page, depth int) {
  318. if (p.flags & leafPageFlag) != 0 {
  319. s.KeyN += int(p.count)
  320. // used totals the used bytes for the page
  321. used := pageHeaderSize
  322. if p.count != 0 {
  323. // If page has any elements, add all element headers.
  324. used += leafPageElementSize * int(p.count-1)
  325. // Add all element key, value sizes.
  326. // The computation takes advantage of the fact that the position
  327. // of the last element's key/value equals to the total of the sizes
  328. // of all previous elements' keys and values.
  329. // It also includes the last element's header.
  330. lastElement := p.leafPageElement(p.count - 1)
  331. used += int(lastElement.pos + lastElement.ksize + lastElement.vsize)
  332. }
  333. if b.root == 0 {
  334. // For inlined bucket just update the inline stats
  335. s.InlineBucketInuse += used
  336. } else {
  337. // For non-inlined bucket update all the leaf stats
  338. s.LeafPageN++
  339. s.LeafInuse += used
  340. s.LeafOverflowN += int(p.overflow)
  341. // Collect stats from sub-buckets.
  342. // Do that by iterating over all element headers
  343. // looking for the ones with the bucketLeafFlag.
  344. for i := uint16(0); i < p.count; i++ {
  345. e := p.leafPageElement(i)
  346. if (e.flags & bucketLeafFlag) != 0 {
  347. // For any bucket element, open the element value
  348. // and recursively call Stats on the contained bucket.
  349. subStats.Add(b.openBucket(e.value()).Stats())
  350. }
  351. }
  352. }
  353. } else if (p.flags & branchPageFlag) != 0 {
  354. s.BranchPageN++
  355. lastElement := p.branchPageElement(p.count - 1)
  356. // used totals the used bytes for the page
  357. // Add header and all element headers.
  358. used := pageHeaderSize + (branchPageElementSize * int(p.count-1))
  359. // Add size of all keys and values.
  360. // Again, use the fact that last element's position equals to
  361. // the total of key, value sizes of all previous elements.
  362. used += int(lastElement.pos + lastElement.ksize)
  363. s.BranchInuse += used
  364. s.BranchOverflowN += int(p.overflow)
  365. }
  366. // Keep track of maximum page depth.
  367. if depth+1 > s.Depth {
  368. s.Depth = (depth + 1)
  369. }
  370. })
  371. // Alloc stats can be computed from page counts and pageSize.
  372. s.BranchAlloc = (s.BranchPageN + s.BranchOverflowN) * pageSize
  373. s.LeafAlloc = (s.LeafPageN + s.LeafOverflowN) * pageSize
  374. // Add the max depth of sub-buckets to get total nested depth.
  375. s.Depth += subStats.Depth
  376. // Add the stats for all sub-buckets
  377. s.Add(subStats)
  378. return s
  379. }
  380. // forEachPage iterates over every page in a bucket, including inline pages.
  381. func (b *Bucket) forEachPage(fn func(*page, int)) {
  382. // If we have an inline page then just use that.
  383. if b.page != nil {
  384. fn(b.page, 0)
  385. return
  386. }
  387. // Otherwise traverse the page hierarchy.
  388. b.tx.forEachPage(b.root, 0, fn)
  389. }
  390. // forEachPageNode iterates over every page (or node) in a bucket.
  391. // This also includes inline pages.
  392. func (b *Bucket) forEachPageNode(fn func(*page, *node, int)) {
  393. // If we have an inline page or root node then just use that.
  394. if b.page != nil {
  395. fn(b.page, nil, 0)
  396. return
  397. }
  398. b._forEachPageNode(b.root, 0, fn)
  399. }
  400. func (b *Bucket) _forEachPageNode(pgid pgid, depth int, fn func(*page, *node, int)) {
  401. var p, n = b.pageNode(pgid)
  402. // Execute function.
  403. fn(p, n, depth)
  404. // Recursively loop over children.
  405. if p != nil {
  406. if (p.flags & branchPageFlag) != 0 {
  407. for i := 0; i < int(p.count); i++ {
  408. elem := p.branchPageElement(uint16(i))
  409. b._forEachPageNode(elem.pgid, depth+1, fn)
  410. }
  411. }
  412. } else {
  413. if !n.isLeaf {
  414. for _, inode := range n.inodes {
  415. b._forEachPageNode(inode.pgid, depth+1, fn)
  416. }
  417. }
  418. }
  419. }
  420. // spill writes all the nodes for this bucket to dirty pages.
  421. func (b *Bucket) spill() error {
  422. // Spill all child buckets first.
  423. for name, child := range b.buckets {
  424. // If the child bucket is small enough and it has no child buckets then
  425. // write it inline into the parent bucket's page. Otherwise spill it
  426. // like a normal bucket and make the parent value a pointer to the page.
  427. var value []byte
  428. if child.inlineable() {
  429. child.free()
  430. value = child.write()
  431. } else {
  432. if err := child.spill(); err != nil {
  433. return err
  434. }
  435. // Update the child bucket header in this bucket.
  436. value = make([]byte, unsafe.Sizeof(bucket{}))
  437. var bucket = (*bucket)(unsafe.Pointer(&value[0]))
  438. *bucket = *child.bucket
  439. }
  440. // Skip writing the bucket if there are no materialized nodes.
  441. if child.rootNode == nil {
  442. continue
  443. }
  444. // Update parent node.
  445. var c = b.Cursor()
  446. k, _, flags := c.seek([]byte(name))
  447. if !bytes.Equal([]byte(name), k) {
  448. panic(fmt.Sprintf("misplaced bucket header: %x -> %x", []byte(name), k))
  449. }
  450. if flags&bucketLeafFlag == 0 {
  451. panic(fmt.Sprintf("unexpected bucket header flag: %x", flags))
  452. }
  453. c.node().put([]byte(name), []byte(name), value, 0, bucketLeafFlag)
  454. }
  455. // Ignore if there's not a materialized root node.
  456. if b.rootNode == nil {
  457. return nil
  458. }
  459. // Spill nodes.
  460. if err := b.rootNode.spill(); err != nil {
  461. return err
  462. }
  463. b.rootNode = b.rootNode.root()
  464. // Update the root node for this bucket.
  465. if b.rootNode.pgid >= b.tx.meta.pgid {
  466. panic(fmt.Sprintf("pgid (%d) above high water mark (%d)", b.rootNode.pgid, b.tx.meta.pgid))
  467. }
  468. b.root = b.rootNode.pgid
  469. return nil
  470. }
  471. // inlineable returns true if a bucket is small enough to be written inline
  472. // and if it contains no subbuckets. Otherwise returns false.
  473. func (b *Bucket) inlineable() bool {
  474. var n = b.rootNode
  475. // Bucket must only contain a single leaf node.
  476. if n == nil || !n.isLeaf {
  477. return false
  478. }
  479. // Bucket is not inlineable if it contains subbuckets or if it goes beyond
  480. // our threshold for inline bucket size.
  481. var size = pageHeaderSize
  482. for _, inode := range n.inodes {
  483. size += leafPageElementSize + len(inode.key) + len(inode.value)
  484. if inode.flags&bucketLeafFlag != 0 {
  485. return false
  486. } else if size > b.maxInlineBucketSize() {
  487. return false
  488. }
  489. }
  490. return true
  491. }
  492. // Returns the maximum total size of a bucket to make it a candidate for inlining.
  493. func (b *Bucket) maxInlineBucketSize() int {
  494. return b.tx.db.pageSize / 4
  495. }
  496. // write allocates and writes a bucket to a byte slice.
  497. func (b *Bucket) write() []byte {
  498. // Allocate the appropriate size.
  499. var n = b.rootNode
  500. var value = make([]byte, bucketHeaderSize+n.size())
  501. // Write a bucket header.
  502. var bucket = (*bucket)(unsafe.Pointer(&value[0]))
  503. *bucket = *b.bucket
  504. // Convert byte slice to a fake page and write the root node.
  505. var p = (*page)(unsafe.Pointer(&value[bucketHeaderSize]))
  506. n.write(p)
  507. return value
  508. }
  509. // rebalance attempts to balance all nodes.
  510. func (b *Bucket) rebalance() {
  511. for _, n := range b.nodes {
  512. n.rebalance()
  513. }
  514. for _, child := range b.buckets {
  515. child.rebalance()
  516. }
  517. }
  518. // node creates a node from a page and associates it with a given parent.
  519. func (b *Bucket) node(pgid pgid, parent *node) *node {
  520. _assert(b.nodes != nil, "nodes map expected")
  521. // Retrieve node if it's already been created.
  522. if n := b.nodes[pgid]; n != nil {
  523. return n
  524. }
  525. // Otherwise create a node and cache it.
  526. n := &node{bucket: b, parent: parent}
  527. if parent == nil {
  528. b.rootNode = n
  529. } else {
  530. parent.children = append(parent.children, n)
  531. }
  532. // Use the inline page if this is an inline bucket.
  533. var p = b.page
  534. if p == nil {
  535. p = b.tx.page(pgid)
  536. }
  537. // Read the page into the node and cache it.
  538. n.read(p)
  539. b.nodes[pgid] = n
  540. // Update statistics.
  541. b.tx.stats.NodeCount++
  542. return n
  543. }
  544. // free recursively frees all pages in the bucket.
  545. func (b *Bucket) free() {
  546. if b.root == 0 {
  547. return
  548. }
  549. var tx = b.tx
  550. b.forEachPageNode(func(p *page, n *node, _ int) {
  551. if p != nil {
  552. tx.db.freelist.free(tx.meta.txid, p)
  553. } else {
  554. n.free()
  555. }
  556. })
  557. b.root = 0
  558. }
  559. // dereference removes all references to the old mmap.
  560. func (b *Bucket) dereference() {
  561. if b.rootNode != nil {
  562. b.rootNode.root().dereference()
  563. }
  564. for _, child := range b.buckets {
  565. child.dereference()
  566. }
  567. }
  568. // pageNode returns the in-memory node, if it exists.
  569. // Otherwise returns the underlying page.
  570. func (b *Bucket) pageNode(id pgid) (*page, *node) {
  571. // Inline buckets have a fake page embedded in their value so treat them
  572. // differently. We'll return the rootNode (if available) or the fake page.
  573. if b.root == 0 {
  574. if id != 0 {
  575. panic(fmt.Sprintf("inline bucket non-zero page access(2): %d != 0", id))
  576. }
  577. if b.rootNode != nil {
  578. return nil, b.rootNode
  579. }
  580. return b.page, nil
  581. }
  582. // Check the node cache for non-inline buckets.
  583. if b.nodes != nil {
  584. if n := b.nodes[id]; n != nil {
  585. return nil, n
  586. }
  587. }
  588. // Finally lookup the page from the transaction if no node is materialized.
  589. return b.tx.page(id), nil
  590. }
  591. // BucketStats records statistics about resources used by a bucket.
  592. type BucketStats struct {
  593. // Page count statistics.
  594. BranchPageN int // number of logical branch pages
  595. BranchOverflowN int // number of physical branch overflow pages
  596. LeafPageN int // number of logical leaf pages
  597. LeafOverflowN int // number of physical leaf overflow pages
  598. // Tree statistics.
  599. KeyN int // number of keys/value pairs
  600. Depth int // number of levels in B+tree
  601. // Page size utilization.
  602. BranchAlloc int // bytes allocated for physical branch pages
  603. BranchInuse int // bytes actually used for branch data
  604. LeafAlloc int // bytes allocated for physical leaf pages
  605. LeafInuse int // bytes actually used for leaf data
  606. // Bucket statistics
  607. BucketN int // total number of buckets including the top bucket
  608. InlineBucketN int // total number on inlined buckets
  609. InlineBucketInuse int // bytes used for inlined buckets (also accounted for in LeafInuse)
  610. }
  611. func (s *BucketStats) Add(other BucketStats) {
  612. s.BranchPageN += other.BranchPageN
  613. s.BranchOverflowN += other.BranchOverflowN
  614. s.LeafPageN += other.LeafPageN
  615. s.LeafOverflowN += other.LeafOverflowN
  616. s.KeyN += other.KeyN
  617. if s.Depth < other.Depth {
  618. s.Depth = other.Depth
  619. }
  620. s.BranchAlloc += other.BranchAlloc
  621. s.BranchInuse += other.BranchInuse
  622. s.LeafAlloc += other.LeafAlloc
  623. s.LeafInuse += other.LeafInuse
  624. s.BucketN += other.BucketN
  625. s.InlineBucketN += other.InlineBucketN
  626. s.InlineBucketInuse += other.InlineBucketInuse
  627. }
  628. // cloneBytes returns a copy of a given slice.
  629. func cloneBytes(v []byte) []byte {
  630. var clone = make([]byte, len(v))
  631. copy(clone, v)
  632. return clone
  633. }