changed: `os.with_file` implementation
authorBrendan Hansen <brendan.f.hansen@gmail.com>
Fri, 19 May 2023 19:19:04 +0000 (14:19 -0500)
committerBrendan Hansen <brendan.f.hansen@gmail.com>
Fri, 19 May 2023 19:19:04 +0000 (14:19 -0500)
core/os/file.onyx

index 79bb717be1faa394cb6c239ff44771fee9c2e5d0..db2077ea01adb69da7049c55e1d967081da609e7 100644 (file)
@@ -103,31 +103,22 @@ get_contents :: #match {
 }
 
 with_file :: (path: str, mode := OpenMode.Read) -> Iterator(&File) {
-    Context :: struct {
-        valid_file_stream := false;
-
-        file_stream: File;
-    }
-
-    c := new(Context);
-    if file_stream := open(path, mode); file_stream {
-        c.file_stream = file_stream->unwrap();
-        c.valid_file_stream = true;
+    file_stream: ? File;
+    if fs := open(path, mode); fs {
+        file_stream = fs->ok();
     }
 
-    next :: (use c: &Context) -> (&File, bool) {
-        if !valid_file_stream do return null, false;
+    if file_stream {
+        return iter.single(
+            file_stream->unwrap() |> alloc.on_heap(),
+            file => {
+                close(file);
+                cfree(file);
+            });
 
-        defer valid_file_stream = false;
-        return &file_stream, true;
-    }
-
-    close_context :: (use c: &Context) {
-        close(&file_stream);
-        cfree(c);
+    } else {
+        return iter.empty(&File);
     }
-
-    return .{ c, next, close_context };
 }
 
 is_file :: (path: str) -> bool {