Skip to content

Commit

Permalink
minor
Browse files Browse the repository at this point in the history
  • Loading branch information
gaissmai committed Jan 26, 2025
1 parent c1fd3be commit 2a1f31e
Showing 1 changed file with 10 additions and 8 deletions.
18 changes: 10 additions & 8 deletions internal/sparse/array.go
Original file line number Diff line number Diff line change
Expand Up @@ -55,7 +55,6 @@ func (s *Array[T]) Copy() *Array[T] {

// InsertAt a value at i into the sparse array.
// If the value already exists, overwrite it with val and return true.
// The capacity is identical to the length after insertion.
func (s *Array[T]) InsertAt(i uint, val T) (exists bool) {
// slot exists, overwrite val
if s.Len() != 0 && s.Test(i) {
Expand All @@ -68,7 +67,7 @@ func (s *Array[T]) InsertAt(i uint, val T) (exists bool) {
s.BitSet = s.Set(i)

// ... and slice
s.insertItem(val, s.Rank0(i))
s.insertItem(s.Rank0(i), val)

return false
}
Expand Down Expand Up @@ -135,21 +134,22 @@ func (s *Array[T]) UpdateAt(i uint, cb func(T, bool) T) (newVal T, wasPresent bo
idx = s.Rank0(i)

// ... and insert value into slice
s.insertItem(newVal, idx)
s.insertItem(idx, newVal)

return newVal, wasPresent
}

// insertItem inserts the item at index i, shift the rest one pos right
//
// It panics if i is out of range.
func (s *Array[T]) insertItem(item T, i int) {
func (s *Array[T]) insertItem(i int, item T) {
if len(s.Items) < cap(s.Items) {
s.Items = s.Items[:len(s.Items)+1] // fast resize, no alloc
} else {
var zero T
s.Items = append(s.Items, zero) // appends maybe more than just one item
s.Items = append(s.Items, zero) // append one item, mostly enlarge cap by more than one item
}

copy(s.Items[i+1:], s.Items[i:])
s.Items[i] = item
}
Expand All @@ -159,8 +159,10 @@ func (s *Array[T]) insertItem(item T, i int) {
// It panics if i is out of range.
func (s *Array[T]) deleteItem(i int) {
var zero T

l := len(s.Items) - 1 // new len
copy(s.Items[i:], s.Items[i+1:]) // overwrite s[i]
s.Items[l] = zero // clear the tail item
s.Items = s.Items[:l] // new len, cap is unchanged
copy(s.Items[i:], s.Items[i+1:]) // overwrite item at [i]

s.Items[l] = zero // clear the tail item
s.Items = s.Items[:l] // new len, keep cap is unchanged
}

0 comments on commit 2a1f31e

Please sign in to comment.