fix: improve paging and subscriptions

This commit is contained in:
Jon Lundy
2022-08-10 10:09:58 -06:00
parent 0642879c07
commit 72e7d5f265
11 changed files with 118 additions and 81 deletions

View File

@@ -38,3 +38,30 @@ func Min[T ordered](i T, candidates ...T) T {
}
return i
}
func PagerBox(first, last uint64, pos, count int64) (uint64, int64) {
var start uint64
if pos >= 0 {
start = first + uint64(pos)
} else {
start = uint64(int64(last) + pos + 1)
}
switch {
case count > 0:
count = Min(count, int64(last-start)+1)
case pos >= 0 && count < 0:
count = Max(count, int64(first-start))
case pos < 0 && count < 0:
count = Max(count, int64(first-start)-1)
}
if count == 0 || (start < first && count <= 0) || (start > last && count >= 0) {
return 0, 0
}
return start, count
}

View File

@@ -1,9 +1,11 @@
package math_test
import (
"log"
"testing"
"github.com/matryer/is"
"github.com/sour-is/ev/pkg/es"
"github.com/sour-is/ev/pkg/math"
)
@@ -46,3 +48,46 @@ func TestMath(t *testing.T) {
))
}
func TestPagerBox(t *testing.T) {
is := is.New(t)
tests := []struct {
first uint64
last uint64
pos int64
n int64
start uint64
count int64
}{
{1, 10, 0, 10, 1, 10},
{1, 10, 0, 11, 1, 10},
{1, 5, 0, 10, 1, 5},
{1, 10, 4, 10, 5, 6},
{1, 10, 5, 10, 6, 5},
{1, 10, 0, -10, 0, 0},
{1, 10, 1, -1, 2, -1},
{1, 10, 1, -10, 2, -1},
{1, 10, -1, 1, 10, 1},
{1, 10, -2, 10, 9, 2},
{1, 10, -1, -1, 10, -1},
{1, 10, -2, -10, 9, -9},
{1, 10, 0, -10, 0, 0},
{1, 10, 10, 10, 0, 0},
{1, 10, 0, es.AllEvents, 1, 10},
{1, 10, -1, -es.AllEvents, 10, -10},
}
for _, tt := range tests {
start, count := math.PagerBox(tt.first, tt.last, tt.pos, tt.n)
if count > 0 {
log.Print(tt, "|", start, count, int64(start)+count-1)
} else {
log.Print(tt, "|", start, count, int64(start)+count+1)
}
is.Equal(start, tt.start)
is.Equal(count, tt.count)
}
}