| 1 | module scheme |
| 2 | |
| 3 | // This compiler's array-assignment temporary is a C int even though V int |
| 4 | // and array lengths are 64-bit. Keep the ordinary bounds check, then store |
| 5 | // through a full-width pointer index. No pointer survives this call. |
| 6 | @[inline] |
| 7 | fn container_store[T](mut items []T, index int, value T) { |
| 8 | if index < 0 || index >= items.len { panic('container index out of range') } |
| 9 | unsafe { (&T(items.data))[index] = value } |
| 10 | } |
| 11 | |
| 12 | // Callers use this after validating a public range, or for a private index |
| 13 | // proven within the current initialized length. It does not accept spare cap. |
| 14 | @[inline] |
| 15 | fn container_store_validated[T](mut items []T, index int, value T) { |
| 16 | unsafe { (&T(items.data))[index] = value } |
| 17 | } |
| 18 | |
| 19 | // Value's default representation is all zero. Capacity-only allocation avoids |
| 20 | // the compiler's per-element struct initializer, which has the same narrowing. |
| 21 | fn value_storage(length int) []Value { |
| 22 | mut items := []Value{cap: length} |
| 23 | if length > 0 { unsafe { vmemset(items.data, 0, length * int(sizeof(Value))) } } |
| 24 | unsafe { items.len = length } |
| 25 | return items |
| 26 | } |
| 27 | |
| 28 | // A fully initialized scanned array is published only after the loop. The |
| 29 | // pointer remains local to this allocation and never crosses a callback. |
| 30 | fn filled_storage[T](length int, value T) []T { |
| 31 | mut items := []T{cap: length} |
| 32 | for i in 0 .. length { |
| 33 | unsafe { (&T(items.data))[i] = value } |
| 34 | } |
| 35 | unsafe { items.len = length } |
| 36 | return items |
| 37 | } |
| 38 | |
| 39 | // Explicit ends equal to max_i32 have a special meaning to array.slice. |
| 40 | // Copy the validated exact range directly instead, including that boundary. |
| 41 | @[inline] |
| 42 | fn copy_values(items []Value, start int, end int) []Value { |
| 43 | return copy_container_range(items, start, end) |
| 44 | } |
| 45 | |
| 46 | fn copy_container_range[T](items []T, start int, end int) []T { |
| 47 | if start < 0 || end < start || end > items.len { panic('container range out of bounds') } |
| 48 | count := end - start |
| 49 | mut result := []T{cap: count} |
| 50 | if count > 0 { |
| 51 | unsafe { vmemcpy(result.data, &T(items.data) + start, count * int(sizeof(T))) } |
| 52 | } |
| 53 | unsafe { result.len = count } |
| 54 | return result |
| 55 | } |
| 56 | |