From 9ecfe91c9cc34d527ba269fbcde47859f63e73b1 Mon Sep 17 00:00:00 2001 From: Kare Morstol Date: Thu, 14 Apr 2016 02:08:51 +0200 Subject: [PATCH] =?UTF-8?q?Fix=20#16=20by=20having=20WriteableStream=20use?= =?UTF-8?q?=20=E2=80=98print=E2=80=99=20when=20writing=20to=20standard=20o?= =?UTF-8?q?utput.?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit This way print's buffering when standard output is not a terminal does not rearrange the order in which output is printed when using both 'print' and 'main.stdout.writeln'. See also https://bugs.swift.org/browse/SR-1127 and http://stackoverflow.com/a/13933741/96587 . --- Sources/SwiftShell/Stream.swift | 18 +++++++++++++----- 1 file changed, 13 insertions(+), 5 deletions(-) diff --git a/Sources/SwiftShell/Stream.swift b/Sources/SwiftShell/Stream.swift index 3dcc5dd..e2a3b77 100644 --- a/Sources/SwiftShell/Stream.swift +++ b/Sources/SwiftShell/Stream.swift @@ -59,19 +59,27 @@ public final class WriteableStream : OutputStreamType { public let filehandle: NSFileHandle let encoding: NSStringEncoding - /** Write anything to the stream. */ + /** Write the textual representation of `x` to the stream. */ public func write (x: T) { - filehandle.write(x, encoding: encoding) + if filehandle.fileDescriptor == STDOUT_FILENO { + print(x, terminator: "") + } else { + filehandle.write(x, encoding: encoding) + } } - /** Write anything to the stream, and add a newline. */ + /** Write the textual representation of `x` to the stream, and add a newline. */ public func writeln (x: T) { - filehandle.writeln(x, encoding: encoding) + if filehandle.fileDescriptor == STDOUT_FILENO { + print(x) + } else { + filehandle.writeln(x, encoding: encoding) + } } /** Write a newline to the stream. */ public func writeln () { - filehandle.writeln("") + writeln("") } /** Close the stream. Must be called on local streams when finished writing. */