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
@@ -36,6 +36,19 @@ public actual fun String(chars: CharArray, offset: Int, length: Int): String {
return result
}
/**
* Concatenates characters in this [CharArray] into a String.
*/
@SinceKotlin("1.3")
@ExperimentalStdlibApi
public actual fun CharArray.concatToString(): String {
var result = ""
for (char in this) {
result += char
}
return result
}
/**
* Concatenates characters in this [CharArray] or its subrange into a String.
*
@@ -57,6 +70,15 @@ public actual fun CharArray.concatToString(startIndex: Int = 0, endIndex: Int =
return result
}
/**
* Returns a [CharArray] containing characters of this string.
*/
@SinceKotlin("1.3")
@ExperimentalStdlibApi
public actual fun String.toCharArray(): CharArray {
return CharArray(length) { get(it) }
}
/**
* Returns a [CharArray] containing characters of this string or its substring.
*
@@ -74,6 +96,17 @@ public actual fun String.toCharArray(startIndex: Int = 0, endIndex: Int = this.l
return CharArray(endIndex - startIndex) { get(startIndex + it) }
}
/**
* 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 actual fun ByteArray.decodeToString(): String {
return decodeUtf8(this, 0, size, false)
}
/**
* Decodes a string from the bytes in UTF-8 encoding in this array or its subrange.
*
@@ -97,6 +130,17 @@ public actual fun ByteArray.decodeToString(
return decodeUtf8(this, startIndex, endIndex, throwOnInvalidSequence)
}
/**
* 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 actual fun String.encodeToByteArray(): ByteArray {
return encodeUtf8(this, 0, length, false)
}
/**
* Encodes this string or its substring to an array of bytes in UTF-8 encoding.
*