1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
|
/*
*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*
*/
using System;
using System.Text;
namespace Qpid.Buffer
{
public enum ByteOrder { BigEndian, LittleEndian }
// /// <summary>
// /// A buffer that manages an underlying byte oriented stream, and writes and reads to and from it in
// /// BIG ENDIAN order.
// /// </summary>
// public abstract class ByteBuffer
// {
// protected const int MINIMUM_CAPACITY = 1;
//
// protected static Stack _containerStack = new Stack();
//
// protected static Stack[] _heapBufferStacks = new Stack[]
// {
// new Stack(), new Stack(), new Stack(), new Stack(),
// new Stack(), new Stack(), new Stack(), new Stack(),
// new Stack(), new Stack(), new Stack(), new Stack(),
// new Stack(), new Stack(), new Stack(), new Stack(),
// new Stack(), new Stack(), new Stack(), new Stack(),
// new Stack(), new Stack(), new Stack(), new Stack(),
// new Stack(), new Stack(), new Stack(), new Stack(),
// new Stack(), new Stack(), new Stack(), new Stack()
// };
//
// /// <summary>
// /// Returns the direct or heap buffer which is capable of the specified size.
// /// Currently does not support direct buffers but this will be an option in future.
// /// </summary>
// /// <param name="capacity">The capacity.</param>
// /// <returns></returns>
// public static ByteBuffer Allocate(int capacity)
// {
// // for now, just allocate a heap buffer but in future could do an optimised "direct" buffer
// // that is implemented natively
// return Allocate(capacity, false);
// }
//
// public static ByteBuffer Allocate(int capacity, bool direct)
// {
// ByteBuffer buffer = Allocate0(capacity, direct);
// RefCountingByteBuffer buf = AllocateContainer();
// buf.Init(buffer);
// return buf;
// }
//
// private static RefCountingByteBuffer AllocateContainer()
// {
// RefCountingByteBuffer buf = null;
// lock (_containerStack)
// {
// if (_containerStack.Count > 0)
// {
// buf = (RefCountingByteBuffer) _containerStack.Pop();
// }
// }
//
// if (buf == null)
// {
// buf = new RefCountingByteBuffer();
// }
// return buf;
// }
//
// protected static ByteBuffer Allocate0(int capacity, bool direct)
// {
// if (direct)
// {
// throw new NotSupportedException("Direct buffers not currently implemented");
// }
// int idx = GetBufferStackIndex(_heapBufferStacks, capacity);
// Stack stack = _heapBufferStacks[idx];
// ByteBuffer buf = null;
// lock (stack)
// {
// if (stack.Count > 0)
// {
// buf = (ByteBuffer) stack.Pop();
// }
// }
//
// if (buf == null)
// {
// buf = new HeapByteBuffer(MINIMUM_CAPACITY << idx);
// }
//
// return buf;
// }
//
// protected static void Release0(ByteBuffer buf)
// {
// Stack stack = _heapBufferStacks[GetBufferStackIndex(_heapBufferStacks, buf.Capacity)];
// lock (stack)
// {
// stack.Push(buf);
// }
// }
//
// private static int GetBufferStackIndex(Stack[] bufferStacks, int size)
// {
// int targetSize = MINIMUM_CAPACITY;
// int stackIdx = 0;
// // each bucket contains buffers that are double the size of the previous bucket
// while (size > targetSize)
// {
// targetSize <<= 1;
// stackIdx++;
// if (stackIdx >= bufferStacks.Length)
// {
// throw new ArgumentOutOfRangeException("size", "Buffer size is too big: " + size);
// }
// }
// return stackIdx;
// }
//
// /// <summary>
// /// Increases the internal reference count of this buffer to defer automatic release. You have
// /// to invoke release() as many times as you invoked this method to release this buffer.
// /// </summary>
// public abstract void Acquire();
//
// /// <summary>
// /// Releases the specified buffer to the buffer pool.
// /// </summary>
// public abstract void Release();
//
// public abstract int Capacity
// {
// get;
// }
//
// public abstract bool IsAutoExpand
// {
// get;
// set;
// }
//
// /// <summary>
// /// Changes the capacity and limit of this buffer sot his buffer gets the specified
// /// expectedRemaining room from the current position. This method works even if you didn't set
// /// autoExpand to true.
// /// </summary>
// /// <param name="expectedRemaining">Room you want from the current position</param>
// public abstract void Expand(int expectedRemaining);
//
// /// <summary>
// /// Changes the capacity and limit of this buffer sot his buffer gets the specified
// /// expectedRemaining room from the specified position.
// /// </summary>
// /// <param name="pos">The pos you want the room to be available from.</param>
// /// <param name="expectedRemaining">The expected room you want available.</param>
// public abstract void Expand(int pos, int expectedRemaining);
//
// /// <summary>
// /// Returns true if and only if this buffer is returned back to the buffer pool when released.
// /// </summary>
// /// <value><c>true</c> if pooled; otherwise, <c>false</c>.</value>
// public abstract bool Pooled
// {
// get;
// set;
// }
//
// public abstract int Position
// {
// get;
// set;
// }
//
// public abstract int Limit
// {
// get;
// set;
// }
//
// //public abstract void Mark();
//
// //public abstract void Reset();
//
// public abstract void Clear();
//
// /// <summary>
// /// Clears this buffer and fills its content with NULL. The position is set to zero, the limit is set to
// /// capacity and the mark is discarded.
// /// </summary>
// public void Sweep()
// {
// Clear();
// FillAndReset(Remaining);
// }
//
// public void Sweep(byte value)
// {
// Clear();
// FillAndReset(value, Remaining);
// }
//
// public abstract void Flip();
//
// public abstract void Rewind();
//
// public abstract int Remaining
// {
// get;
// }
//
// public bool HasRemaining()
// {
// return Remaining > 0;
// }
//
// public abstract byte Get();
//
// public abstract byte Get(int index);
//
// public abstract void Get(byte[] destination);
//
// public abstract ushort GetUnsignedShort();
//
// public abstract uint GetUnsignedInt();
//
// public abstract ulong GetUnsignedLong();
//
// public abstract string GetString(uint length, Encoding encoder);
//
// public abstract void Put(byte data);
//
// public abstract void Put(byte[] data);
// public abstract void Put(byte[] data, int offset, int size);
//
// public abstract void Put(ushort data);
//
// public abstract void Put(uint data);
//
// public abstract void Put(ulong data);
//
// public abstract void Put(ByteBuffer buf);
//
// public abstract void Compact();
//
// public abstract byte[] ToByteArray();
//
// public override string ToString()
// {
// StringBuilder buf = new StringBuilder();
// buf.Append("HeapBuffer");
// buf.AppendFormat("[pos={0} lim={1} cap={2} : {3}]", Position, Limit, Capacity, HexDump);
// return buf.ToString();
// }
//
// public override int GetHashCode()
// {
// int h = 1;
// int p = Position;
// for (int i = Limit - 1; i >= p; i--)
// {
// h = 31 * h + Get(i);
// }
//
// return h;
// }
//
// public override bool Equals(object obj)
// {
// if (!(obj is ByteBuffer))
// {
// return false;
// }
// ByteBuffer that = (ByteBuffer) obj;
//
// if (Remaining != that.Remaining)
// {
// return false;
// }
// int p = Position;
// for (int i = Limit - 1, j = that.Limit - 1; i >= p; i--, j--)
// {
// byte v1 = this.Get(i);
// byte v2 = that.Get(j);
// if (v1 != v2)
// {
// return false;
// }
// }
// return true;
// }
//
// public string HexDump
// {
// get
// {
// return ByteBufferHexDumper.GetHexDump(this);
// }
// }
//
// /// <summary>
// /// Fills the buffer with the specified specified value. This method moves the buffer position forward.
// /// </summary>
// /// <param name="value">The value.</param>
// /// <param name="size">The size.</param>
// public void Fill(byte value, int size)
// {
// AutoExpand(size);
// int q = size >> 3;
// int r = size & 7;
//
// if (q > 0)
// {
// int intValue = value | (value << 8) | (value << 16) | (value << 24);
// long longValue = intValue;
// longValue <<= 32;
// longValue |= (ushort)intValue;
//
// for (int i = q; i > 0; i--)
// {
// Put((ulong)longValue);
// }
// }
//
// q = r >> 2;
// r = r & 3;
//
// if (q > 0)
// {
// int intValue = value | (value << 8) | (value << 16) | (value << 24);
// Put((uint)intValue);
// }
//
// q = r >> 1;
// r = r & 1;
//
// if (q > 0)
// {
// short shortValue = (short) (value | (value << 8));
// Put((ushort) shortValue);
// }
// if (r > 0)
// {
// Put(value);
// }
// }
//
// public void FillAndReset(byte value, int size)
// {
// AutoExpand(size);
// int pos = Position;
// try
// {
// Fill(value, size);
// }
// finally
// {
// Position = pos;
// }
// }
//
// public void Fill(int size)
// {
// AutoExpand(size);
// int q = size >> 3;
// int r = size & 7;
//
// for (int i = q; i > 0; i--)
// {
// Put(0L);
// }
//
// q = r >> 2;
// r = r & 3;
//
// if (q > 0)
// {
// Put(0);
// }
//
// q = r >> 1;
// r = r & 1;
//
// if(q > 0)
// {
// Put((ushort) 0);
// }
//
// if (r > 0)
// {
// Put((byte) 0);
// }
// }
//
// public void FillAndReset(int size)
// {
// AutoExpand(size);
// int pos = Position;
// try
// {
// Fill(size);
// }
// finally
// {
// Position = pos;
// }
// }
//
// public void Skip(int size)
// {
// AutoExpand(size);
// Position = Position + size;
// }
//
// protected void AutoExpand(int expectedRemaining)
// {
// if (IsAutoExpand)
// {
// Expand(expectedRemaining);
// }
// }
//
// protected void AutoExpand(int pos, int expectedRemaining)
// {
// if (IsAutoExpand)
// {
// Expand(pos, expectedRemaining);
// }
// }
// }
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*
*/
//package org.apache.mina.common;
//
//import java.io.IOException;
//import java.io.InputStream;
//import java.io.ObjectInputStream;
//import java.io.ObjectOutputStream;
//import java.io.ObjectStreamClass;
//import java.io.OutputStream;
//import java.nio.BufferOverflowException;
//import java.nio.BufferUnderflowException;
//import java.nio.ByteOrder;
//import java.nio.CharBuffer;
//import java.nio.DoubleBuffer;
//import java.nio.FloatBuffer;
//import java.nio.IntBuffer;
//import java.nio.LongBuffer;
//import java.nio.ShortBuffer;
//import java.nio.charset.CharacterCodingException;
//import java.nio.charset.CharsetDecoder;
//import java.nio.charset.CharsetEncoder;
//import java.nio.charset.CoderResult;
//
//import org.apache.mina.common.support.ByteBufferHexDumper;
//import org.apache.mina.filter.codec.ProtocolEncoderOutput;
/**
* A byte buffer used by MINA applications.
* <p>
* This is a replacement for {@link FixedByteBuffer}. Please refer to
* {@link FixedByteBuffer} and {@link java.nio.Buffer} documentation for
* usage. MINA does not use NIO {@link FixedByteBuffer} directly for two
* reasons:
* <ul>
* <li>It doesn't provide useful getters and putters such as
* <code>fill</code>, <code>get/putString</code>, and
* <code>get/putAsciiInt()</code> enough.</li>
* <li>It is hard to distinguish if the buffer is created from MINA buffer
* pool or not. MINA have to return used buffers back to pool.</li>
* <li>It is difficult to write variable-length data due to its fixed
* capacity</li>
* </ul>
* </p>
*
* <h2>Allocation</h2>
* <p>
* You can get a heap buffer from buffer pool:
* <pre>
* ByteBuffer buf = ByteBuffer.allocate(1024, false);
* </pre>
* you can also get a direct buffer from buffer pool:
* <pre>
* ByteBuffer buf = ByteBuffer.allocate(1024, true);
* </pre>
* or you can let MINA choose:
* <pre>
* ByteBuffer buf = ByteBuffer.allocate(1024);
* </pre>
* </p>
*
* <h2>Acquire/Release</h2>
* <p>
* <b>Please note that you never need to release the allocated buffer</b>
* because MINA will release it automatically when:
* <ul>
* <li>You pass the buffer by calling {@link IoSession#write(Object)}.</li>
* <li>You pass the buffer by calling {@link IoFilter.NextFilter#filterWrite(IoSession,IoFilter.WriteRequest)}.</li>
* <li>You pass the buffer by calling {@link ProtocolEncoderOutput#write(ByteBuffer)}.</li>
* </ul>
* And, you don't need to release any {@link ByteBuffer} which is passed as a parameter
* of {@link IoHandler#messageReceived(IoSession, Object)} method. They are released
* automatically when the method returns.
* <p>
* You have to release buffers manually by calling {@link #release()} when:
* <ul>
* <li>You allocated a buffer, but didn't pass the buffer to any of two methods above.</li>
* <li>You called {@link #acquire()} to prevent the buffer from being released.</li>
* </ul>
* </p>
*
* <h2>Wrapping existing NIO buffers and arrays</h2>
* <p>
* This class provides a few <tt>wrap(...)</tt> methods that wraps
* any NIO buffers and byte arrays. Wrapped MINA buffers are not returned
* to the buffer pool by default to prevent unexpected memory leakage by default.
* In case you want to make it pooled, you can call {@link #setPooled(bool)}
* with <tt>true</tt> flag to enable pooling.
*
* <h2>AutoExpand</h2>
* <p>
* Writing variable-length data using NIO <tt>ByteBuffers</tt> is not really
* easy, and it is because its size is fixed. MINA <tt>ByteBuffer</tt>
* introduces <tt>autoExpand</tt> property. If <tt>autoExpand</tt> property
* is true, you never get {@link BufferOverflowException} or
* {@link IndexOutOfBoundsException} (except when index is negative).
* It automatically expands its capacity and limit value. For example:
* <pre>
* String greeting = messageBundle.getMessage( "hello" );
* ByteBuffer buf = ByteBuffer.allocate( 16 );
* // Turn on autoExpand (it is off by default)
* buf.setAutoExpand( true );
* buf.putString( greeting, utf8encoder );
* </pre>
* NIO <tt>ByteBuffer</tt> is reallocated by MINA <tt>ByteBuffer</tt> behind
* the scene if the encoded data is larger than 16 bytes. Its capacity will
* increase by two times, and its limit will increase to the last position
* the string is written.
* </p>
*
* <h2>Derived Buffers</h2>
* <p>
* Derived buffers are the buffers which were created by
* {@link #duplicate()}, {@link #slice()}, or {@link #asReadOnlyBuffer()}.
* They are useful especially when you broadcast the same messages to
* multiple {@link IoSession}s. Please note that the derived buffers are
* neither pooled nor auto-expandable. Trying to expand a derived buffer will
* raise {@link IllegalStateException}.
* </p>
*
* <h2>Changing Buffer Allocation and Management Policy</h2>
* <p>
* MINA provides a {@link ByteBufferAllocator} interface to let you override
* the default buffer management behavior. There are two allocators provided
* out-of-the-box:
* <ul>
* <li>{@link PooledByteBufferAllocator} (Default)</li>
* <li>{@link SimpleByteBufferAllocator}</li>
* </ul>
* You can change the allocator by calling {@link #setAllocator(ByteBufferAllocator)}.
* </p>
*
* @author The Apache Directory Project (mina-dev@directory.apache.org)
* @version $Rev: 451854 $, $Date: 2006-10-02 11:30:11 +0900 (월, 02 10월 2006) $
* @noinspection StaticNonFinalField
* @see ByteBufferAllocator
*/
public abstract class ByteBuffer : IComparable
{
//private static ByteBufferAllocator allocator = new PooledByteBufferAllocator();
private static ByteBufferAllocator allocator = new SimpleByteBufferAllocator();
private static bool _useDirectBuffers = false;
public string HexDump
{
get
{
return ByteBufferHexDumper.GetHexDump(this);
}
}
/**
* Returns the current allocator which manages the allocated buffers.
*/
public static ByteBufferAllocator getAllocator()
{
return allocator;
}
/**
* Changes the current allocator with the specified one to manage
* the allocated buffers from now.
*/
public static void setAllocator( ByteBufferAllocator newAllocator )
{
if( newAllocator == null )
{
throw new NullReferenceException("allocator cannot be null");
}
ByteBufferAllocator oldAllocator = allocator;
allocator = newAllocator;
if( null != oldAllocator )
{
oldAllocator.dispose();
}
}
public static bool isUseDirectBuffers()
{
return _useDirectBuffers;
}
public static void setUseDirectBuffers( bool useDirectBuffers )
{
_useDirectBuffers = useDirectBuffers;
}
/**
* Returns the direct or heap buffer which is capable of the specified
* size. This method tries to allocate direct buffer first, and then
* tries heap buffer if direct buffer memory is exhausted. Please use
* {@link #allocate(int, bool)} to allocate buffers of specific type.
*
* @param capacity the capacity of the buffer
*/
public static ByteBuffer allocate( int capacity )
{
if( _useDirectBuffers )
{
try
{
// first try to allocate direct buffer
return allocate( capacity, true );
}
catch (OutOfMemoryException)
{
// fall through to heap buffer
}
}
return allocate( capacity, false );
}
/**
* Returns the buffer which is capable of the specified size.
*
* @param capacity the capacity of the buffer
* @param direct <tt>true</tt> to get a direct buffer,
* <tt>false</tt> to get a heap buffer.
*/
public static ByteBuffer allocate( int capacity, bool direct )
{
return allocator.allocate( capacity, direct );
}
/**
* Wraps the specified NIO {@link FixedByteBuffer} into MINA buffer.
*/
public static ByteBuffer wrap( FixedByteBuffer nioBuffer )
{
return allocator.wrap( nioBuffer );
}
/**
* Wraps the specified byte array into MINA heap buffer.
*/
public static ByteBuffer wrap( byte[] byteArray )
{
return wrap( FixedByteBuffer.wrap( byteArray ) );
}
/**
* Wraps the specified byte array into MINA heap buffer.
* Please note that MINA buffers are going to be pooled, and
* therefore there can be waste of memory if you wrap
* your byte array specifying <tt>offset</tt> and <tt>length</tt>.
*/
public static ByteBuffer wrap( byte[] byteArray, int offset, int length )
{
return wrap( FixedByteBuffer.wrap( byteArray, offset, length ) );
}
protected ByteBuffer()
{
}
/**
* Increases the internal reference count of this buffer to defer
* automatic release. You have to invoke {@link #release()} as many
* as you invoked this method to release this buffer.
*
* @throws IllegalStateException if you attempt to acquire already
* released buffer.
*/
public abstract void acquire();
/**
* Releases the specified buffer to buffer pool.
*
* @throws IllegalStateException if you attempt to release already
* released buffer.
*/
public abstract void release();
/**
* Returns the underlying NIO buffer instance.
*/
public abstract FixedByteBuffer buf();
/**
* @see FixedByteBuffer#isDirect()
*/
public abstract bool isDirect();
/**
* @see FixedByteBuffer#isReadOnly()
*/
public abstract bool isReadOnly();
/**
* @see FixedByteBuffer#capacity()
*/
public abstract int capacity();
/**
* Changes the capacity of this buffer.
*/
public abstract ByteBuffer capacity( int newCapacity );
/**
* Returns <tt>true</tt> if and only if <tt>autoExpand</tt> is turned on.
*/
public abstract bool isAutoExpand();
/**
* Turns on or off <tt>autoExpand</tt>.
*/
public abstract ByteBuffer setAutoExpand( bool autoExpand );
/**
* Changes the capacity and limit of this buffer so this buffer get
* the specified <tt>expectedRemaining</tt> room from the current position.
* This method works even if you didn't set <tt>autoExpand</tt> to
* <tt>true</tt>.
*/
public ByteBuffer expand( int expectedRemaining )
{
return expand( position(), expectedRemaining );
}
/**
* Changes the capacity and limit of this buffer so this buffer get
* the specified <tt>expectedRemaining</tt> room from the specified
* <tt>pos</tt>.
* This method works even if you didn't set <tt>autoExpand</tt> to
* <tt>true</tt>.
*/
public abstract ByteBuffer expand( int pos, int expectedRemaining );
/**
* Returns <tt>true</tt> if and only if this buffer is returned back
* to the buffer pool when released.
* <p>
* The default value of this property is <tt>true</tt> if and only if you
* allocated this buffer using {@link #allocate(int)} or {@link #allocate(int, bool)},
* or <tt>false</tt> otherwise. (i.e. {@link #wrap(byte[])}, {@link #wrap(byte[], int, int)},
* and {@link #wrap(FixedByteBuffer)})
*/
public abstract bool isPooled();
/**
* Sets whether this buffer is returned back to the buffer pool when released.
* <p>
* The default value of this property is <tt>true</tt> if and only if you
* allocated this buffer using {@link #allocate(int)} or {@link #allocate(int, bool)},
* or <tt>false</tt> otherwise. (i.e. {@link #wrap(byte[])}, {@link #wrap(byte[], int, int)},
* and {@link #wrap(FixedByteBuffer)})
*/
public abstract void setPooled( bool pooled );
/**
* @see java.nio.Buffer#position()
*/
public abstract int position();
/**
* @see java.nio.Buffer#position(int)
*/
public abstract ByteBuffer position( int newPosition );
/**
* @see java.nio.Buffer#limit()
*/
public abstract int limit();
/**
* @see java.nio.Buffer#limit(int)
*/
public abstract ByteBuffer limit( int newLimit );
/**
* @see java.nio.Buffer#mark()
*/
public abstract ByteBuffer mark();
/**
* Returns the position of the current mark. This method returns <tt>-1</tt> if no
* mark is set.
*/
public abstract int markValue();
/**
* @see java.nio.Buffer#reset()
*/
public abstract ByteBuffer reset();
/**
* @see java.nio.Buffer#clear()
*/
public abstract ByteBuffer clear();
/**
* Clears this buffer and fills its content with <tt>NUL</tt>.
* The position is set to zero, the limit is set to the capacity,
* and the mark is discarded.
*/
// public ByteBuffer sweep()
// {
// clear();
// return fillAndReset( remaining() );
// }
/**
* Clears this buffer and fills its content with <tt>value</tt>.
* The position is set to zero, the limit is set to the capacity,
* and the mark is discarded.
*/
// public ByteBuffer sweep( byte value )
// {
// clear();
// return fillAndReset( value, remaining() );
// }
/**
* @see java.nio.Buffer#flip()
*/
public abstract ByteBuffer flip();
/**
* @see java.nio.Buffer#rewind()
*/
public abstract ByteBuffer rewind();
/**
* @see java.nio.Buffer#remaining()
*/
public int remaining()
{
return limit() - position();
}
/**
* @see java.nio.Buffer#hasRemaining()
*/
public bool hasRemaining()
{
return remaining() > 0;
}
/**
* @see FixedByteBuffer#duplicate()
*/
public abstract ByteBuffer duplicate();
/**
* @see FixedByteBuffer#slice()
*/
public abstract ByteBuffer slice();
/**
* @see FixedByteBuffer#asReadOnlyBuffer()
*/
public abstract ByteBuffer asReadOnlyBuffer();
/**
* @see FixedByteBuffer#array()
*/
public abstract byte[] array();
/**
* @see FixedByteBuffer#arrayOffset()
*/
public abstract int arrayOffset();
/**
* @see FixedByteBuffer#get()
*/
public abstract byte get();
/**
* Reads one unsigned byte as a short integer.
*/
public short getUnsigned()
{
return (short)( get() & 0xff );
}
/**
* @see FixedByteBuffer#put(byte)
*/
public abstract ByteBuffer put( byte b );
/**
* @see FixedByteBuffer#get(int)
*/
public abstract byte get( int index );
/**
* Reads one byte as an unsigned short integer.
*/
public short getUnsigned( int index )
{
return (short)( get( index ) & 0xff );
}
/**
* @see FixedByteBuffer#put(int, byte)
*/
public abstract ByteBuffer put( int index, byte b );
/**
* @see FixedByteBuffer#get(byte[], int, int)
*/
public abstract ByteBuffer get( byte[] dst, int offset, int length );
/**
* @see FixedByteBuffer#get(byte[])
*/
public abstract ByteBuffer get(byte[] dst);
// {
// return get( dst, 0, dst.Length );
// }
/**
* Writes the content of the specified <tt>src</tt> into this buffer.
*/
public abstract ByteBuffer put( FixedByteBuffer src );
/**
* Writes the content of the specified <tt>src</tt> into this buffer.
*/
public ByteBuffer put( ByteBuffer src )
{
return put( src.buf() );
}
/**
* @see FixedByteBuffer#put(byte[], int, int)
*/
public abstract ByteBuffer put( byte[] src, int offset, int length );
/**
* @see FixedByteBuffer#put(byte[])
*/
public abstract ByteBuffer put(byte[] src);
// {
// return put(src);
//// return put( src, 0, src.Length );
// }
/**
* @see FixedByteBuffer#compact()
*/
public abstract ByteBuffer compact();
public String toString()
{
StringBuilder buf = new StringBuilder();
if( isDirect() )
{
buf.Append( "DirectBuffer" );
}
else
{
buf.Append( "HeapBuffer" );
}
buf.Append( "[pos=" );
buf.Append( position() );
buf.Append( " lim=" );
buf.Append( limit() );
buf.Append( " cap=" );
buf.Append( capacity() );
buf.Append( ": " );
buf.Append( getHexDump() );
buf.Append( ']' );
return buf.ToString();
}
public int hashCode()
{
int h = 1;
int p = position();
for( int i = limit() - 1; i >= p; i -- )
{
h = 31 * h + get( i );
}
return h;
}
public bool equals( Object o )
{
if( !( o is ByteBuffer ) )
{
return false;
}
ByteBuffer that = (ByteBuffer)o;
if( this.remaining() != that.remaining() )
{
return false;
}
int p = this.position();
for( int i = this.limit() - 1, j = that.limit() - 1; i >= p; i --, j -- )
{
byte v1 = this.get( i );
byte v2 = that.get( j );
if( v1 != v2 )
{
return false;
}
}
return true;
}
public int CompareTo( Object o )
{
ByteBuffer that = (ByteBuffer)o;
int n = this.position() + Math.Min( this.remaining(), that.remaining() );
for( int i = this.position(), j = that.position(); i < n; i ++, j ++ )
{
byte v1 = this.get( i );
byte v2 = that.get( j );
if( v1 == v2 )
{
continue;
}
if( v1 < v2 )
{
return -1;
}
return +1;
}
return this.remaining() - that.remaining();
}
/**
* @see FixedByteBuffer#order()
*/
public abstract ByteOrder order();
/**
* @see FixedByteBuffer#order(ByteOrder)
*/
public abstract ByteBuffer order( ByteOrder bo );
/**
* @see FixedByteBuffer#getChar()
*/
public abstract char getChar();
/**
* @see FixedByteBuffer#putChar(char)
*/
public abstract ByteBuffer putChar( char value );
/**
* @see FixedByteBuffer#getChar(int)
*/
public abstract char getChar( int index );
/**
* @see FixedByteBuffer#putChar(int, char)
*/
public abstract ByteBuffer putChar( int index, char value );
/**
* @see FixedByteBuffer#asCharBuffer()
*/
// public abstract CharBuffer asCharBuffer();
/**
* @see FixedByteBuffer#getShort()
*/
public abstract short getShort();
/**
* Reads two bytes unsigned integer.
*/
public int getUnsignedShort()
{
return getShort() & 0xffff;
}
/**
* @see FixedByteBuffer#putShort(short)
*/
public abstract ByteBuffer putShort( short value );
/**
* @see FixedByteBuffer#getShort()
*/
public abstract short getShort( int index );
/**
* Reads two bytes unsigned integer.
*/
public int getUnsignedShort( int index )
{
return getShort( index ) & 0xffff;
}
/**
* @see FixedByteBuffer#putShort(int, short)
*/
public abstract ByteBuffer putShort( int index, short value );
/**
* @see FixedByteBuffer#asShortBuffer()
*/
// public abstract ShortBuffer asShortBuffer();
/**
* @see FixedByteBuffer#getInt()
*/
public abstract int getInt();
/**
* Reads four bytes unsigned integer.
*/
public uint getUnsignedInt()
{
// return getInt() & 0xffffffffL;
//CheckSpaceForReading(4);
byte b1 = get();
byte b2 = get();
byte b3 = get();
byte b4 = get();
return (uint)((b1 << 24) + (b2 << 16) + (b3 << 8) + b4);
}
/**
* @see FixedByteBuffer#putInt(int)
*/
public abstract ByteBuffer putInt( int value );
/**
* @see FixedByteBuffer#getInt(int)
*/
public abstract int getInt( int index );
/**
* Reads four bytes unsigned integer.
*/
public long getUnsignedInt( int index )
{
return getInt( index ) & 0xffffffffL;
}
/**
* @see FixedByteBuffer#putInt(int, int)
*/
public abstract ByteBuffer putInt( int index, int value );
/**
* @see FixedByteBuffer#asIntBuffer()
*/
// public abstract IntBuffer asIntBuffer();
/**
* @see FixedByteBuffer#getLong()
*/
public abstract long getLong();
/**
* @see FixedByteBuffer#putLong(int, long)
*/
public abstract ByteBuffer putLong( long value );
/**
* @see FixedByteBuffer#getLong(int)
*/
public abstract long getLong( int index );
/**
* @see FixedByteBuffer#putLong(int, long)
*/
public abstract ByteBuffer putLong( int index, long value );
/**
* @see FixedByteBuffer#asLongBuffer()
*/
// public abstract LongBuffer asLongBuffer();
/**
* @see FixedByteBuffer#getFloat()
*/
public abstract float getFloat();
/**
* @see FixedByteBuffer#putFloat(float)
*/
public abstract ByteBuffer putFloat( float value );
/**
* @see FixedByteBuffer#getFloat(int)
*/
public abstract float getFloat( int index );
/**
* @see FixedByteBuffer#putFloat(int, float)
*/
public abstract ByteBuffer putFloat( int index, float value );
/**
* @see FixedByteBuffer#asFloatBuffer()
*/
// public abstract FloatBuffer asFloatBuffer();
/**
* @see FixedByteBuffer#getDouble()
*/
public abstract double getDouble();
/**
* @see FixedByteBuffer#putDouble(double)
*/
public abstract ByteBuffer putDouble( double value );
/**
* @see FixedByteBuffer#getDouble(int)
*/
public abstract double getDouble( int index );
/**
* @see FixedByteBuffer#putDouble(int, double)
*/
public abstract ByteBuffer putDouble( int index, double value );
/**
* @see FixedByteBuffer#asDoubleBuffer()
*/
// public abstract DoubleBuffer asDoubleBuffer();
/**
* Returns an {@link InputStream} that reads the data from this buffer.
* {@link InputStream#read()} returns <tt>-1</tt> if the buffer position
* reaches to the limit.
*/
// public InputStream asInputStream()
// {
// // XXX: Use System.IO.Stream here?
// return new InputStream()
// {
// public int available()
// {
// return ByteBuffer.this.remaining();
// }
//
// public synchronized void mark( int readlimit )
// {
// ByteBuffer.this.mark();
// }
//
// public bool markSupported()
// {
// return true;
// }
//
// public int read()
// {
// if( ByteBuffer.this.hasRemaining() )
// {
// return ByteBuffer.this.get() & 0xff;
// }
// else
// {
// return -1;
// }
// }
//
// public int read( byte[] b, int off, int len )
// {
// int remaining = ByteBuffer.this.remaining();
// if( remaining > 0 )
// {
// int readBytes = Math.min( remaining, len );
// ByteBuffer.this.get( b, off, readBytes );
// return readBytes;
// }
// else
// {
// return -1;
// }
// }
//
// public synchronized void reset()
// {
// ByteBuffer.this.reset();
// }
//
// public long skip( long n )
// {
// int bytes;
// if( n > Integer.MAX_VALUE )
// {
// bytes = ByteBuffer.this.remaining();
// }
// else
// {
// bytes = Math.min( ByteBuffer.this.remaining(), (int)n );
// }
// ByteBuffer.this.skip( bytes );
// return bytes;
// }
// };
// }
/**
* Returns an {@link OutputStream} that Appends the data into this buffer.
* Please note that the {@link OutputStream#write(int)} will throw a
* {@link BufferOverflowException} instead of an {@link IOException}
* in case of buffer overflow. Please set <tt>autoExpand</tt> property by
* calling {@link #setAutoExpand(bool)} to prevent the unexpected runtime
* exception.
*/
// public OutputStream asOutputStream()
// {
// return new OutputStream()
// {
// public void write( byte[] b, int off, int len )
// {
// ByteBuffer.this.put( b, off, len );
// }
//
// public void write( int b )
// {
// ByteBuffer.this.put( (byte)b );
// }
// };
// }
/**
* Returns hexdump of this buffer.
*/
public String getHexDump()
{
return ByteBufferHexDumper.GetHexDump(this);
}
////////////////////////////////
// String getters and putters //
////////////////////////////////
/**
* Reads a <code>NUL</code>-terminated string from this buffer using the
* specified <code>decoder</code> and returns it. This method reads
* until the limit of this buffer if no <tt>NUL</tt> is found.
*/
// public String getString( Encoding decoder )
// {
// if( !hasRemaining() )
// {
// return "";
// }
//
// decoder.
// bool utf16 = decoder.charset().name().startsWith( "UTF-16" );
//
// int oldPos = position();
// int oldLimit = limit();
// int end;
//
// if( !utf16 )
// {
// while( hasRemaining() )
// {
// if( get() == 0 )
// {
// break;
// }
// }
//
// end = position();
// if( end == oldLimit && get( end - 1 ) != 0 )
// {
// limit( end );
// }
// else
// {
// limit( end - 1 );
// }
// }
// else
// {
// while( remaining() >= 2 )
// {
// if( ( get() == 0 ) && ( get() == 0 ) )
// {
// break;
// }
// }
//
// end = position();
// if( end == oldLimit || end == oldLimit - 1 )
// {
// limit( end );
// }
// else
// {
// limit( end - 2 );
// }
// }
//
// position( oldPos );
// if( !hasRemaining() )
// {
// limit( oldLimit );
// position( end );
// return "";
// }
// decoder.reset();
//
// int expectedLength = (int)( remaining() * decoder.averageCharsPerByte() ) + 1;
// CharBuffer out = CharBuffer.allocate( expectedLength );
// for( ; ; )
// {
// CoderResult cr;
// if( hasRemaining() )
// {
// cr = decoder.decode( buf(), out, true );
// }
// else
// {
// cr = decoder.flush( out );
// }
//
// if( cr.isUnderflow() )
// {
// break;
// }
//
// if( cr.isOverflow() )
// {
// CharBuffer o = CharBuffer.allocate( out.capacity() + expectedLength );
// out.flip();
// o.put( out );
// out = o;
// continue;
// }
//
// cr.throwException();
// }
//
// limit( oldLimit );
// position( end );
// return out.flip().toString();
// }
/**
* Reads a <code>NUL</code>-terminated string from this buffer using the
* specified <code>decoder</code> and returns it.
*
* @param fieldSize the maximum number of bytes to read
*/
// public String getString( int fieldSize, CharsetDecoder decoder ) throws CharacterCodingException
// {
// checkFieldSize( fieldSize );
//
// if( fieldSize == 0 )
// {
// return "";
// }
//
// if( !hasRemaining() )
// {
// return "";
// }
//
// bool utf16 = decoder.charset().name().startsWith( "UTF-16" );
//
// if( utf16 && ( ( fieldSize & 1 ) != 0 ) )
// {
// throw new IllegalArgumentException( "fieldSize is not even." );
// }
//
// int oldPos = position();
// int oldLimit = limit();
// int end = position() + fieldSize;
//
// if( oldLimit < end )
// {
// throw new BufferUnderflowException();
// }
//
// int i;
//
// if( !utf16 )
// {
// for( i = 0; i < fieldSize; i ++ )
// {
// if( get() == 0 )
// {
// break;
// }
// }
//
// if( i == fieldSize )
// {
// limit( end );
// }
// else
// {
// limit( position() - 1 );
// }
// }
// else
// {
// for( i = 0; i < fieldSize; i += 2 )
// {
// if( ( get() == 0 ) && ( get() == 0 ) )
// {
// break;
// }
// }
//
// if( i == fieldSize )
// {
// limit( end );
// }
// else
// {
// limit( position() - 2 );
// }
// }
//
// position( oldPos );
// if( !hasRemaining() )
// {
// limit( oldLimit );
// position( end );
// return "";
// }
// decoder.reset();
//
// int expectedLength = (int)( remaining() * decoder.averageCharsPerByte() ) + 1;
// CharBuffer out = CharBuffer.allocate( expectedLength );
// for( ; ; )
// {
// CoderResult cr;
// if( hasRemaining() )
// {
// cr = decoder.decode( buf(), out, true );
// }
// else
// {
// cr = decoder.flush( out );
// }
//
// if( cr.isUnderflow() )
// {
// break;
// }
//
// if( cr.isOverflow() )
// {
// CharBuffer o = CharBuffer.allocate( out.capacity() + expectedLength );
// out.flip();
// o.put( out );
// out = o;
// continue;
// }
//
// cr.throwException();
// }
//
// limit( oldLimit );
// position( end );
// return out.flip().toString();
// }
/**
* Writes the content of <code>in</code> into this buffer using the
* specified <code>encoder</code>. This method doesn't terminate
* string with <tt>NUL</tt>. You have to do it by yourself.
*
* @throws BufferOverflowException if the specified string doesn't fit
*/
// public ByteBuffer putString(
// CharSequence val, CharsetEncoder encoder ) throws CharacterCodingException
// {
// if( val.length() == 0 )
// {
// return this;
// }
//
// CharBuffer in = CharBuffer.wrap( val );
// encoder.reset();
//
// int expandedState = 0;
//
// for( ; ; )
// {
// CoderResult cr;
// if( in.hasRemaining() )
// {
// cr = encoder.encode( in, buf(), true );
// }
// else
// {
// cr = encoder.flush( buf() );
// }
//
// if( cr.isUnderflow() )
// {
// break;
// }
// if( cr.isOverflow() )
// {
// if( isAutoExpand() )
// {
// switch( expandedState )
// {
// case 0:
// autoExpand( (int)Math.ceil( in.remaining() * encoder.averageBytesPerChar() ) );
// expandedState ++;
// break;
// case 1:
// autoExpand( (int)Math.ceil( in.remaining() * encoder.maxBytesPerChar() ) );
// expandedState ++;
// break;
// default:
// throw new RuntimeException( "Expanded by " +
// (int)Math.ceil( in.remaining() * encoder.maxBytesPerChar() ) +
// " but that wasn't enough for '" + val + "'" );
// }
// continue;
// }
// }
// else
// {
// expandedState = 0;
// }
// cr.throwException();
// }
// return this;
// }
/**
* Writes the content of <code>in</code> into this buffer as a
* <code>NUL</code>-terminated string using the specified
* <code>encoder</code>.
* <p>
* If the charset name of the encoder is UTF-16, you cannot specify
* odd <code>fieldSize</code>, and this method will Append two
* <code>NUL</code>s as a terminator.
* <p>
* Please note that this method doesn't terminate with <code>NUL</code>
* if the input string is longer than <tt>fieldSize</tt>.
*
* @param fieldSize the maximum number of bytes to write
*/
// public ByteBuffer putString(
// CharSequence val, int fieldSize, CharsetEncoder encoder ) throws CharacterCodingException
// {
// checkFieldSize( fieldSize );
//
// if( fieldSize == 0 )
// return this;
//
// autoExpand( fieldSize );
//
// bool utf16 = encoder.charset().name().startsWith( "UTF-16" );
//
// if( utf16 && ( ( fieldSize & 1 ) != 0 ) )
// {
// throw new IllegalArgumentException( "fieldSize is not even." );
// }
//
// int oldLimit = limit();
// int end = position() + fieldSize;
//
// if( oldLimit < end )
// {
// throw new BufferOverflowException();
// }
//
// if( val.length() == 0 )
// {
// if( !utf16 )
// {
// put( (byte)0x00 );
// }
// else
// {
// put( (byte)0x00 );
// put( (byte)0x00 );
// }
// position( end );
// return this;
// }
//
// CharBuffer in = CharBuffer.wrap( val );
// limit( end );
// encoder.reset();
//
// for( ; ; )
// {
// CoderResult cr;
// if( in.hasRemaining() )
// {
// cr = encoder.encode( in, buf(), true );
// }
// else
// {
// cr = encoder.flush( buf() );
// }
//
// if( cr.isUnderflow() || cr.isOverflow() )
// {
// break;
// }
// cr.throwException();
// }
//
// limit( oldLimit );
//
// if( position() < end )
// {
// if( !utf16 )
// {
// put( (byte)0x00 );
// }
// else
// {
// put( (byte)0x00 );
// put( (byte)0x00 );
// }
// }
//
// position( end );
// return this;
// }
/**
* Reads a string which has a 16-bit length field before the actual
* encoded string, using the specified <code>decoder</code> and returns it.
* This method is a shortcut for <tt>getPrefixedString(2, decoder)</tt>.
*/
// public String getPrefixedString( CharsetDecoder decoder ) throws CharacterCodingException
// {
// return getPrefixedString( 2, decoder );
// }
/**
* Reads a string which has a length field before the actual
* encoded string, using the specified <code>decoder</code> and returns it.
*
* @param prefixLength the length of the length field (1, 2, or 4)
*/
// public String getPrefixedString( int prefixLength, CharsetDecoder decoder ) throws CharacterCodingException
// {
// if( !prefixedDataAvailable( prefixLength ) )
// {
// throw new BufferUnderflowException();
// }
//
// int fieldSize = 0;
//
// switch( prefixLength )
// {
// case 1:
// fieldSize = getUnsigned();
// break;
// case 2:
// fieldSize = getUnsignedShort();
// break;
// case 4:
// fieldSize = getInt();
// break;
// }
//
// if( fieldSize == 0 )
// {
// return "";
// }
//
// bool utf16 = decoder.charset().name().startsWith( "UTF-16" );
//
// if( utf16 && ( ( fieldSize & 1 ) != 0 ) )
// {
// throw new BufferDataException( "fieldSize is not even for a UTF-16 string." );
// }
//
// int oldLimit = limit();
// int end = position() + fieldSize;
//
// if( oldLimit < end )
// {
// throw new BufferUnderflowException();
// }
//
// limit( end );
// decoder.reset();
//
// int expectedLength = (int)( remaining() * decoder.averageCharsPerByte() ) + 1;
// CharBuffer out = CharBuffer.allocate( expectedLength );
// for( ; ; )
// {
// CoderResult cr;
// if( hasRemaining() )
// {
// cr = decoder.decode( buf(), out, true );
// }
// else
// {
// cr = decoder.flush( out );
// }
//
// if( cr.isUnderflow() )
// {
// break;
// }
//
// if( cr.isOverflow() )
// {
// CharBuffer o = CharBuffer.allocate( out.capacity() + expectedLength );
// out.flip();
// o.put( out );
// out = o;
// continue;
// }
//
// cr.throwException();
// }
//
// limit( oldLimit );
// position( end );
// return out.flip().toString();
// }
/**
* Writes the content of <code>in</code> into this buffer as a
* string which has a 16-bit length field before the actual
* encoded string, using the specified <code>encoder</code>.
* This method is a shortcut for <tt>putPrefixedString(in, 2, 0, encoder)</tt>.
*
* @throws BufferOverflowException if the specified string doesn't fit
*/
// public ByteBuffer putPrefixedString( CharSequence in, CharsetEncoder encoder ) throws CharacterCodingException
// {
// return putPrefixedString( in, 2, 0, encoder );
// }
/**
* Writes the content of <code>in</code> into this buffer as a
* string which has a 16-bit length field before the actual
* encoded string, using the specified <code>encoder</code>.
* This method is a shortcut for <tt>putPrefixedString(in, prefixLength, 0, encoder)</tt>.
*
* @param prefixLength the length of the length field (1, 2, or 4)
*
* @throws BufferOverflowException if the specified string doesn't fit
*/
// public ByteBuffer putPrefixedString( CharSequence in, int prefixLength, CharsetEncoder encoder )
// throws CharacterCodingException
// {
// return putPrefixedString( in, prefixLength, 0, encoder );
// }
/**
* Writes the content of <code>in</code> into this buffer as a
* string which has a 16-bit length field before the actual
* encoded string, using the specified <code>encoder</code>.
* This method is a shortcut for <tt>putPrefixedString(in, prefixLength, padding, ( byte ) 0, encoder)</tt>.
*
* @param prefixLength the length of the length field (1, 2, or 4)
* @param padding the number of padded <tt>NUL</tt>s (1 (or 0), 2, or 4)
*
* @throws BufferOverflowException if the specified string doesn't fit
*/
// public ByteBuffer putPrefixedString( CharSequence in, int prefixLength, int padding, CharsetEncoder encoder )
// throws CharacterCodingException
// {
// return putPrefixedString( in, prefixLength, padding, (byte)0, encoder );
// }
/**
* Writes the content of <code>in</code> into this buffer as a
* string which has a 16-bit length field before the actual
* encoded string, using the specified <code>encoder</code>.
*
* @param prefixLength the length of the length field (1, 2, or 4)
* @param padding the number of padded bytes (1 (or 0), 2, or 4)
* @param padValue the value of padded bytes
*
* @throws BufferOverflowException if the specified string doesn't fit
*/
// public ByteBuffer putPrefixedString( CharSequence val,
// int prefixLength,
// int padding,
// byte padValue,
// CharsetEncoder encoder ) throws CharacterCodingException
// {
// int maxLength;
// switch( prefixLength )
// {
// case 1:
// maxLength = 255;
// break;
// case 2:
// maxLength = 65535;
// break;
// case 4:
// maxLength = Integer.MAX_VALUE;
// break;
// default:
// throw new IllegalArgumentException( "prefixLength: " + prefixLength );
// }
//
// if( val.length() > maxLength )
// {
// throw new IllegalArgumentException( "The specified string is too long." );
// }
// if( val.length() == 0 )
// {
// switch( prefixLength )
// {
// case 1:
// put( (byte)0 );
// break;
// case 2:
// putShort( (short)0 );
// break;
// case 4:
// putInt( 0 );
// break;
// }
// return this;
// }
//
// int padMask;
// switch( padding )
// {
// case 0:
// case 1:
// padMask = 0;
// break;
// case 2:
// padMask = 1;
// break;
// case 4:
// padMask = 3;
// break;
// default:
// throw new IllegalArgumentException( "padding: " + padding );
// }
//
// CharBuffer in = CharBuffer.wrap( val );
// int expectedLength = (int)( in.remaining() * encoder.averageBytesPerChar() ) + 1;
//
// skip( prefixLength ); // make a room for the length field
// int oldPos = position();
// encoder.reset();
//
// for( ; ; )
// {
// CoderResult cr;
// if( in.hasRemaining() )
// {
// cr = encoder.encode( in, buf(), true );
// }
// else
// {
// cr = encoder.flush( buf() );
// }
//
// if( position() - oldPos > maxLength )
// {
// throw new IllegalArgumentException( "The specified string is too long." );
// }
//
// if( cr.isUnderflow() )
// {
// break;
// }
// if( cr.isOverflow() && isAutoExpand() )
// {
// autoExpand( expectedLength );
// continue;
// }
// cr.throwException();
// }
//
// // Write the length field
// fill( padValue, padding - ( ( position() - oldPos ) & padMask ) );
// int length = position() - oldPos;
// switch( prefixLength )
// {
// case 1:
// put( oldPos - 1, (byte)length );
// break;
// case 2:
// putShort( oldPos - 2, (short)length );
// break;
// case 4:
// putInt( oldPos - 4, length );
// break;
// }
// return this;
// }
/**
* Reads a Java object from the buffer using the context {@link ClassLoader}
* of the current thread.
*/
// public Object getObject() throws ClassNotFoundException
// {
// return getObject( Thread.currentThread().getContextClassLoader() );
// }
/**
* Reads a Java object from the buffer using the specified <tt>classLoader</tt>.
*/
// public Object getObject( final ClassLoader classLoader ) throws ClassNotFoundException
// {
// if( !prefixedDataAvailable( 4 ) )
// {
// throw new BufferUnderflowException();
// }
//
// int length = getInt();
// if( length <= 4 )
// {
// throw new BufferDataException( "Object length should be greater than 4: " + length );
// }
//
// int oldLimit = limit();
// limit( position() + length );
// try
// {
// ObjectInputStream in = new ObjectInputStream( asInputStream() )
// {
// protected ObjectStreamClass readClassDescriptor() throws IOException, ClassNotFoundException
// {
// String className = readUTF();
// Class clazz = Class.forName( className, true, classLoader );
// return ObjectStreamClass.lookup( clazz );
// }
// };
// return in.readObject();
// }
// catch( IOException e )
// {
// throw new BufferDataException( e );
// }
// finally
// {
// limit( oldLimit );
// }
// }
/**
* Writes the specified Java object to the buffer.
*/
// public ByteBuffer putObject( Object o )
// {
// int oldPos = position();
// skip( 4 ); // Make a room for the length field.
// try
// {
// ObjectOutputStream out = new ObjectOutputStream( asOutputStream() )
// {
// protected void writeClassDescriptor( ObjectStreamClass desc ) throws IOException
// {
// writeUTF( desc.getName() );
// }
// };
// out.writeObject( o );
// out.flush();
// }
// catch( IOException e )
// {
// throw new BufferDataException( e );
// }
//
// // Fill the length field
// int newPos = position();
// position( oldPos );
// putInt( newPos - oldPos - 4 );
// position( newPos );
// return this;
// }
/**
* Returns <tt>true</tt> if this buffer contains a data which has a data
* length as a prefix and the buffer has remaining data as enough as
* specified in the data length field. This method is identical with
* <tt>prefixedDataAvailable( prefixLength, Integer.MAX_VALUE )</tt>.
* Please not that using this method can allow DoS (Denial of Service)
* attack in case the remote peer sends too big data length value.
* It is recommended to use {@link #prefixedDataAvailable(int, int)}
* instead.
*
* @param prefixLength the length of the prefix field (1, 2, or 4)
*
* @throws IllegalArgumentException if prefixLength is wrong
* @throws BufferDataException if data length is negative
*/
public bool prefixedDataAvailable( int prefixLength )
{
return prefixedDataAvailable( prefixLength, int.MaxValue);
}
/**
* Returns <tt>true</tt> if this buffer contains a data which has a data
* length as a prefix and the buffer has remaining data as enough as
* specified in the data length field.
*
* @param prefixLength the length of the prefix field (1, 2, or 4)
* @param maxDataLength the allowed maximum of the read data length
*
* @throws IllegalArgumentException if prefixLength is wrong
* @throws BufferDataException if data length is negative or greater then <tt>maxDataLength</tt>
*/
public bool prefixedDataAvailable( int prefixLength, int maxDataLength )
{
if( remaining() < prefixLength )
{
return false;
}
int dataLength;
switch( prefixLength )
{
case 1:
dataLength = getUnsigned( position() );
break;
case 2:
dataLength = getUnsignedShort( position() );
break;
case 4:
dataLength = getInt( position() );
break;
default:
throw new ArgumentException("prefixLength: " + prefixLength);
}
if( dataLength < 0 || dataLength > maxDataLength )
{
throw new BufferDataException( "dataLength: " + dataLength );
}
return remaining() - prefixLength >= dataLength;
}
//////////////////////////
// Skip or fill methods //
//////////////////////////
/**
* Forwards the position of this buffer as the specified <code>size</code>
* bytes.
*/
public ByteBuffer skip( int size )
{
autoExpand( size );
return position( position() + size );
}
/**
* Fills this buffer with the specified value.
* This method moves buffer position forward.
*/
// public ByteBuffer fill( byte value, int size )
// {
// autoExpand( size );
// int q = size >>> 3;
// int r = size & 7;
//
// if( q > 0 )
// {
// int intValue = value | ( value << 8 ) | ( value << 16 )
// | ( value << 24 );
// long longValue = intValue;
// longValue <<= 32;
// longValue |= intValue;
//
// for( int i = q; i > 0; i -- )
// {
// putLong( longValue );
// }
// }
//
// q = r >>> 2;
// r = r & 3;
//
// if( q > 0 )
// {
// int intValue = value | ( value << 8 ) | ( value << 16 )
// | ( value << 24 );
// putInt( intValue );
// }
//
// q = r >> 1;
// r = r & 1;
//
// if( q > 0 )
// {
// short shortValue = (short)( value | ( value << 8 ) );
// putShort( shortValue );
// }
//
// if( r > 0 )
// {
// put( value );
// }
//
// return this;
// }
/**
* Fills this buffer with the specified value.
* This method does not change buffer position.
*/
// public ByteBuffer fillAndReset( byte value, int size )
// {
// autoExpand( size );
// int pos = position();
// try
// {
// fill( value, size );
// }
// finally
// {
// position( pos );
// }
// return this;
// }
/**
* Fills this buffer with <code>NUL (0x00)</code>.
* This method moves buffer position forward.
*/
// public ByteBuffer fill( int size )
// {
// autoExpand( size );
// int q = size >>> 3;
// int r = size & 7;
//
// for( int i = q; i > 0; i -- )
// {
// putLong( 0L );
// }
//
// q = r >>> 2;
// r = r & 3;
//
// if( q > 0 )
// {
// putInt( 0 );
// }
//
// q = r >> 1;
// r = r & 1;
//
// if( q > 0 )
// {
// putShort( (short)0 );
// }
//
// if( r > 0 )
// {
// put( (byte)0 );
// }
//
// return this;
// }
/**
* Fills this buffer with <code>NUL (0x00)</code>.
* This method does not change buffer position.
*/
// public ByteBuffer fillAndReset( int size )
// {
// autoExpand( size );
// int pos = position();
// try
// {
// fill( size );
// }
// finally
// {
// position( pos );
// }
//
// return this;
// }
/**
* This method forwards the call to {@link #expand(int)} only when
* <tt>autoExpand</tt> property is <tt>true</tt>.
*/
protected ByteBuffer autoExpand( int expectedRemaining )
{
if( isAutoExpand() )
{
expand( expectedRemaining );
}
return this;
}
/**
* This method forwards the call to {@link #expand(int)} only when
* <tt>autoExpand</tt> property is <tt>true</tt>.
*/
protected ByteBuffer autoExpand( int pos, int expectedRemaining )
{
if( isAutoExpand() )
{
expand( pos, expectedRemaining );
}
return this;
}
private static void checkFieldSize( int fieldSize )
{
if( fieldSize < 0 )
{
throw new ArgumentOutOfRangeException("fieldSize");
}
}
public abstract void put(ushort value);
public abstract ushort GetUnsignedShort();
public abstract uint GetUnsignedInt();
public abstract void put(uint max);
public abstract void put(ulong tag);
public abstract ulong GetUnsignedLong();
}
}
|