-
Notifications
You must be signed in to change notification settings - Fork 5.6k
/
Console.kt
298 lines (263 loc) · 10.6 KB
/
Console.kt
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
/*
* Copyright 2010-2018 JetBrains s.r.o. and Kotlin Programming Language contributors.
* Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file.
*/
@file:JvmName("ConsoleKt")
package kotlin.io
import java.io.InputStream
import java.nio.ByteBuffer
import java.nio.CharBuffer
import java.nio.charset.Charset
import java.nio.charset.CharsetDecoder
import java.nio.charset.CoderResult
/** Prints the given [message] to the standard output stream. */
@kotlin.internal.InlineOnly
public actual inline fun print(message: Any?) {
System.out.print(message)
}
/** Prints the given [message] to the standard output stream. */
@kotlin.internal.InlineOnly
public inline fun print(message: Int) {
System.out.print(message)
}
/** Prints the given [message] to the standard output stream. */
@kotlin.internal.InlineOnly
public inline fun print(message: Long) {
System.out.print(message)
}
/** Prints the given [message] to the standard output stream. */
@kotlin.internal.InlineOnly
public inline fun print(message: Byte) {
System.out.print(message)
}
/** Prints the given [message] to the standard output stream. */
@kotlin.internal.InlineOnly
public inline fun print(message: Short) {
System.out.print(message)
}
/** Prints the given [message] to the standard output stream. */
@kotlin.internal.InlineOnly
public inline fun print(message: Char) {
System.out.print(message)
}
/** Prints the given [message] to the standard output stream. */
@kotlin.internal.InlineOnly
public inline fun print(message: Boolean) {
System.out.print(message)
}
/** Prints the given [message] to the standard output stream. */
@kotlin.internal.InlineOnly
public inline fun print(message: Float) {
System.out.print(message)
}
/** Prints the given [message] to the standard output stream. */
@kotlin.internal.InlineOnly
public inline fun print(message: Double) {
System.out.print(message)
}
/** Prints the given [message] to the standard output stream. */
@kotlin.internal.InlineOnly
public inline fun print(message: CharArray) {
System.out.print(message)
}
/** Prints the given [message] and the line separator to the standard output stream. */
@kotlin.internal.InlineOnly
public actual inline fun println(message: Any?) {
System.out.println(message)
}
/** Prints the given [message] and the line separator to the standard output stream. */
@kotlin.internal.InlineOnly
public inline fun println(message: Int) {
System.out.println(message)
}
/** Prints the given [message] and the line separator to the standard output stream. */
@kotlin.internal.InlineOnly
public inline fun println(message: Long) {
System.out.println(message)
}
/** Prints the given [message] and the line separator to the standard output stream. */
@kotlin.internal.InlineOnly
public inline fun println(message: Byte) {
System.out.println(message)
}
/** Prints the given [message] and the line separator to the standard output stream. */
@kotlin.internal.InlineOnly
public inline fun println(message: Short) {
System.out.println(message)
}
/** Prints the given [message] and the line separator to the standard output stream. */
@kotlin.internal.InlineOnly
public inline fun println(message: Char) {
System.out.println(message)
}
/** Prints the given [message] and the line separator to the standard output stream. */
@kotlin.internal.InlineOnly
public inline fun println(message: Boolean) {
System.out.println(message)
}
/** Prints the given [message] and the line separator to the standard output stream. */
@kotlin.internal.InlineOnly
public inline fun println(message: Float) {
System.out.println(message)
}
/** Prints the given [message] and the line separator to the standard output stream. */
@kotlin.internal.InlineOnly
public inline fun println(message: Double) {
System.out.println(message)
}
/** Prints the given [message] and the line separator to the standard output stream. */
@kotlin.internal.InlineOnly
public inline fun println(message: CharArray) {
System.out.println(message)
}
/** Prints the line separator to the standard output stream. */
@kotlin.internal.InlineOnly
public actual inline fun println() {
System.out.println()
}
/**
* Reads a line of input from the standard input stream and returns it,
* or throws a [RuntimeException] if EOF has already been reached when [readln] is called.
*
* LF or CRLF is treated as the line terminator. Line terminator is not included in the returned string.
*
* The input is decoded using the system default Charset. A [CharacterCodingException] is thrown if input is malformed.
*/
@SinceKotlin("1.6")
public actual fun readln(): String = readlnOrNull() ?: throw ReadAfterEOFException("EOF has already been reached")
/**
* Reads a line of input from the standard input stream and returns it,
* or return `null` if EOF has already been reached when [readlnOrNull] is called.
*
* LF or CRLF is treated as the line terminator. Line terminator is not included in the returned string.
*
* The input is decoded using the system default Charset. A [CharacterCodingException] is thrown if input is malformed.
*/
@SinceKotlin("1.6")
public actual fun readlnOrNull(): String? = readLine()
/**
* Reads a line of input from the standard input stream.
*
* @return the line read or `null` if the input stream is redirected to a file and the end of file has been reached.
*/
fun readLine(): String? = LineReader.readLine(System.`in`, Charset.defaultCharset())
// Singleton object lazy initializes on the first use, internal for tests
internal object LineReader {
private const val BUFFER_SIZE: Int = 32
private lateinit var decoder: CharsetDecoder
private var directEOL = false
private val bytes = ByteArray(BUFFER_SIZE)
private val chars = CharArray(BUFFER_SIZE)
private val byteBuf: ByteBuffer = ByteBuffer.wrap(bytes)
private val charBuf: CharBuffer = CharBuffer.wrap(chars)
private val sb = StringBuilder()
/**
* Reads line from the specified [inputStream] with the given [charset].
* The general design:
* * This function contains only fast path code and all it state is kept in local variables as much as possible.
* * All the slow-path code is moved to separate functions and the call-sequence bytecode is minimized for it.
*/
@Synchronized
fun readLine(inputStream: InputStream, charset: Charset): String? { // charset == null -> use default
if (!::decoder.isInitialized || decoder.charset() != charset) updateCharset(charset)
var nBytes = 0
var nChars = 0
while (true) {
val readByte = inputStream.read()
if (readByte == -1) {
// The result is null only if there was absolutely nothing read
if (sb.isEmpty() && nBytes == 0 && nChars == 0) {
return null
} else {
nChars = decodeEndOfInput(nBytes, nChars) // throws exception if partial char
break
}
} else {
bytes[nBytes++] = readByte.toByte()
}
// With "directEOL" encoding bytes are batched before being decoded all at once
if (readByte == '\n'.code || nBytes == BUFFER_SIZE || !directEOL) {
// Decode the bytes that were read
byteBuf.limit(nBytes) // byteBuf position is always zero
charBuf.position(nChars) // charBuf limit is always BUFFER_SIZE
nChars = decode(false)
// Break when we have decoded end of line
if (nChars > 0 && chars[nChars - 1] == '\n') {
byteBuf.position(0) // reset position for next use
break
}
// otherwise we're going to read more bytes, so compact byteBuf
nBytes = compactBytes()
}
}
// Trim the end of line
if (nChars > 0 && chars[nChars - 1] == '\n') {
nChars--
if (nChars > 0 && chars[nChars - 1] == '\r') nChars--
}
// Fast path for short lines (don't use StringBuilder)
if (sb.isEmpty()) return String(chars, 0, nChars)
// Copy the rest of chars to StringBuilder
sb.append(chars, 0, nChars)
// Build the result
val result = sb.toString()
if (sb.length > BUFFER_SIZE) trimStringBuilder()
sb.setLength(0)
return result
}
// The result is the number of chars in charBuf
private fun decode(endOfInput: Boolean): Int {
while (true) {
val coderResult: CoderResult = decoder.decode(byteBuf, charBuf, endOfInput)
if (coderResult.isError) {
resetAll() // so that next call to readLine starts from clean state
coderResult.throwException()
}
val nChars = charBuf.position()
if (!coderResult.isOverflow) return nChars // has room in buffer -- everything possible was decoded
// overflow (charBuf is full) -- offload everything from charBuf but last char into sb
sb.append(chars, 0, nChars - 1)
charBuf.position(0)
charBuf.limit(BUFFER_SIZE)
charBuf.put(chars[nChars - 1]) // retain last char
}
}
// Slow path -- only on long lines (extra call to decode will be performed)
private fun compactBytes(): Int = with(byteBuf) {
compact()
return position().also { position(0) }
}
// Slow path -- only on end of input
private fun decodeEndOfInput(nBytes: Int, nChars: Int): Int {
byteBuf.limit(nBytes) // byteBuf position is always zero
charBuf.position(nChars) // charBuf limit is always BUFFER_SIZE
return decode(true).also { // throws exception if partial char
// reset decoder and byteBuf for next use
decoder.reset()
byteBuf.position(0)
}
}
// Slow path -- only on charset change
private fun updateCharset(charset: Charset) {
decoder = charset.newDecoder()
// try decoding ASCII line separator to see if this charset (like UTF-8) encodes it directly
byteBuf.clear()
charBuf.clear()
byteBuf.put('\n'.code.toByte())
byteBuf.flip()
decoder.decode(byteBuf, charBuf, false)
directEOL = charBuf.position() == 1 && charBuf.get(0) == '\n'
resetAll()
}
// Slow path -- only on exception in decoder and on charset change
private fun resetAll() {
decoder.reset()
byteBuf.position(0)
sb.setLength(0)
}
// Slow path -- only on long lines
private fun trimStringBuilder() {
sb.setLength(BUFFER_SIZE)
sb.trimToSize()
}
}