Skip to content

Commit 7e7df6a

Browse files
authored
Automatically dispose DirectoryStream when possible (#55)
* Automatically dispose DirectoryStream when possible * Remove finalizer
1 parent f90253d commit 7e7df6a

File tree

1 file changed

+27
-12
lines changed

1 file changed

+27
-12
lines changed

src/directory.toit

Lines changed: 27 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -92,34 +92,49 @@ chdir name:
9292

9393
// An open directory, used to iterate over the named entries in a directory.
9494
class DirectoryStream:
95-
dir_ := ?
95+
dir_ := null
96+
is_closed_/bool := false
9697

9798
constructor name:
98-
dir_ = null
9999
error := catch:
100100
dir_ = opendir_ resource_freeing_module_ name
101-
if error:
102-
if error is string:
103-
throw "$error: \"$name\""
101+
if error is string:
102+
throw "$error: \"$name\""
103+
else if error:
104104
throw error
105+
add-finalizer this:: dispose_
105106

106107
/**
107108
Returns a string with the next name from the directory.
108109
The '.' and '..' entries are skipped and never returned.
109-
Returns null when no entry is left.
110+
Returns null when no entries are left.
110111
*/
111112
next -> string?:
113+
if is_closed_: throw "ALREADY_CLOSED"
114+
// We automatically dispose the underlying resource when
115+
// we reach the end of the stream. In that case, we return
116+
// null because we know that no more entries are left.
117+
dir := dir_
118+
if not dir: return null
112119
while true:
113-
byte_array := readdir_ dir_
114-
if not byte_array: return null
115-
str := byte_array.to_string
120+
bytes/ByteArray? := readdir_ dir
121+
if not bytes:
122+
dispose_
123+
return null
124+
str := bytes.to_string
116125
if str == "." or str == "..": continue
117126
return str
118127

119128
close -> none:
120-
if dir_:
121-
closedir_ dir_
122-
dir_ = null
129+
is_closed_ = true
130+
dispose_
131+
132+
dispose_ -> none:
133+
dir := dir_
134+
if not dir: return
135+
dir_ = null
136+
closedir_ dir
137+
remove_finalizer this
123138

124139
opendir_ resource_group name:
125140
#primitive.file.opendir2

0 commit comments

Comments
 (0)