Permalink
Browse files

Good base level going before Chapter 2 of the tutorial.

  • Loading branch information...
sgoodwin committed Apr 15, 2017
0 parents commit d546e2b18dca463149b7368c5fe0a66891c5186c
Showing with 88 additions and 0 deletions.
  1. +4 −0 .gitignore
  2. +7 −0 Package.swift
  3. +18 −0 Sources/CChar+Literal.swift
  4. +59 −0 Sources/main.swift
@@ -0,0 +1,4 @@
.DS_Store
/.build
/Packages
/*.xcodeproj
@@ -0,0 +1,7 @@
// swift-tools-version:3.1
import PackageDescription
let package = Package(
name: "SwiftKilo"
)
@@ -0,0 +1,18 @@
extension CChar: ExpressibleByStringLiteral {
public typealias StringLiteralType = String
public typealias ExtendedGraphemeClusterLiteralType = Character
public typealias UnicodeScalarLiteralType = UnicodeScalar
public init(stringLiteral value: String) {
self.init(value.utf8CString[0])
}
public init(extendedGraphemeClusterLiteral value: Character) {
self.init(stringLiteral: String(value))
}
public init(unicodeScalarLiteral value: UnicodeScalar) {
self.init(stringLiteral: String(value))
}
}
@@ -0,0 +1,59 @@
import Darwin
var originalTermios = termios()
func control(_ key: CChar) -> CChar {
return key & 0x1f
}
func die(_ s: String) {
perror(s)
exit(1)
}
func disableRawMode() {
if tcsetattr(STDIN_FILENO, TCSAFLUSH, &originalTermios) == -1 {
die("tcsetattr")
}
}
func enableRawMode() {
if tcgetattr(STDIN_FILENO, &originalTermios) == -1 {
die("tcgetattr")
}
atexit(disableRawMode)
var raw = originalTermios
raw.c_iflag &= ~(tcflag_t(ICRNL | IXON))
raw.c_oflag &= ~(tcflag_t(OPOST))
raw.c_lflag &= ~(tcflag_t(ECHO | ICANON | IEXTEN | ISIG))
raw.c_cc.6 = 0 // VMIN
raw.c_cc.5 = 1 // VTIME
if tcsetattr(STDIN_FILENO, TCSAFLUSH, &raw) == -1 {
die("tcsetattr")
}
}
func main() {
enableRawMode()
while true {
var c:CChar = CChar()
if read(STDIN_FILENO, &c, 1) == -1 {
die("read")
}
if iscntrl(Int32(c)) == 1 {
print("control char \(c)", terminator: "\r\n")
} else {
print("printable char \(UnicodeScalar(UInt32(c))!.escaped(asASCII: true))", terminator: "\r\n")
}
if c == control("q") {
break
}
}
}
main()

0 comments on commit d546e2b

Please sign in to comment.