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
@@ -74,6 +74,52 @@ 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 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")
@Suppress("ACTUAL_FUNCTION_WITH_DEFAULT_ARGUMENTS")
@ExperimentalStdlibApi
public actual fun ByteArray.decodeToString(
startIndex: Int = 0,
endIndex: Int = this.size,
throwOnInvalidSequence: Boolean = false
): String {
AbstractList.checkBoundsIndexes(startIndex, endIndex, this.size)
return decodeUtf8(this, startIndex, endIndex, throwOnInvalidSequence)
}
/**
* 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")
@Suppress("ACTUAL_FUNCTION_WITH_DEFAULT_ARGUMENTS")
@ExperimentalStdlibApi
public actual fun String.encodeToByteArray(
startIndex: Int = 0,
endIndex: Int = this.length,
throwOnInvalidSequence: Boolean = false
): ByteArray {
AbstractList.checkBoundsIndexes(startIndex, endIndex, length)
return encodeUtf8(this, startIndex, endIndex, throwOnInvalidSequence)
}
/**
* Returns a copy of this string converted to upper case using the rules of the default locale.
*