mirror of
https://github.com/nim-lang/Nim.git
synced 2025-12-30 18:02:05 +00:00
Use defer in iterator to avoid possible leaks. Fixes #3802
This commit is contained in:
@@ -774,6 +774,7 @@ iterator walkFiles*(pattern: string): string {.tags: [ReadDirEffect].} =
|
||||
res: int
|
||||
res = findFirstFile(pattern, f)
|
||||
if res != -1:
|
||||
defer: findClose(res)
|
||||
while true:
|
||||
if not skipFindData(f) and
|
||||
(f.dwFileAttributes and FILE_ATTRIBUTE_DIRECTORY) == 0'i32:
|
||||
@@ -786,7 +787,6 @@ iterator walkFiles*(pattern: string): string {.tags: [ReadDirEffect].} =
|
||||
pattern[dotPos+1] == '*':
|
||||
yield splitFile(pattern).dir / extractFilename(ff)
|
||||
if findNextFile(res, f) == 0'i32: break
|
||||
findClose(res)
|
||||
else: # here we use glob
|
||||
var
|
||||
f: Glob
|
||||
@@ -795,11 +795,11 @@ iterator walkFiles*(pattern: string): string {.tags: [ReadDirEffect].} =
|
||||
f.gl_pathc = 0
|
||||
f.gl_pathv = nil
|
||||
res = glob(pattern, 0, nil, addr(f))
|
||||
defer: globfree(addr(f))
|
||||
if res == 0:
|
||||
for i in 0.. f.gl_pathc - 1:
|
||||
assert(f.gl_pathv[i] != nil)
|
||||
yield $f.gl_pathv[i]
|
||||
globfree(addr(f))
|
||||
|
||||
type
|
||||
PathComponent* = enum ## Enumeration specifying a path component.
|
||||
@@ -845,6 +845,7 @@ iterator walkDir*(dir: string; relative=false): tuple[kind: PathComponent, path:
|
||||
var f: WIN32_FIND_DATA
|
||||
var h = findFirstFile(dir / "*", f)
|
||||
if h != -1:
|
||||
defer: findClose(h)
|
||||
while true:
|
||||
var k = pcFile
|
||||
if not skipFindData(f):
|
||||
@@ -856,10 +857,10 @@ iterator walkDir*(dir: string; relative=false): tuple[kind: PathComponent, path:
|
||||
else: dir / extractFilename(getFilename(f))
|
||||
yield (k, xx)
|
||||
if findNextFile(h, f) == 0'i32: break
|
||||
findClose(h)
|
||||
else:
|
||||
var d = opendir(dir)
|
||||
if d != nil:
|
||||
defer: discard closedir(d)
|
||||
while true:
|
||||
var x = readdir(d)
|
||||
if x == nil: break
|
||||
@@ -883,7 +884,6 @@ iterator walkDir*(dir: string; relative=false): tuple[kind: PathComponent, path:
|
||||
if S_ISDIR(s.st_mode): k = pcDir
|
||||
if S_ISLNK(s.st_mode): k = succ(k)
|
||||
yield (k, y)
|
||||
discard closedir(d)
|
||||
|
||||
iterator walkDirRec*(dir: string, filter={pcFile, pcDir}): string {.
|
||||
tags: [ReadDirEffect].} =
|
||||
|
||||
@@ -2960,9 +2960,9 @@ when not defined(JS): #and not defined(nimscript):
|
||||
## buffer.add(line.replace("a", "0") & '\x0A')
|
||||
## writeFile(filename, buffer)
|
||||
var f = open(filename, bufSize=8000)
|
||||
defer: close(f)
|
||||
var res = TaintedString(newStringOfCap(80))
|
||||
while f.readLine(res): yield res
|
||||
close(f)
|
||||
|
||||
iterator lines*(f: File): TaintedString {.tags: [ReadIOEffect].} =
|
||||
## Iterate over any line in the file `f`.
|
||||
|
||||
Reference in New Issue
Block a user