added variant of iter.as_iterator for arrays by pointer
authorBrendan Hansen <brendan.f.hansen@gmail.com>
Thu, 31 Mar 2022 20:25:15 +0000 (15:25 -0500)
committerBrendan Hansen <brendan.f.hansen@gmail.com>
Thu, 31 Mar 2022 20:25:15 +0000 (15:25 -0500)
core/container/iter.onyx

index b7b3efe5076b4ab3a5fe7839e55bcfbf06e16b3f..11f5b781e459697f414ff8693683800a94958247 100644 (file)
@@ -437,7 +437,47 @@ from_array :: (arr: [] $T) -> Iterator(^T) {
     };
 }
 
-#match as_iterator (x: ^[..] $T) -> Iterator(^T) {
+#match as_iterator (x: ^[..] $T) -> Iterator(T) {
+    Context :: struct (T: type_expr) {
+        arr: ^[..] T;
+        current: u32;
+    }
+
+    c := make(Context(T));
+    c.arr = x;
+    c.current = 0;
+
+    next :: (use _: ^Context($T)) -> (T, bool) {
+        if current < arr.count {
+            defer current += 1;
+            return arr.data[current], true;
+
+        } else {
+            return null, false;
+        }
+    }
+
+    close :: (data: rawptr) {
+        cfree(data);
+    }
+
+    remove :: (use _: ^Context($T)) {
+        //
+        // This is current - 1 because current will have already
+        // been incremented by the time this element calls #remove.
+        array :: package core.array
+        array.delete(arr, current - 1);
+    }
+
+    return .{
+        data  = c,
+        next  = #solidify next { T = T },
+        close = close,
+        remove = #solidify remove { T = T },
+    };
+}
+
+#match as_iterator (x: ^[..] $T, by_pointer: bool) -> Iterator(^T) {
     Context :: struct (T: type_expr) {
         arr: ^[..] T;
         current: u32;