Skip to content

Commit

Permalink
add Deque.Set
Browse files Browse the repository at this point in the history
  • Loading branch information
bradenaw committed Nov 25, 2023
1 parent f2ed395 commit 1b49b27
Show file tree
Hide file tree
Showing 2 changed files with 41 additions and 9 deletions.
9 changes: 9 additions & 0 deletions container/deque/deque.go
Original file line number Diff line number Diff line change
Expand Up @@ -175,6 +175,15 @@ func (d *Deque[T]) Item(i int) T {
return d.a[idx]
}

// Set sets the ith item in the deque. 0 is the front and d.Len()-1 is the back.
func (d *Deque[T]) Set(i int, t T) {
if i < 0 || i >= d.Len() {
panic("deque index out of range")
}
idx := (d.front + i) % len(d.a)
d.a[idx] = t
}

func positiveMod(l, d int) int {
x := l % d
if x < 0 {
Expand Down
41 changes: 32 additions & 9 deletions container/deque/deque_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -55,9 +55,12 @@ func FuzzDeque(f *testing.F) {
func() {
if len(oracle) == 0 {
t.Log("Front() should panic")
defer func() { recover() }()
deque.Front()
t.FailNow()
func() {
defer func() { recover() }()
deque.Front()
t.FailNow()
}()
return
}
oracleItem := oracle[0]
t.Logf("Front() -> %#v", oracleItem)
Expand All @@ -67,9 +70,12 @@ func FuzzDeque(f *testing.F) {
func() {
if len(oracle) == 0 {
t.Log("Back() should panic")
defer func() { recover() }()
deque.Back()
t.FailNow()
func() {
defer func() { recover() }()
deque.Back()
t.FailNow()
}()
return
}
oracleItem := oracle[len(oracle)-1]
t.Logf("Back() -> %#v", oracleItem)
Expand All @@ -79,15 +85,32 @@ func FuzzDeque(f *testing.F) {
func(i int) {
if i < 0 || i >= len(oracle) {
t.Logf("Item(%d) should panic", i)
defer func() { recover() }()
deque.Item(i)
t.FailNow()
func() {
defer func() { recover() }()
deque.Item(i)
t.FailNow()
}()
return
}
oracleItem := oracle[i]
t.Logf("Item(%d) -> %#v", i, oracleItem)
dequeItem := deque.Item(i)
require2.Equal(t, oracleItem, dequeItem)
},
func(i int, x byte) {
if i < 0 || i >= len(oracle) {
t.Logf("Set(%d, x) should panic", i)
func() {
defer func() { recover() }()
deque.Item(i)
t.FailNow()
}()
return
}
t.Logf("Set(%d, %d)", i, x)
oracle[i] = x
deque.Set(i, x)
},
func() {
t.Log("Iterate()")
oracleAll := oracle
Expand Down

0 comments on commit 1b49b27

Please sign in to comment.