Skip to content

Commit

Permalink
Merge pull request #29 from rkyymmt/master
Browse files Browse the repository at this point in the history
Add Shift-JIS encoding support
  • Loading branch information
dehesa committed Nov 22, 2020
2 parents 9e2583a + 93481d2 commit bef29ba
Showing 1 changed file with 24 additions and 0 deletions.
24 changes: 24 additions & 0 deletions sources/imperative/writer/internal/WriterEncoder.swift
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down Expand Up @@ -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<CSVWriter> {
.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<CSVWriter> {
.init(.streamFailure, underlying: error,
Expand Down

0 comments on commit bef29ba

Please sign in to comment.