|
| 1 | +import Foundation |
| 2 | + |
| 3 | +internal extension CSVWriter { |
| 4 | + /// Closure where each time that is executed a scalar will be stored on the final output. |
| 5 | + typealias ScalarEncoder = (Unicode.Scalar) throws -> Void |
| 6 | + |
| 7 | + /// Creates an encoder that take a `Unicode.Scalar` and store the correct byte representation on the appropriate place. |
| 8 | + /// - parameter stream: Output stream receiving the encoded data. |
| 9 | + /// - parameter encoding: The string encoding being used for the external representation. |
| 10 | + /// - parameter firstBytes: Bytes to be preppended at the beggining of the stream. |
| 11 | + static func makeEncoder(from stream: OutputStream, encoding: String.Encoding, firstBytes: [UInt8]) throws -> ScalarEncoder { |
| 12 | + if !firstBytes.isEmpty { |
| 13 | + try CSVWriter.lowlevelWriter(on: stream, bytes: firstBytes, count: firstBytes.count) |
| 14 | + } |
| 15 | + |
| 16 | + switch encoding { |
| 17 | + case .ascii: |
| 18 | + return { [unowned stream] (scalar) in |
| 19 | + guard var byte = Unicode.ASCII.encode(scalar)?.first else { throw Error.invalidASCII(scalar: scalar) } |
| 20 | + try CSVWriter.lowlevelWriter(on: stream, bytes: &byte, count: 1) |
| 21 | + } |
| 22 | + case .utf8: |
| 23 | + return { [unowned stream] (scalar) in |
| 24 | + guard let bytes = Unicode.UTF8.encode(scalar), |
| 25 | + let _ = try bytes.withContiguousStorageIfAvailable({ try CSVWriter.lowlevelWriter(on: stream, bytes: $0.baseAddress!, count: bytes.count) }) else { |
| 26 | + throw Error.invalidUTF8(scalar: scalar) |
| 27 | + } |
| 28 | + } |
| 29 | + case .utf16BigEndian, .utf16, .unicode: // UTF16 & Unicode imply: follow the BOM and if it is not there, assume big endian. |
| 30 | + return { [unowned stream] (scalar) in |
| 31 | + guard let tmp = Unicode.UTF16.encode(scalar) else { throw Error.invalidUTF16(scalar: scalar) } |
| 32 | + let bytes = tmp.flatMap { |
| 33 | + [UInt8(truncatingIfNeeded: $0 >> 8), |
| 34 | + UInt8(truncatingIfNeeded: $0)] |
| 35 | + } |
| 36 | + try CSVWriter.lowlevelWriter(on: stream, bytes: bytes, count: bytes.count) |
| 37 | + } |
| 38 | + case .utf16LittleEndian: |
| 39 | + return { [unowned stream] (scalar) in |
| 40 | + guard let tmp = Unicode.UTF16.encode(scalar) else { throw Error.invalidUTF16(scalar: scalar) } |
| 41 | + let bytes = tmp.flatMap { |
| 42 | + [UInt8(truncatingIfNeeded: $0), |
| 43 | + UInt8(truncatingIfNeeded: $0 >> 8)] |
| 44 | + } |
| 45 | + try CSVWriter.lowlevelWriter(on: stream, bytes: bytes, count: bytes.count) |
| 46 | + } |
| 47 | + case .utf32BigEndian, .utf32: |
| 48 | + return { [unowned stream] (scalar) in |
| 49 | + guard let tmp = Unicode.UTF32.encode(scalar) else { throw Error.invalidUTF32(scalar: scalar) } |
| 50 | + let bytes = tmp.flatMap { |
| 51 | + [UInt8(truncatingIfNeeded: $0 >> 24), |
| 52 | + UInt8(truncatingIfNeeded: $0 >> 16), |
| 53 | + UInt8(truncatingIfNeeded: $0 >> 8), |
| 54 | + UInt8(truncatingIfNeeded: $0)] |
| 55 | + } |
| 56 | + try CSVWriter.lowlevelWriter(on: stream, bytes: bytes, count: bytes.count) |
| 57 | + } |
| 58 | + case .utf32LittleEndian: |
| 59 | + return { [unowned stream] (scalar) in |
| 60 | + guard let tmp = Unicode.UTF32.encode(scalar) else { throw Error.invalidUTF32(scalar: scalar) } |
| 61 | + let bytes = tmp.flatMap { |
| 62 | + [UInt8(truncatingIfNeeded: $0), |
| 63 | + UInt8(truncatingIfNeeded: $0 >> 8), |
| 64 | + UInt8(truncatingIfNeeded: $0 >> 16), |
| 65 | + UInt8(truncatingIfNeeded: $0 >> 24)] |
| 66 | + } |
| 67 | + try CSVWriter.lowlevelWriter(on: stream, bytes: bytes, count: bytes.count) |
| 68 | + } |
| 69 | + default: throw Error.unsupported(encoding: encoding) |
| 70 | + } |
| 71 | + } |
| 72 | +} |
| 73 | + |
| 74 | +fileprivate extension CSVWriter { |
| 75 | + /// Writes on the stream the given bytes. |
| 76 | + static func lowlevelWriter(on stream: OutputStream, bytes: UnsafePointer<UInt8>, count: Int, attempts: Int = 2) throws { |
| 77 | + var (distance, remainingAttempts) = (0, attempts) |
| 78 | + |
| 79 | + repeat { |
| 80 | + let written = stream.write(bytes.advanced(by: distance), maxLength: count - distance) |
| 81 | + |
| 82 | + if written > 0 { |
| 83 | + distance += written |
| 84 | + } else if written == 0 { |
| 85 | + remainingAttempts -= 1 |
| 86 | + guard remainingAttempts > 0 else { |
| 87 | + throw Error.streamEmptyWrite(underlyingError: stream.streamError, status: stream.streamStatus, numAttempts: attempts) |
| 88 | + } |
| 89 | + } else { |
| 90 | + throw Error.streamFailed(underlyingError: stream.streamError, status: stream.streamStatus) |
| 91 | + } |
| 92 | + } while distance < count |
| 93 | + } |
| 94 | +} |
| 95 | + |
| 96 | +fileprivate extension CSVWriter.Error { |
| 97 | + /// The given `String.Encoding` is not yet supported by the library. |
| 98 | + /// - parameter encoding: The desired byte representatoion. |
| 99 | + static func unsupported(encoding: String.Encoding) -> CSVError<CSVWriter> { |
| 100 | + .init(.invalidConfiguration, |
| 101 | + reason: "The given encoding is not yet supported by this library", |
| 102 | + help: "Contact the library maintainer", |
| 103 | + userInfo: ["Encoding": encoding]) |
| 104 | + } |
| 105 | + /// Error raised when a Unicode scalar is an invalid ASCII character. |
| 106 | + /// - parameter byte: The byte being decoded from the input data. |
| 107 | + static func invalidASCII(scalar: Unicode.Scalar) -> CSVError<CSVReader> { |
| 108 | + .init(.invalidInput, |
| 109 | + reason: "The Unicode Scalar is not an ASCII character.", |
| 110 | + help: "Make sure the CSV only contains ASCII characters or select a different encoding (e.g. UTF8).", |
| 111 | + userInfo: ["Unicode scalar": scalar]) |
| 112 | + } |
| 113 | + /// Error raised when a UTF8 character cannot be constructed from a Unicode scalar value. |
| 114 | + static func invalidUTF8(scalar: Unicode.Scalar) -> CSVError<CSVReader> { |
| 115 | + .init(.invalidInput, |
| 116 | + reason: "The Unicode Scalar couldn't be decoded as UTF8 characters", |
| 117 | + help: "Make sure the CSV only contains UTF8 characters or select a different encoding.", |
| 118 | + userInfo: ["Unicode scalar": scalar]) |
| 119 | + } |
| 120 | + /// Error raised when a UTF16 character cannot be constructed from a Unicode scalar value. |
| 121 | + static func invalidUTF16(scalar: Unicode.Scalar) -> CSVError<CSVReader> { |
| 122 | + .init(.invalidInput, |
| 123 | + reason: "The Unicode Scalar couldn't be decoded as multibyte UTF16", |
| 124 | + help: "Make sure the CSV only contains UTF16 characters.", |
| 125 | + userInfo: ["Unicode scalar": scalar]) |
| 126 | + } |
| 127 | + /// Error raised when a UTF32 character cannot be constructed from a Unicode scalar value. |
| 128 | + static func invalidUTF32(scalar: Unicode.Scalar) -> CSVError<CSVReader> { |
| 129 | + .init(.invalidInput, |
| 130 | + reason: "The Unicode Scalar couldn't be decoded as multibyte UTF32", |
| 131 | + help: "Make sure the CSV only contains UTF32 characters.", |
| 132 | + userInfo: ["Unicode scalar": scalar]) |
| 133 | + } |
| 134 | + /// |
| 135 | + static func streamFailed(underlyingError: Swift.Error?, status: Stream.Status) -> CSVError<CSVWriter> { |
| 136 | + .init(.streamFailure, underlying: underlyingError, |
| 137 | + reason: "The output stream encountered an error while trying to write encoded bytes", |
| 138 | + help: "Review the underlying error and make sure you have access to the output data (if it is a file)", |
| 139 | + userInfo: ["Status": status]) |
| 140 | + } |
| 141 | + /// |
| 142 | + static func streamEmptyWrite(underlyingError: Swift.Error?, status: Stream.Status, numAttempts: Int) -> CSVError<CSVWriter> { |
| 143 | + .init(.streamFailure, underlying: underlyingError, |
| 144 | + reason: "Several attempts were made to write on the stream, but they were unsuccessful.", |
| 145 | + help: "Review the underlying error (if any) and try again.", |
| 146 | + userInfo: ["Status": status, "Attempts": numAttempts]) |
| 147 | + } |
| 148 | +} |
0 commit comments