pagecursor.go 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102
  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 paging contains functions and constants necessary for paging of records.
  12. NOTE: Operations in this code are expected to either fail completely or succeed.
  13. Errors in the middle of an operation may leave the datastructures in an
  14. inconsistent state.
  15. PageCursor
  16. PageCursor is a pointer into a PagedStorageFile and can be used to traverse
  17. a linked list of pages (see also PagedStorageFileHeader which stores the
  18. entry points).
  19. PagedStorageFile
  20. PagedStorageFile is a wrapper object for a StorageFile which views the file
  21. records as a linked list of pages.
  22. PagedStorageFileHeader
  23. PagedStorageFileHeader is a wrapper object for the header record of a StorageFile.
  24. The header record stores information about linked lists and root values.
  25. */
  26. package paging
  27. /*
  28. PageCursor data structure
  29. */
  30. type PageCursor struct {
  31. psf *PagedStorageFile // Pager to be used
  32. ptype int16 // Page type which will be traversed
  33. current uint64 // Current page
  34. }
  35. /*
  36. NewPageCursor creates a new cursor object which can be used to traverse a set of pages.
  37. */
  38. func NewPageCursor(psf *PagedStorageFile, ptype int16, current uint64) *PageCursor {
  39. return &PageCursor{psf, ptype, current}
  40. }
  41. /*
  42. Current gets the page this cursor currently points at.
  43. */
  44. func (pc *PageCursor) Current() uint64 {
  45. return pc.current
  46. }
  47. /*
  48. Next moves the PageCursor to the next page and returns it.
  49. */
  50. func (pc *PageCursor) Next() (uint64, error) {
  51. var page uint64
  52. var err error
  53. if pc.current == 0 {
  54. page = pc.psf.First(pc.ptype)
  55. } else {
  56. page, err = pc.psf.Next(pc.current)
  57. if err != nil {
  58. return 0, err
  59. }
  60. }
  61. if page != 0 {
  62. pc.current = page
  63. }
  64. return page, nil
  65. }
  66. /*
  67. Prev moves the PageCursor to the previous page and returns it.
  68. */
  69. func (pc *PageCursor) Prev() (uint64, error) {
  70. if pc.current == 0 {
  71. return 0, nil
  72. }
  73. page, err := pc.psf.Prev(pc.current)
  74. if err != nil {
  75. return 0, err
  76. }
  77. if page != 0 {
  78. pc.current = page
  79. }
  80. return page, nil
  81. }