From 93481d2463d355a36ffcd0f6f7ef86013dd22cf7 Mon Sep 17 00:00:00 2001 From: Rikiya Yamamoto Date: Wed, 18 Nov 2020 00:02:02 +0900 Subject: [PATCH] add Shift-JIS encoding support. --- .../writer/internal/WriterEncoder.swift | 24 +++++++++++++++++++ 1 file changed, 24 insertions(+) diff --git a/sources/imperative/writer/internal/WriterEncoder.swift b/sources/imperative/writer/internal/WriterEncoder.swift index ca0e3ce..e6e9fe5 100644 --- a/sources/imperative/writer/internal/WriterEncoder.swift +++ b/sources/imperative/writer/internal/WriterEncoder.swift @@ -68,11 +68,28 @@ internal extension CSVWriter { } try CSVWriter._streamWrite(on: stream, bytes: bytes, count: bytes.count) } + case .shiftJIS: + return { [unowned stream] (scalar) in + guard let tmp = String(scalar).data(using: .shiftJIS) else { throw Error._invalidShiftJIS(scalar: scalar) } + guard let bytes = tmp.encodedHexadecimals else { throw Error._invalidShiftJIS(scalar: scalar) } + try CSVWriter._streamWrite(on: stream, bytes: bytes, count: bytes.count) + } default: throw Error._unsupported(encoding: encoding) } } } +extension Data { + var encodedHexadecimals: [UInt8]? { + let responseValues = self.withUnsafeBytes({ (pointer: UnsafeRawBufferPointer) -> [UInt8] in + let unsafeBufferPointer = pointer.bindMemory(to: UInt8.self) + let unsafePointer = unsafeBufferPointer.baseAddress! + return [UInt8](UnsafeBufferPointer(start: unsafePointer, count: self.count)) + }) + return responseValues + } +} + fileprivate extension CSVWriter { /// Writes on the stream the given bytes. /// - precondition: `count` is always greater than zero. @@ -142,6 +159,13 @@ fileprivate extension CSVWriter.Error { help: "Make sure the CSV only contains UTF32 characters.", userInfo: ["Unicode scalar": scalar]) } + /// Error raised when a Shift-JIS character cannot be constructed from a Unicode scalar value. + static func _invalidShiftJIS(scalar: Unicode.Scalar) -> CSVError { + .init(.invalidInput, + reason: "The Unicode Scalar couldn't be encoded to multibyte Shift-JIS", + help: "Make sure the CSV only contains Shift-JIS characters.", + userInfo: ["Unicode scalar": scalar]) + } /// Error raised when the output stream failed to write some bytes. static func _streamFailed(error: Swift.Error?, status: Stream.Status) -> CSVError { .init(.streamFailure, underlying: error,