78 lines
2.5 KiB
Java
78 lines
2.5 KiB
Java
package io.gitlab.jfronny.commons.serialize;
|
|
|
|
import io.gitlab.jfronny.commons.concurrent.ScopedValue;
|
|
import io.gitlab.jfronny.commons.concurrent.WithScopedValue;
|
|
import org.jetbrains.annotations.ApiStatus;
|
|
|
|
import java.io.IOException;
|
|
import java.io.StringReader;
|
|
import java.io.StringWriter;
|
|
|
|
public interface Transport<TEx extends Exception, Reader extends SerializeReader<TEx, Reader>, Writer extends SerializeWriter<TEx, Writer>> extends WithScopedValue<Transport<?, ?, ?>> {
|
|
ScopedValue<Transport<?, ?, ?>> DEFAULT = new ScopedValue<>();
|
|
|
|
@Override
|
|
@ApiStatus.Internal
|
|
default ScopedValue<Transport<?, ?, ?>> getAttached() {
|
|
return DEFAULT;
|
|
}
|
|
|
|
@Override
|
|
@ApiStatus.Internal
|
|
default Transport<?, ?, ?> self() {
|
|
return this;
|
|
}
|
|
|
|
Reader createReader(java.io.Reader source) throws TEx;
|
|
|
|
default Reader createReader(String source) throws TEx {
|
|
return createReader(new StringReader(source));
|
|
}
|
|
|
|
Writer createWriter(java.io.Writer target) throws TEx;
|
|
|
|
String getFormatMime();
|
|
|
|
// Utility methods for reading and writing. Not intended to be overridden.
|
|
default void read(java.io.Reader source, Action<Reader, TEx> action) throws TEx, MalformedDataException {
|
|
try (Reader reader = createReader(source)) {
|
|
action.run(reader);
|
|
}
|
|
}
|
|
|
|
default void read(String source, Action<Reader, TEx> action) throws TEx, MalformedDataException {
|
|
read(new StringReader(source), action);
|
|
}
|
|
|
|
default <R> R read(java.io.Reader source, Returnable<Reader, R, TEx> action) throws TEx, MalformedDataException {
|
|
try (Reader reader = createReader(source)) {
|
|
return action.run(reader);
|
|
}
|
|
}
|
|
|
|
default <R> R read(String source, Returnable<Reader, R, TEx> action) throws TEx, MalformedDataException {
|
|
return read(new StringReader(source), action);
|
|
}
|
|
|
|
default void write(java.io.Writer target, Action<Writer, TEx> action) throws TEx, MalformedDataException {
|
|
try (Writer writer = createWriter(target)) {
|
|
action.run(writer);
|
|
}
|
|
}
|
|
|
|
default String write(Action<Writer, TEx> action) throws TEx, IOException {
|
|
try (StringWriter sw = new StringWriter()) {
|
|
write(sw, action);
|
|
return sw.toString();
|
|
}
|
|
}
|
|
|
|
interface Returnable<T, R, TEx extends Exception> {
|
|
R run(T value) throws TEx, MalformedDataException;
|
|
}
|
|
|
|
interface Action<T, TEx extends Exception> {
|
|
void run(T value) throws TEx, MalformedDataException;
|
|
}
|
|
}
|