Kotlin conversion: Ready

This commit is contained in:
Paul Schaub 2023-10-31 13:16:37 +01:00
parent 9dbb93e13d
commit e6562cecff
Signed by: vanitasvitae
GPG Key ID: 62BEE9264BF17311
2 changed files with 49 additions and 45 deletions

View File

@ -1,45 +0,0 @@
// SPDX-FileCopyrightText: 2021 Paul Schaub <vanitasvitae@fsfe.org>
//
// SPDX-License-Identifier: Apache-2.0
package sop;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
public abstract class Ready {
/**
* Write the data to the provided output stream.
*
* @param outputStream output stream
* @throws IOException in case of an IO error
*/
public abstract void writeTo(OutputStream outputStream) throws IOException;
/**
* Return the data as a byte array by writing it to a {@link ByteArrayOutputStream} first and then returning
* the array.
*
* @return data as byte array
* @throws IOException in case of an IO error
*/
public byte[] getBytes() throws IOException {
ByteArrayOutputStream bytes = new ByteArrayOutputStream();
writeTo(bytes);
return bytes.toByteArray();
}
/**
* Return an input stream containing the data.
*
* @return input stream
* @throws IOException in case of an IO error
*/
public InputStream getInputStream() throws IOException {
return new ByteArrayInputStream(getBytes());
}
}

View File

@ -0,0 +1,49 @@
// SPDX-FileCopyrightText: 2023 Paul Schaub <vanitasvitae@fsfe.org>
//
// SPDX-License-Identifier: Apache-2.0
package sop
import java.io.ByteArrayInputStream
import java.io.ByteArrayOutputStream
import java.io.IOException
import java.io.InputStream
import java.io.OutputStream
/** Abstract class that encapsulates output data, waiting to be consumed. */
abstract class Ready {
/**
* Write the data to the provided output stream.
*
* @param outputStream output stream
* @throws IOException in case of an IO error
*/
@Throws(IOException::class) abstract fun writeTo(outputStream: OutputStream)
/**
* Return the data as a byte array by writing it to a [ByteArrayOutputStream] first and then
* returning the array.
*
* @return data as byte array
* @throws IOException in case of an IO error
*/
val bytes: ByteArray
@Throws(IOException::class)
get() =
ByteArrayOutputStream()
.let {
writeTo(it)
it
}
.toByteArray()
/**
* Return an input stream containing the data.
*
* @return input stream
* @throws IOException in case of an IO error
*/
val inputStream: InputStream
@Throws(IOException::class) get() = ByteArrayInputStream(bytes)
}