| 1 |
// Copyright (c) 2026, Daniel Martà <[email protected]> |
| 2 |
// See LICENSE for licensing information |
| 3 |
|
| 4 |
package internal |
| 5 |
|
| 6 |
import "slices" |
| 7 |
|
| 8 |
// The helpers below manipulate indexed array variables held as a list of |
| 9 |
// elements plus the index of each element when the array is sparse. |
| 10 |
// A nil indexes slice means the array is dense: each element's index is its |
| 11 |
// position in the list. See the expand.Variable.Indexes field. |
| 12 |
|
| 13 |
// IndexedMax returns the maximum index of an indexed array, |
| 14 |
// or -1 when the array is empty. |
| 15 |
func IndexedMax(list []string, indexes []int) int { |
| 16 |
if len(indexes) > 0 { |
| 17 |
return indexes[len(indexes)-1] |
| 18 |
} |
| 19 |
return len(list) - 1 |
| 20 |
} |
| 21 |
|
| 22 |
// SetIndexedElem returns list and indexes with the element at index k set, |
| 23 |
// converting a dense array to a sparse one when setting index k would |
| 24 |
// otherwise leave a hole. The index k must not be negative. |
| 25 |
func SetIndexedElem(list []string, indexes []int, k int, val string) ([]string, []int) { |
| 26 |
if indexes == nil { |
| 27 |
if k < len(list) { |
| 28 |
list[k] = val |
| 29 |
return list, nil |
| 30 |
} |
| 31 |
if k == len(list) { |
| 32 |
return append(list, val), nil |
| 33 |
} |
| 34 |
indexes = make([]int, len(list), len(list)+1) |
| 35 |
for i := range indexes { |
| 36 |
indexes[i] = i |
| 37 |
} |
| 38 |
} |
| 39 |
pos, ok := slices.BinarySearch(indexes, k) |
| 40 |
if ok { |
| 41 |
list[pos] = val |
| 42 |
return list, indexes |
| 43 |
} |
| 44 |
list = slices.Insert(list, pos, val) |
| 45 |
indexes = slices.Insert(indexes, pos, k) |
| 46 |
return list, CanonicalIndexes(indexes) |
| 47 |
} |
| 48 |
|
| 49 |
// DeleteIndexedElem is like [SetIndexedElem], but unsetting the element at |
| 50 |
// index k, which may leave a hole. |
| 51 |
func DeleteIndexedElem(list []string, indexes []int, k int) ([]string, []int) { |
| 52 |
if indexes == nil { |
| 53 |
if k < 0 || k >= len(list) { |
| 54 |
return list, nil |
| 55 |
} |
| 56 |
if k == len(list)-1 { |
| 57 |
return list[:k], nil |
| 58 |
} |
| 59 |
indexes = make([]int, len(list)) |
| 60 |
for i := range indexes { |
| 61 |
indexes[i] = i |
| 62 |
} |
| 63 |
} |
| 64 |
pos, ok := slices.BinarySearch(indexes, k) |
| 65 |
if !ok { |
| 66 |
return list, indexes |
| 67 |
} |
| 68 |
list = slices.Delete(list, pos, pos+1) |
| 69 |
indexes = slices.Delete(indexes, pos, pos+1) |
| 70 |
return list, CanonicalIndexes(indexes) |
| 71 |
} |
| 72 |
|
| 73 |
// CanonicalIndexes returns nil when indexes is simply 0, 1, 2, and so on, |
| 74 |
// as a dense array should leave the indexes nil. |
| 75 |
func CanonicalIndexes(indexes []int) []int { |
| 76 |
for i, k := range indexes { |
| 77 |
if k != i { |
| 78 |
return indexes |
| 79 |
} |
| 80 |
} |
| 81 |
return nil |
| 82 |
} |