Introduce Common readln() and readlnOrNull() top-level functions #KT-48456
This commit is contained in:
committed by
Space
parent
14b66872b5
commit
97eb28144f
@@ -13,6 +13,8 @@
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
#include <cstdio>
|
||||
|
||||
#include "KAssert.h"
|
||||
#include "Memory.h"
|
||||
#include "Natives.h"
|
||||
@@ -67,4 +69,35 @@ OBJ_GETTER0(Kotlin_io_Console_readLine) {
|
||||
RETURN_RESULT_OF(CreateStringFromCString, data);
|
||||
}
|
||||
|
||||
OBJ_GETTER0(Kotlin_io_Console_readlnOrNull) {
|
||||
KStdVector<char> data;
|
||||
data.reserve(16);
|
||||
bool isEOF = false;
|
||||
bool isError = false;
|
||||
{
|
||||
kotlin::ThreadStateGuard guard(kotlin::ThreadState::kNative);
|
||||
while (true) {
|
||||
int result = fgetc(stdin);
|
||||
|
||||
if (result == EOF || result == '\n') {
|
||||
isEOF = (result == EOF);
|
||||
isError = (ferror(stdin) != 0);
|
||||
break;
|
||||
}
|
||||
|
||||
data.push_back(result);
|
||||
}
|
||||
}
|
||||
if (isError) {
|
||||
ThrowIllegalStateException();
|
||||
}
|
||||
if (!isEOF && !data.empty() && data.back() == '\r') { // CRLF
|
||||
data.pop_back();
|
||||
}
|
||||
if (data.empty() && isEOF) {
|
||||
RETURN_OBJ(nullptr);
|
||||
}
|
||||
RETURN_RESULT_OF(StringFromUtf8Buffer, data.data(), data.size());
|
||||
}
|
||||
|
||||
} // extern "C"
|
||||
|
||||
@@ -29,6 +29,29 @@ public actual fun println(message: Any?) {
|
||||
@GCUnsafeCall("Kotlin_io_Console_println0")
|
||||
public actual external fun 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 interpreted as UTF-8. Invalid bytes are replaced by the replacement character '\uFFFD'.
|
||||
*/
|
||||
@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 interpreted as UTF-8. Invalid bytes are replaced by the replacement character '\uFFFD'.
|
||||
*/
|
||||
@SinceKotlin("1.6")
|
||||
@GCUnsafeCall("Kotlin_io_Console_readlnOrNull")
|
||||
public actual external fun readlnOrNull(): String?
|
||||
|
||||
/**
|
||||
* Reads a line of input from the standard input stream.
|
||||
*
|
||||
|
||||
Reference in New Issue
Block a user