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, Writer extends SerializeWriter> extends WithScopedValue> { ScopedValue> DEFAULT = new ScopedValue<>(); @Override @ApiStatus.Internal default ScopedValue> 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 action) throws TEx, MalformedDataException { try (Reader reader = createReader(source)) { action.run(reader); } } default void read(String source, Action action) throws TEx, MalformedDataException { read(new StringReader(source), action); } default R read(java.io.Reader source, Returnable action) throws TEx, MalformedDataException { try (Reader reader = createReader(source)) { return action.run(reader); } } default R read(String source, Returnable action) throws TEx, MalformedDataException { return read(new StringReader(source), action); } default void write(java.io.Writer target, Action action) throws TEx, MalformedDataException { try (Writer writer = createWriter(target)) { action.run(writer); } } default String write(Action action) throws TEx, IOException { try (StringWriter sw = new StringWriter()) { write(sw, action); return sw.toString(); } } interface Returnable { R run(T value) throws TEx, MalformedDataException; } interface Action { void run(T value) throws TEx, MalformedDataException; } }