Created
August 20, 2017 13:41
-
-
Save sonsongithub/5d8f048fb3fb627ef4e294f5846b146d to your computer and use it in GitHub Desktop.
Get lines from a binary data of strings.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| extension Data { | |
| /** | |
| 生のテキストデータをバイナリのまま改行コードを探し,改行コードごとにバイトストリームを切り分けて,テキストにデコードする. | |
| 戻り値はテキストのArrayになる. | |
| - returns: 文字列のArray. | |
| */ | |
| func lines() throws -> [String] { | |
| return try self.withUnsafeBytes({ (pointer: UnsafePointer<UInt8>) -> [String] in | |
| let buffer = [UInt8](UnsafeBufferPointer(start: pointer, count: self.count)) | |
| var lines: [String] = [] | |
| let newline = UInt8(ascii: "\n") | |
| var begin = buffer.startIndex | |
| while let end = buffer.suffix(from: begin).index(of: newline).map({ buffer.index(after: $0) }) { | |
| defer { begin = end } | |
| let beforeNewline = buffer.index(before: end) | |
| guard beforeNewline - begin > 0 else { continue } | |
| let lineBuffer = buffer[begin..<beforeNewline] | |
| let data = Data(bytes: lineBuffer) | |
| if let line = String(data: data, encoding: .shiftJIS) { | |
| lines.append(line) | |
| } | |
| } | |
| return lines | |
| }) | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment