use Iter IntoIter(*), Iter(*), to, zip, all use Prim (panic, or-fail) use Mem i32-size use Misc is-just fn get-ptr (arr Ptr (Array count a), i Size) -> Ptr a if i < 0 or i >= @cast(count) panic('Access to array at index \(i). (max: \(count))') p = Mem.cast-ptr(arr) as Ptr a return Mem.offset-ptr(p, @cast(i)) fn get (arr Ptr (Array count a), i Size) -> a: arr get-ptr(i)& fn set (arr Ptr (Array count a), i Size, e a) p = arr get-ptr(i) p <&= e fn size (arr Ptr (Array n a)) -> Size: n Mem.i32-size() # i think it should be in Slice and called `from-array`? fn as-slice (arr Ptr (Array count a)) -> Slice a: Slice { ptr: Mem.cast(arr), count: @cast(count) } fn map-array (arr Array count a, fun a -> b) -> Array count b nuarr =& @undefined for x in 0 to (count - 1) x = x i32-size() nuarr set(x, get(&arr, x) fun()) return nuarr& fn map(arr, fun): map-array(arr, fun) fn fill-default (default a) -> Array count a arr =& @undefined for i in 0 to (count - 1) arr set(Mem.i32-size(i), default) return arr& # converts iterator into an array. # NOTE: fails if the length of the iterator does not exactly match # the array length. fn from-iter (it it) -> Array count a <= IntoIter it arr =& @undefined it =& it into-iter() for i in 0 to (count - 1) el = next(it) or-fail('(Array.from-iter) expect iter of length \(count), but no elements after \(i)') arr set(i Mem.i32-size(), el) if is-just(next(it)) panic('(Array.from-iter) iter too long. expect only \(count) elements') return arr& # converts iterator into an array # NOTE: this fails only if there is too much stuff. missing stuff will be filled with default. fn fill-iter (it it, default a) -> Array count a <= IntoIter it arr =& fill-default(default) it =& it into-iter() for i in 0 to (count - 1) case next(it) None return arr& Just(x) arr set(i Mem.i32-size(), x) if is-just(next(it)) panic('(Array.from-iter) iter too long. expect only \(count) elements') return arr& ArrayIter ^count a backing Array count a cur Size inst IntoIter Array into-iter (self): ArrayIter { backing: self, cur: 0 } inst IntoIter ArrayIter into-iter (self): self inst Iter ArrayIter next (self Ptr (ArrayIter count a)) if self&.cur >= @cast(count) return None e = (&self&.backing) get(self&.cur) self <&.cur= self&.cur + 1 return Just(e) inst Eq Array eq (l Array len a, r Array len a) -> Bool <= Eq a: l zip (r) all(fn ((l, r)): l == r) ##### # should this be here? fn u8-to-const-str (arr Ptr (Array n U8)) -> ConstStr: @cast(arr)