1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16 package io.netty.channel.unix;
17
18 import io.netty.buffer.ByteBufAllocator;
19 import io.netty.util.internal.ObjectUtil;
20
21 import java.io.IOException;
22 import java.nio.ByteBuffer;
23 import java.nio.channels.WritableByteChannel;
24
25 public abstract class SocketWritableByteChannel implements WritableByteChannel {
26 protected final FileDescriptor fd;
27
28 protected SocketWritableByteChannel(FileDescriptor fd) {
29 this.fd = ObjectUtil.checkNotNull(fd, "fd");
30 }
31
32 protected int write(ByteBuffer buf, int pos, int limit) throws IOException {
33 return fd.write(buf, pos, limit);
34 }
35
36 @Override
37 public final int write(java.nio.ByteBuffer src) throws java.io.IOException {
38 final int written;
39 int position = src.position();
40 int limit = src.limit();
41 if (src.isDirect()) {
42 written = write(src, position, src.limit());
43 } else {
44 final int readableBytes = limit - position;
45 io.netty.buffer.ByteBuf buffer = null;
46 try {
47 if (readableBytes == 0) {
48 buffer = io.netty.buffer.Unpooled.EMPTY_BUFFER;
49 } else {
50 final ByteBufAllocator alloc = alloc();
51 if (alloc.isDirectBufferPooled()) {
52 buffer = alloc.directBuffer(readableBytes);
53 } else {
54 buffer = io.netty.buffer.ByteBufUtil.threadLocalDirectBuffer();
55 if (buffer == null) {
56 buffer = io.netty.buffer.Unpooled.directBuffer(readableBytes);
57 }
58 }
59 }
60 buffer.writeBytes(src.duplicate());
61 java.nio.ByteBuffer nioBuffer = buffer.internalNioBuffer(buffer.readerIndex(), readableBytes);
62 written = write(nioBuffer, nioBuffer.position(), nioBuffer.limit());
63 } finally {
64 if (buffer != null) {
65 buffer.release();
66 }
67 }
68 }
69 if (written > 0) {
70 src.position(position + written);
71 }
72 return written;
73 }
74
75 @Override
76 public final boolean isOpen() {
77 return fd.isOpen();
78 }
79
80 @Override
81 public final void close() throws java.io.IOException {
82 fd.close();
83 }
84
85 protected abstract ByteBufAllocator alloc();
86 }