scoop:scoop.terminal:0.1.0
src/internal/platform/input.scoop
Selected production source · src/internal/platform/input.scoop
1
package scoop.terminal.internal.platform3
import scoop.platform.memory.NativeByteBuffer4
import scoop.platform.system.*5
import scoop.time.Duration7
internal fun TerminalHandle.waitInput(timeout: Duration?): Int =8
withPointer {9
pointer -> @Unsafe10
{11
val result = nativeWait(pointer, waitMilliseconds(timeout))12
val ready = result.value13
if (ready < 0) {14
if (terminalError(result.error).kind == PlatformErrorKind.Interrupted)15
return@withPointer 016
failTerminal("wait terminal input", result.error)17
}18
return@withPointer ready19
}20
}22
internal fun TerminalHandle.readInput(hungUp: Boolean): Array<Byte>? =23
withPointer {24
pointer -> NativeByteBuffer.allocate(4096L).use {25
buffer -> @Unsafe26
{27
val borrow = buffer.borrowWritable(4096L)28
val result = nativeRead(pointer, borrow.pointer()!!, borrow.length, hungUp)29
val count = result.value30
borrow.complete(31
if (count < 0L)32
0L33
else34
count35
)36
if (count < 0L) {37
val kind = terminalError(result.error).kind38
if (39
kind ==40
PlatformErrorKind.Interrupted ||41
kind ==42
PlatformErrorKind.WouldBlock43
)44
return@use None45
failTerminal("read terminal input", result.error)46
}47
return@use Some(buffer.readBytes(count))48
}49
}50
}52
private fun waitMilliseconds(timeout: Duration?): Int {53
if (timeout == None)54
return -155
val duration = timeout!!56
if (duration.floorSeconds > 2147483L)57
return Int.MAX_VALUE58
val milliseconds =59
duration.floorSeconds * 1000L + (duration.nanosecondsOfSecond.toLong() + 999999L) / 1000000L60
return if (milliseconds > Int.MAX_VALUE.toLong())61
Int.MAX_VALUE62
else63
milliseconds.toInt()64
}