Add simplified overloads of String<->ByteArray/CharArray conversions

These overloads cover the most common cases of conversion of the entire
String or Byte/CharArray, avoiding extra index check and branching.

#KT-24810, KT-29265
This commit is contained in:
Ilya Gorbunov
2019-05-07 05:35:20 +03:00
parent f9c12db3b5
commit 2c26dc3af6
4 changed files with 112 additions and 2 deletions
@@ -116,6 +116,13 @@ public expect fun String(chars: CharArray): String
@SinceKotlin("1.2")
public expect fun String(chars: CharArray, offset: Int, length: Int): String
/**
* Concatenates characters in this [CharArray] into a String.
*/
@SinceKotlin("1.3")
@ExperimentalStdlibApi
public expect fun CharArray.concatToString(): String
/**
* Concatenates characters in this [CharArray] or its subrange into a String.
*
@@ -129,6 +136,13 @@ public expect fun String(chars: CharArray, offset: Int, length: Int): String
@ExperimentalStdlibApi
public expect fun CharArray.concatToString(startIndex: Int = 0, endIndex: Int = this.size): String
/**
* Returns a [CharArray] containing characters of this string.
*/
@SinceKotlin("1.3")
@ExperimentalStdlibApi
public expect fun String.toCharArray(): CharArray
/**
* Returns a [CharArray] containing characters of this string or its substring.
*
@@ -142,6 +156,15 @@ 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.
*
* Malformed byte sequences are replaced by the replacement char `\uFFFD`.
*/
@SinceKotlin("1.3")
@ExperimentalStdlibApi
public expect fun ByteArray.decodeToString(): String
/**
* Decodes a string from the bytes in UTF-8 encoding in this array or its subrange.
*
@@ -161,6 +184,15 @@ public expect fun ByteArray.decodeToString(
throwOnInvalidSequence: Boolean = false
): String
/**
* Encodes this string to an array of bytes in UTF-8 encoding.
*
* Any malformed char sequence is replaced by the replacement byte sequence.
*/
@SinceKotlin("1.3")
@ExperimentalStdlibApi
public expect fun String.encodeToByteArray(): ByteArray
/**
* Encodes this string or its substring to an array of bytes in UTF-8 encoding.
*