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
@@ -111,6 +111,15 @@ public actual inline fun String.toUpperCase(): String = (this as java.lang.Strin
@kotlin.internal.InlineOnly
public actual inline fun String.toLowerCase(): String = (this as java.lang.String).toLowerCase()
/**
* Concatenates characters in this [CharArray] into a String.
*/
@SinceKotlin("1.3")
@ExperimentalStdlibApi
public actual fun CharArray.concatToString(): String {
return String(this)
}
/**
* Concatenates characters in this [CharArray] or its subrange into a String.
*
@@ -145,6 +154,17 @@ public actual fun String.toCharArray(startIndex: Int = 0, endIndex: Int = this.l
return toCharArray(CharArray(endIndex - startIndex), 0, startIndex, endIndex)
}
/**
* 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 String(this)
}
/**
* Decodes a string from the bytes in UTF-8 encoding in this array or its subrange.
*
@@ -177,6 +197,17 @@ public actual fun ByteArray.decodeToString(
return decoder.decode(ByteBuffer.wrap(this, startIndex, endIndex - startIndex)).toString()
}
/**
* 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 this.toByteArray(Charsets.UTF_8)
}
/**
* Encodes this string or its substring to an array of bytes in UTF-8 encoding.
*
@@ -215,10 +246,10 @@ public actual fun String.encodeToByteArray(
}
/**
* Returns a new character array containing the characters from this string.
* Returns a [CharArray] containing characters of this string.
*/
@kotlin.internal.InlineOnly
public inline fun String.toCharArray(): CharArray = (this as java.lang.String).toCharArray()
public actual inline fun String.toCharArray(): CharArray = (this as java.lang.String).toCharArray()
/**
* Copies characters from this string into the [destination] character array and returns that array.