switch to binary search

This commit is contained in:
Matthias Kadenbach 2017-02-15 10:48:43 -08:00
parent 53630f5ff1
commit 316f6c0cf3
No known key found for this signature in database
GPG Key ID: DC1F4DC6D31A7031
2 changed files with 20 additions and 4 deletions

View File

@ -116,10 +116,9 @@ func (i *Migrations) Down(version uint) (m *Migration, ok bool) {
func (i *Migrations) findPos(version uint) int {
if len(i.index) > 0 {
for i, v := range i.index {
if v == version {
return i
}
ix := i.index.Search(version)
if ix < len(i.index) && i.index[ix] == version {
return ix
}
}
return -1
@ -138,3 +137,7 @@ func (s uintSlice) Swap(i, j int) {
func (s uintSlice) Less(i, j int) bool {
return s[i] < s[j]
}
func (s uintSlice) Search(x uint) int {
return sort.Search(len(s), func(i int) bool { return s[i] >= x })
}

View File

@ -31,3 +31,16 @@ func TestUp(t *testing.T) {
func TestDown(t *testing.T) {
// TODO
}
func TestFindPos(t *testing.T) {
m := Migrations{index: uintSlice{1, 2, 3}}
if p := m.findPos(0); p != -1 {
t.Errorf("expected -1, got %v", p)
}
if p := m.findPos(1); p != 0 {
t.Errorf("expected 0, got %v", p)
}
if p := m.findPos(3); p != 2 {
t.Errorf("expected 2, got %v", p)
}
}