-
Notifications
You must be signed in to change notification settings - Fork 5
/
pager.go
105 lines (87 loc) · 2.43 KB
/
pager.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
package mempager
const DEFAULT_PAGE_SIZE = 1024
// Page is an indexed representation of a chunk of memory
type Page struct {
offset int
buffer []byte
}
// Offset returns the byte offset of the page relvative to the other pages within the pager
func (p Page) Offset() int {
return p.offset
}
// Buffer returns a pointer to the internal byte buffer of the page
func (p Page) Buffer() *[]byte {
return &p.buffer
}
// Pager is a tool used to reference chunks of memory (pages)
// Allows retrieval, allocation, and setting memory contents by an index
type Pager struct {
pageSize int
pages []*Page
}
// NewPager constructs a new pager with the specified pageSize
// Defaults the page size to 1024 bytes if passed a size of 0
func NewPager(pageSize int) Pager {
if pageSize == 0 {
pageSize = DEFAULT_PAGE_SIZE
}
return Pager{
pageSize: pageSize,
pages: []*Page{},
}
}
func (p Pager) newPage(index int, buf []byte) *Page {
return &Page{
offset: index * p.pageSize,
buffer: buf,
}
}
// Get will return the page at the specified index
func (p Pager) Get(pageNum int) *Page {
if pageNum >= len(p.pages) {
return nil
}
return p.pages[pageNum]
}
// GetOrAlloc will return the page at the specified index, allocating it if not already allocated
func (p *Pager) GetOrAlloc(pageNum int) (page *Page) {
p.growPages(pageNum)
if page = p.pages[pageNum]; page == nil {
p.pages[pageNum] = p.newPage(pageNum, make([]byte, p.pageSize))
page = p.pages[pageNum]
}
return page
}
// PageSize will return the page size of the pager
func (p Pager) PageSize() int {
return p.pageSize
}
// Len will return the size of the pager (number of pages)
func (p Pager) Len() int {
return len(p.pages)
}
// IsEmpty will check if the memory page is empty (has zero pages)
func (p Pager) IsEmpty() bool {
return len(p.pages) == 0
}
// Set will set the contents of the page at the specified index, with the provided data
// Allocates a new page if it doesn't already exist
func (p *Pager) Set(pageNum int, data []byte) {
page := p.GetOrAlloc(pageNum)
page.buffer = p.truncate(data)
}
// growPages will increases the size of the pager's page buffer up till the supplied index
func (p *Pager) growPages(index int) {
diff := index - (len(p.pages) - 1)
if diff <= 0 {
return
}
padding := make([]*Page, diff)
p.pages = append(p.pages, padding...)
}
func (p Pager) truncate(buf []byte) []byte {
if p.pageSize >= len(buf) {
return buf
}
return buf[:p.pageSize]
}