Scoop API

scoop:scoop.terminal:0.1.0

src/internal/platform/input.scoop

Selected production source · src/internal/platform/input.scoop

1package scoop.terminal.internal.platform
3import scoop.platform.memory.NativeByteBuffer
4import scoop.platform.system.*
5import scoop.time.Duration
7internal fun TerminalHandle.waitInput(timeout: Duration?): Int =
8 withPointer {
9 pointer -> @Unsafe
10 {
11 val result = nativeWait(pointer, waitMilliseconds(timeout))
12 val ready = result.value
13 if (ready < 0) {
14 if (terminalError(result.error).kind == PlatformErrorKind.Interrupted)
15 return@withPointer 0
16 failTerminal("wait terminal input", result.error)
17 }
18 return@withPointer ready
19 }
20 }
22internal fun TerminalHandle.readInput(hungUp: Boolean): Array<Byte>? =
23 withPointer {
24 pointer -> NativeByteBuffer.allocate(4096L).use {
25 buffer -> @Unsafe
26 {
27 val borrow = buffer.borrowWritable(4096L)
28 val result = nativeRead(pointer, borrow.pointer()!!, borrow.length, hungUp)
29 val count = result.value
30 borrow.complete(
31 if (count < 0L)
32 0L
33 else
34 count
35 )
36 if (count < 0L) {
37 val kind = terminalError(result.error).kind
38 if (
39 kind ==
40 PlatformErrorKind.Interrupted ||
41 kind ==
42 PlatformErrorKind.WouldBlock
43 )
44 return@use None
45 failTerminal("read terminal input", result.error)
46 }
47 return@use Some(buffer.readBytes(count))
48 }
49 }
50 }
52private fun waitMilliseconds(timeout: Duration?): Int {
53 if (timeout == None)
54 return -1
55 val duration = timeout!!
56 if (duration.floorSeconds > 2147483L)
57 return Int.MAX_VALUE
58 val milliseconds =
59 duration.floorSeconds * 1000L + (duration.nanosecondsOfSecond.toLong() + 999999L) / 1000000L
60 return if (milliseconds > Int.MAX_VALUE.toLong())
61 Int.MAX_VALUE
62 else
63 milliseconds.toInt()