From 58c6521bbf45bfc4c0d7896247a28fa5d08407ce Mon Sep 17 00:00:00 2001 From: Yeo Kheng Meng Date: Tue, 25 Oct 2016 23:17:24 +0800 Subject: [PATCH] Correct issue where sometimes the bytesRead can be -1 especially when read() is called for the first time --- Sources/SwiftSerial.swift | 12 +++++++++++- 1 file changed, 11 insertions(+), 1 deletion(-) diff --git a/Sources/SwiftSerial.swift b/Sources/SwiftSerial.swift index d7cae99..d489b7a 100644 --- a/Sources/SwiftSerial.swift +++ b/Sources/SwiftSerial.swift @@ -380,7 +380,16 @@ extension SerialPort { } let bytesRead = try readBytes(into: buffer, size: length) - let data = Data(bytes: buffer, count: bytesRead) + + var data : Data + + if bytesRead > 0 { + data = Data(bytes: buffer, count: bytesRead) + } else { + //This is to avoid the case where bytesRead can be negative causing problems allocating the Data buffer + data = Data(bytes: buffer, count: 0) + } + return data } @@ -390,6 +399,7 @@ extension SerialPort { while remainingBytesToRead > 0 { let data = try readData(ofLength: remainingBytesToRead) + if let string = String(data: data, encoding: String.Encoding.utf8) { result += string remainingBytesToRead -= data.count