Created
December 18, 2020 13:48
-
-
Save Que20/68f1d641d3bcca4ea95341b1501fd113 to your computer and use it in GitHub Desktop.
This file contains 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
func input(_ block: (UInt8) -> (Bool)) { | |
func initStruct<S>() -> S { | |
let struct_pointer = UnsafeMutablePointer<S>.allocate(capacity: 1) | |
let struct_memory = struct_pointer.pointee | |
struct_pointer.deallocate() | |
return struct_memory | |
} | |
func enableRawMode(fileHandle: FileHandle) -> termios { | |
var raw: termios = initStruct() | |
tcgetattr(fileHandle.fileDescriptor, &raw) | |
let original = raw | |
raw.c_lflag &= ~(UInt(ECHO | ICANON)) | |
tcsetattr(fileHandle.fileDescriptor, TCSAFLUSH, &raw); | |
return original | |
} | |
func restoreRawMode(fileHandle: FileHandle, originalTerm: termios) { | |
var term = originalTerm | |
tcsetattr(fileHandle.fileDescriptor, TCSAFLUSH, &term); | |
} | |
let stdIn = FileHandle.standardInput | |
let originalTerm = enableRawMode(fileHandle: stdIn) | |
var char: UInt8 = 0 | |
while read(stdIn.fileDescriptor, &char, 1) == 1 { | |
let keepListening = block(char) | |
if !keepListening { | |
break | |
} | |
} | |
restoreRawMode(fileHandle: stdIn, originalTerm: originalTerm) | |
} | |
// Usage | |
input { (inputValue) -> (Bool) in | |
// return true to keep listening | |
return true | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment