1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16 package org.jboss.netty.buffer;
17
18 import java.nio.ByteBuffer;
19 import java.nio.ByteOrder;
20
21
22
23
24
25
26
27 public class HeapChannelBufferFactory extends AbstractChannelBufferFactory {
28
29 private static final HeapChannelBufferFactory INSTANCE_BE =
30 new HeapChannelBufferFactory(ByteOrder.BIG_ENDIAN);
31
32 private static final HeapChannelBufferFactory INSTANCE_LE =
33 new HeapChannelBufferFactory(ByteOrder.LITTLE_ENDIAN);
34
35 public static ChannelBufferFactory getInstance() {
36 return INSTANCE_BE;
37 }
38
39 public static ChannelBufferFactory getInstance(ByteOrder endianness) {
40 if (endianness == ByteOrder.BIG_ENDIAN) {
41 return INSTANCE_BE;
42 } else if (endianness == ByteOrder.LITTLE_ENDIAN) {
43 return INSTANCE_LE;
44 } else if (endianness == null) {
45 throw new NullPointerException("endianness");
46 } else {
47 throw new IllegalStateException("Should not reach here");
48 }
49 }
50
51
52
53
54
55 public HeapChannelBufferFactory() {
56 }
57
58
59
60
61
62
63 public HeapChannelBufferFactory(ByteOrder defaultOrder) {
64 super(defaultOrder);
65 }
66
67 public ChannelBuffer getBuffer(ByteOrder order, int capacity) {
68 return ChannelBuffers.buffer(order, capacity);
69 }
70
71 public ChannelBuffer getBuffer(ByteOrder order, byte[] array, int offset, int length) {
72 return ChannelBuffers.wrappedBuffer(order, array, offset, length);
73 }
74
75 public ChannelBuffer getBuffer(ByteBuffer nioBuffer) {
76 if (nioBuffer.hasArray()) {
77 return ChannelBuffers.wrappedBuffer(nioBuffer);
78 }
79
80 ChannelBuffer buf = getBuffer(nioBuffer.order(), nioBuffer.remaining());
81 int pos = nioBuffer.position();
82 buf.writeBytes(nioBuffer);
83 nioBuffer.position(pos);
84 return buf;
85 }
86 }