71 lines
2.5 KiB
Java
71 lines
2.5 KiB
Java
package eu.mikroskeem.uurimustoo.algoritmidetest.algoritmid;
|
|
|
|
import eu.mikroskeem.shuriken.common.SneakyThrow;
|
|
|
|
import java.io.ByteArrayInputStream;
|
|
import java.io.ByteArrayOutputStream;
|
|
import java.io.IOException;
|
|
import java.io.InputStream;
|
|
import java.io.OutputStream;
|
|
|
|
/**
|
|
* @author Mark Vainomaa
|
|
*/
|
|
public abstract class AbstractAlgorithm {
|
|
public abstract String getName();
|
|
|
|
public byte[] compress(byte[] input) {
|
|
try {
|
|
ByteArrayInputStream bais = new ByteArrayInputStream(input);
|
|
ByteArrayOutputStream baos = new ByteArrayOutputStream();
|
|
compress(bais, baos);
|
|
return baos.toByteArray();
|
|
} catch (IOException e) {
|
|
SneakyThrow.throwException(e);
|
|
}
|
|
return new byte[0]; // Never reaches here anyway
|
|
}
|
|
|
|
public byte[] decompress(byte[] input) {
|
|
try {
|
|
ByteArrayInputStream bais = new ByteArrayInputStream(input);
|
|
ByteArrayOutputStream baos = new ByteArrayOutputStream();
|
|
decompress(bais, baos);
|
|
return baos.toByteArray();
|
|
} catch (IOException e) {
|
|
SneakyThrow.throwException(e);
|
|
}
|
|
return new byte[0]; // Never reaches here anyway
|
|
}
|
|
|
|
public void compress(InputStream inputStream, OutputStream outputStream) throws IOException {
|
|
try(OutputStream out = createCompressor(outputStream)) {
|
|
byte[] buf = new byte[8192];
|
|
int s; while ((s = inputStream.read(buf)) != -1) out.write(buf, 0, s);
|
|
try {
|
|
outputStream.flush();
|
|
}
|
|
catch (Throwable ignored) {} // Some compressors may not support flushing, like LZMA
|
|
}
|
|
}
|
|
|
|
public void decompress(InputStream inputStream, OutputStream outputStream) throws IOException {
|
|
try(InputStream is = createDecompressor(inputStream)) {
|
|
byte[] buf = new byte[8192];
|
|
int s; while ((s = is.read(buf)) != -1) outputStream.write(buf, 0, s);
|
|
try {
|
|
outputStream.flush();
|
|
}
|
|
catch (Throwable ignored) {} // Some compressors may not support flushing, like LZMA
|
|
}
|
|
}
|
|
|
|
public OutputStream createCompressor(OutputStream outputStream) throws IOException {
|
|
throw new UnsupportedOperationException("Not implemented yet");
|
|
}
|
|
|
|
public InputStream createDecompressor(InputStream inputStream) throws IOException {
|
|
throw new UnsupportedOperationException("Not implemented yet");
|
|
}
|
|
}
|