In Kotlin multiplatform, how can I read line separator's length?
Asked Answered
W

1

0

On JVM I can use the following:

fun lineSeparatorLength(): Int = System.getProperty("line.separator").length

Can someone show me how to implement the same for Native/Desktop and JS?

Windowlight answered 13/8 at 20:28 Comment(2)
This is a duplicate of #70460531. Alas, that question has no (correct) answer.Microhenry
@Microhenry the answer that got -4 points in the question you linked is actually partially correct. In Kotlin/Native, println calls a C++ function konan::consoleWriteUtf8("\n", 1); and the single character '\n' gets translated on Windows to \r\n deep inside the C++ standard library (or the C library that the C++ library calls).Ogdan
O
0

You need to write this in the common module:

val lineSeparatorLength = lineSeparator.length

and define lineSeparator in platform-specific modules:

In JVM:

val lineSeparator = System.lineSeparator()

On the remaining platforms, it's actually as simple as:

val lineSeparator = "\n"

Explanation:

In Kotlin/Native, all output is forwarded to an internal library written in C++. For example, see the implementation of println(), which calls Kotlin_io_Console_println0. This is a C++ function that simply outputs "\n" to standard output.

The way it works is that in C++ (and C), files can be opened for writing in either "binary mode" or "text mode". In text mode (the default mode for stdout), the C++ and C library implementations take care of any necessary translation of newlines. So whereas in Kotlin and Java, if we want to output a newline, we need to output System.lineSeparator(), by contrast in C++ and C we simply output "\n" and the library implementation takes care of it for us.

The Kotlin/JS situation is similar: println() simply outputs "\n".

Now what if you want to know how many bytes will be taken up by the line separator?

So far, we've seen that if we just want to know how many characters a line separator takes in a Kotlin string, the answer for Native and JS is just 1. But if we want to know how many actual characters will be ultimately output, there is no portable way of finding out; you will have to have a Windows-specific definition for the newline character being "\r\n". All other current platforms use "\n" (I won't include MacOS 9, which uses "\r", because that's ancient and no longer supported).

Ogdan answered 14/8 at 9:51 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.