Implement String to/from ByteArray conversion (KT-24810)

This commit is contained in:
Abduqodiri Qurbonzoda
2019-04-11 03:12:29 +03:00
parent 81d2d3cb6a
commit c8a4fa58cd
15 changed files with 844 additions and 7 deletions
@@ -82,6 +82,13 @@ expect enum class RegexOption {
MULTILINE
}
/**
* The exception thrown when a character encoding or decoding error occurs.
*/
@SinceKotlin("1.3")
@ExperimentalStdlibApi
public expect open class CharacterCodingException() : Exception
// From char.kt
@@ -135,6 +142,45 @@ public expect fun CharArray.concatToString(startIndex: Int = 0, endIndex: Int =
@ExperimentalStdlibApi
public expect fun String.toCharArray(startIndex: Int = 0, endIndex: Int = this.length): CharArray
/**
* Decodes a string from the bytes in UTF-8 encoding in this array or its subrange.
*
* @param startIndex the beginning (inclusive) of the subrange to decode, 0 by default.
* @param endIndex the end (exclusive) of the subrange to decode, size of this array by default.
* @param throwOnInvalidSequence specifies whether to throw an exception on malformed byte sequence or replace it by the replacement char `\uFFFD`.
*
* @throws IndexOutOfBoundsException if [startIndex] is less than zero or [endIndex] is greater than the size of this array.
* @throws IllegalArgumentException if [startIndex] is greater than [endIndex].
* @throws CharacterCodingException if the byte array contains malformed UTF-8 byte sequence and [throwOnInvalidSequence] is true.
*/
@SinceKotlin("1.3")
@ExperimentalStdlibApi
public expect fun ByteArray.decodeToString(
startIndex: Int = 0,
endIndex: Int = this.size,
throwOnInvalidSequence: Boolean = false
): String
/**
* Encodes this string or its substring to an array of bytes in UTF-8 encoding.
*
* @param startIndex the beginning (inclusive) of the substring to encode, 0 by default.
* @param endIndex the end (exclusive) of the substring to encode, length of this string by default.
* @param throwOnInvalidSequence specifies whether to throw an exception on malformed char sequence or replace.
*
* @throws IndexOutOfBoundsException if [startIndex] is less than zero or [endIndex] is greater than the length of this string.
* @throws IllegalArgumentException if [startIndex] is greater than [endIndex].
* @throws CharacterCodingException if this string contains malformed char sequence and [throwOnInvalidSequence] is true.
*/
@SinceKotlin("1.3")
@ExperimentalStdlibApi
public expect fun String.encodeToByteArray(
startIndex: Int = 0,
endIndex: Int = this.length,
throwOnInvalidSequence: Boolean = false
): ByteArray
internal expect fun String.nativeIndexOf(str: String, fromIndex: Int): Int
internal expect fun String.nativeLastIndexOf(str: String, fromIndex: Int): Int