Skip to content

Commit

Permalink
unicode scalarを読むことにした
Browse files Browse the repository at this point in the history
  • Loading branch information
Gurrium committed Mar 15, 2023
1 parent 31d1555 commit a8e0312
Show file tree
Hide file tree
Showing 3 changed files with 7 additions and 78 deletions.
3 changes: 3 additions & 0 deletions Package.swift
Expand Up @@ -5,6 +5,9 @@ import PackageDescription

let package = Package(
name: "SwiftKilo",
platforms: [
.macOS(.v12)
],
dependencies: [
// Dependencies declare other packages that this package depends on.
// .package(url: /* package url */, from: "1.0.0"),
Expand Down
41 changes: 3 additions & 38 deletions Sources/SwiftKilo/SwiftKilo.swift
Expand Up @@ -19,27 +19,10 @@ public class SwiftKilo {
private func main() async throws {
enableRawMode()

let keyPath = \String.count

let shouldWaitFlag = Container(content: true)
let iterator = Container(content: FileHandle.standardInput.bytes.characters.makeAsyncIterator())

let readTask = Task.detached {
return try await iterator.content
}

let timeoutTask = Task.detached {
while await shouldWaitFlag.content {
try await Task.sleep(nanoseconds: 1_000)
}

for try await scalar in FileHandle.standardInput.bytes.unicodeScalars {
guard scalar != "q" else { break }

}

for try await character in FileHandle.standardInput.bytes.characters {
guard character != "q" else { break }

print(character)
print(scalar)
}
}

Expand All @@ -56,21 +39,3 @@ public class SwiftKilo {
tcsetattr(STDIN_FILENO, TCSAFLUSH, &origTermios)
}
}

actor Container<T> {
var content: T

init(content: T) {
self.content = content
}

func set(_ content: T) {
self.content = content
}
}

extension Container where T: AsyncIteratorProtocol {
func next() async throws -> T.Element? {
try await content.next()
}
}
41 changes: 1 addition & 40 deletions Tests/SwiftKiloTests/SwiftKiloTests.swift
Expand Up @@ -2,43 +2,4 @@ import XCTest
import System
@testable import SwiftKilo

final class SwiftKiloTests: XCTestCase {
func testExample() async throws {
let (inHandle, outHandle): (FileHandle, FileHandle) = {
let pipe = Pipe()
return (pipe.fileHandleForWriting, pipe.fileHandleForReading)
}()

Task.detached {
try await Task.sleep(nanoseconds: 1_000_000)
try inHandle.write(contentsOf: [0])
try inHandle.write(contentsOf: [1])
try inHandle.write(contentsOf: [2])
try inHandle.write(contentsOf: [3])
}

let testTask = Task {
var bytes = [UInt8]()

for try await byte in outHandle.bytes {
bytes.append(byte)

if bytes == [0, 1, 2, 3] {
break
}
}
}

let timeoutTask = Task {
try await Task.sleep(nanoseconds: 5_000_000)
testTask.cancel()
}

do {
_ = try await testTask.value
timeoutTask.cancel()
} catch {
XCTFail("timeout")
}
}
}
final class SwiftKiloTests: XCTestCase {}

0 comments on commit a8e0312

Please sign in to comment.