Skip to content

Instantly share code, notes, and snippets.

@Que20
Created December 18, 2020 13:48
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Que20/68f1d641d3bcca4ea95341b1501fd113 to your computer and use it in GitHub Desktop.
Save Que20/68f1d641d3bcca4ea95341b1501fd113 to your computer and use it in GitHub Desktop.
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