-
Notifications
You must be signed in to change notification settings - Fork 0
/
paging.go
75 lines (62 loc) · 1.21 KB
/
paging.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
package main
import (
"errors"
)
var (
ErrCursorOutOfRange = errors.New("Paging cursor out of range")
ErrPageNoOutOfRange = errors.New("Page number out of range")
)
type Paging struct {
nrPerPage, nrEntries, nrPages, cursor, curPage int
}
func NewPaging(nrPerPage, nrEntries int) *Paging {
npages := nrEntries / nrPerPage
if nrEntries%nrPerPage > 0 {
npages++
}
if npages == 0 {
npages++
}
return &Paging{
nrPerPage: nrPerPage,
nrEntries: nrEntries,
nrPages: npages,
cursor: 0,
curPage: 1,
}
}
func (p *Paging) HasPrev() bool {
return p.curPage > 1
}
func (p *Paging) HasNext() bool {
return p.curPage < p.LastPageNo()
}
func (p *Paging) PrevPageNo() int {
return p.curPage - 1
}
func (p *Paging) NextPageNo() int {
return p.curPage + 1
}
func (p *Paging) FirstPageNo() int {
return 1
}
func (p *Paging) LastPageNo() int {
return p.nrPages
}
func (p *Paging) SetCursor(i int) error {
if i < 0 || i >= p.nrEntries {
return ErrCursorOutOfRange
}
p.cursor = i
return nil
}
func (p *Paging) SetPageNo(no int) error {
if no < 1 || no > p.LastPageNo() {
return ErrPageNoOutOfRange
}
p.cursor = (no - 1) * p.nrPerPage
return nil
}
func (p *Paging) Cursor() int {
return p.cursor
}