1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20 package org.apache.mina.codec.delimited;
21
22 import org.apache.mina.codec.IoBuffer;
23 import org.apache.mina.codec.ProtocolDecoder;
24
25
26
27
28
29 public class SizePrefixedDecoder<OUT> implements ProtocolDecoder<IoBuffer, OUT, SizePrefixedDecoder.MutableInt> {
30
31
32
33
34
35
36
37 protected static final class MutableInt {
38
39 private Integer value = null;
40
41
42
43
44 private MutableInt() {
45
46 }
47
48
49
50
51
52
53
54 public Integer getValue() {
55 return value;
56 }
57
58
59
60
61
62
63 public boolean isDefined() {
64 return value != null;
65 }
66
67
68
69
70 public void reset() {
71 value = null;
72 }
73
74
75
76
77
78
79
80 public void setValue(Integer value) {
81 this.value = value;
82 }
83 }
84
85 private final IoBufferDecoder<Integer> sizeDecoder;
86
87 private final IoBufferDecoder<OUT> payloadDecoder;
88
89 public SizePrefixedDecoder(IoBufferDecoder<Integer> sizeDecoder, IoBufferDecoder<OUT> payloadDecoder) {
90 super();
91 this.sizeDecoder = sizeDecoder;
92 this.payloadDecoder = payloadDecoder;
93 }
94
95 @Override
96 public MutableInt createDecoderState() {
97
98 return new MutableInt();
99 }
100
101 @Override
102 public OUT decode(IoBuffer input, MutableInt nextBlockSize) {
103 OUT output = null;
104
105 if (nextBlockSize.getValue() == null) {
106 nextBlockSize.setValue(sizeDecoder.decode(input));
107 }
108
109 if (nextBlockSize.isDefined() && (input.remaining() >= nextBlockSize.getValue())) {
110 IoBuffer buffer = input.slice();
111 buffer.limit(buffer.position() + nextBlockSize.getValue());
112
113 output = payloadDecoder.decode(buffer);
114 nextBlockSize.reset();
115 }
116
117 return output;
118 }
119
120 @Override
121 public void finishDecode(MutableInt context) {
122
123 }
124 }