Kotlin conversion: UTF8Util

This commit is contained in:
Paul Schaub 2023-10-31 15:18:48 +01:00
parent e1a6ffd07a
commit 94b428ef62
Signed by: vanitasvitae
GPG key ID: 62BEE9264BF17311
3 changed files with 37 additions and 45 deletions

View file

@ -1,37 +0,0 @@
// SPDX-FileCopyrightText: 2022 Paul Schaub <vanitasvitae@fsfe.org>
//
// SPDX-License-Identifier: Apache-2.0
package sop.util;
import java.nio.ByteBuffer;
import java.nio.CharBuffer;
import java.nio.charset.CharacterCodingException;
import java.nio.charset.Charset;
import java.nio.charset.CharsetDecoder;
import java.nio.charset.CodingErrorAction;
public class UTF8Util {
public static final Charset UTF8 = Charset.forName("UTF8");
private static final CharsetDecoder UTF8Decoder = UTF8
.newDecoder()
.onUnmappableCharacter(CodingErrorAction.REPORT)
.onMalformedInput(CodingErrorAction.REPORT);
/**
* Detect non-valid UTF8 data.
*
* @see <a href="https://stackoverflow.com/a/1471193">ante on StackOverflow</a>
* @param data utf-8 encoded bytes
*
* @return decoded string
* @throws CharacterCodingException if the input data does not resemble UTF8
*/
public static String decodeUTF8(byte[] data)
throws CharacterCodingException {
ByteBuffer byteBuffer = ByteBuffer.wrap(data);
CharBuffer charBuffer = UTF8Decoder.decode(byteBuffer);
return charBuffer.toString();
}
}

View file

@ -1,8 +0,0 @@
// SPDX-FileCopyrightText: 2021 Paul Schaub <vanitasvitae@fsfe.org>
//
// SPDX-License-Identifier: Apache-2.0
/**
* Utility classes.
*/
package sop.util;

View file

@ -0,0 +1,37 @@
// SPDX-FileCopyrightText: 2023 Paul Schaub <vanitasvitae@fsfe.org>
//
// SPDX-License-Identifier: Apache-2.0
package sop.util
import java.nio.ByteBuffer
import java.nio.charset.Charset
import java.nio.charset.CodingErrorAction
class UTF8Util {
companion object {
@JvmField val UTF8: Charset = Charset.forName("UTF8")
@JvmStatic
private val UTF8Decoder =
UTF8.newDecoder()
.onUnmappableCharacter(CodingErrorAction.REPORT)
.onMalformedInput(CodingErrorAction.REPORT)
/**
* Detect non-valid UTF8 data.
*
* @param data utf-8 encoded bytes
* @return decoded string
* @throws CharacterCodingException if the input data does not resemble UTF8
* @see [ante on StackOverflow](https://stackoverflow.com/a/1471193)
*/
@JvmStatic
@Throws(CharacterCodingException::class)
fun decodeUTF8(data: ByteArray): String {
val byteBuffer = ByteBuffer.wrap(data)
val charBuffer = UTF8Decoder.decode(byteBuffer)
return charBuffer.toString()
}
}
}