CavalliumDBEngine/src/main/java/it/cavallium/dbengine/netty/NullableBuffer.java

77 lines
1.7 KiB
Java
Raw Normal View History

package it.cavallium.dbengine.netty;
2022-03-16 13:47:56 +01:00
import io.netty5.buffer.api.Buffer;
import io.netty5.buffer.api.Drop;
import io.netty5.buffer.api.Owned;
import io.netty5.buffer.api.Send;
import io.netty5.buffer.api.internal.ResourceSupport;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.jetbrains.annotations.Nullable;
2021-10-17 17:15:57 +02:00
public class NullableBuffer extends ResourceSupport<NullableBuffer, NullableBuffer> {
private static final Logger logger = LogManager.getLogger(NullableBuffer.class);
2021-10-01 19:17:33 +02:00
private static final Drop<NullableBuffer> DROP = new Drop<>() {
@Override
public void drop(NullableBuffer obj) {
try {
if (obj.buffer != null) {
obj.buffer.close();
}
} catch (Throwable ex) {
logger.error("Failed to close buffer", ex);
}
}
@Override
public Drop<NullableBuffer> fork() {
return this;
}
@Override
public void attach(NullableBuffer obj) {
}
};
@Nullable
private Buffer buffer;
2021-10-01 19:17:33 +02:00
public NullableBuffer(@Nullable Buffer buffer) {
super(DROP);
this.buffer = buffer == null ? null : buffer.send().receive();
}
2021-10-01 19:17:33 +02:00
public NullableBuffer(@Nullable Send<Buffer> buffer) {
super(DROP);
this.buffer = buffer == null ? null : buffer.receive();
}
@Nullable
public Buffer buf() {
return buffer;
}
@Nullable
public Send<Buffer> sendBuf() {
return buffer == null ? null : buffer.send();
}
@Override
protected RuntimeException createResourceClosedException() {
return new IllegalStateException("Closed");
}
@Override
protected Owned<NullableBuffer> prepareSend() {
var buffer = this.buffer == null ? null : this.buffer.send();
2021-10-01 19:17:33 +02:00
return drop -> new NullableBuffer(buffer);
}
2021-09-23 15:34:56 +02:00
protected void makeInaccessible() {
this.buffer = null;
}
}