A simple stream reader protocol for Swift named StreamReader, with two
concrete implementations: GenericStreamReader and DataReader.
The GenericStreamReader can read from any GenericReadStream, which the
FileDescriptor (from SystemPackage),
FileHandle and IntputStream classes have been made to conform to.
letdata=...letreader=DataReader(data: data)letreadData=try reader.readDataToEnd()assert(readData == data)letinputStream=...letreader=InputStreamReader(stream: inputStream, bufferSize:1024, bufferSizeIncrement:512)
/* Read the stream until a newline (whether macOS or Classic MacOS) is found, and returns the data without the newline. */
let(line, separator)=try reader.readData(upTo:[Data("\n".utf8),Data("\r".utf8)], matchingMode:.anyMatchWins, failIfNotFound:false, includeDelimiter:false)
_ =try reader.readData(size: separator.count) /* We must read the line separator before next read, probably :) */Note: In the example above, if the file has Windows new lines, this will add an
empty new line after each line (the separator for Windows being \r\n).
Stream Reader has also a dedicated method to read a line in a stream:
/* Does not return the line separator, _but_ set stream position after the line separator. */
letlineData=try reader.readLine(allowUnixNewLines:true, allowLegacyMacOSNewLines:true, allowWindowsNewLines:true).line