diff options
author | n5m <72841454+n5m@users.noreply.github.com> | 2022-10-31 10:20:06 +0000 |
---|---|---|
committer | GitHub <noreply@github.com> | 2022-10-31 11:20:06 +0100 |
commit | 52166e354617e222cd0a92c581411cb1f60d4fc0 (patch) | |
tree | 5b6768fe86dc891600777a9623d5aa19c920224b | |
parent | 0a1f204f0ffb6201e0f0ea8466e9d474beae5324 (diff) | |
download | Nim-52166e354617e222cd0a92c581411cb1f60d4fc0.tar.gz |
allow deferred close of nil stream (#20706)
* allow deferred close of nil stream * improve example
-rw-r--r-- | lib/pure/streams.nim | 18 | ||||
-rw-r--r-- | tests/stdlib/tstreams.nim | 6 |
2 files changed, 20 insertions, 4 deletions
diff --git a/lib/pure/streams.nim b/lib/pure/streams.nim index 50b3085d2..7ebae3e09 100644 --- a/lib/pure/streams.nim +++ b/lib/pure/streams.nim @@ -173,10 +173,20 @@ proc close*(s: Stream) = ## See also: ## * `flush proc <#flush,Stream>`_ runnableExamples: - var strm = newStringStream("The first line\nthe second line\nthe third line") - ## do something... - strm.close() - if not isNil(s.closeImpl): s.closeImpl(s) + block: + let strm = newStringStream("The first line\nthe second line\nthe third line") + ## do something... + strm.close() + + block: + let strm = newFileStream("amissingfile.txt") + # deferring works even if newFileStream fails + defer: strm.close() + if not isNil(strm): + ## do something... + + if not isNil(s) and not isNil(s.closeImpl): + s.closeImpl(s) proc atEnd*(s: Stream): bool = ## Checks if more data can be read from `s`. Returns ``true`` if all data has diff --git a/tests/stdlib/tstreams.nim b/tests/stdlib/tstreams.nim index 08441a766..891b38e20 100644 --- a/tests/stdlib/tstreams.nim +++ b/tests/stdlib/tstreams.nim @@ -50,6 +50,12 @@ block tstreams3: echo line s.close + +block: + let fs = newFileStream("amissingfile.txt") + defer: fs.close() + doAssert isNil(fs) + # bug #12410 var a = newStringStream "hehohihahuhyh" |