ByteBuffer.cs 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639
  1. namespace PlcSiemens.O
  2. {
  3. public static class ExtensionHelper
  4. {
  5. public static byte[] Reverse(this byte[] buf, int index, int length)
  6. {
  7. Array.Reverse(buf, index, length);
  8. return buf;
  9. }
  10. public static int CompareTo(this byte[] source, Int64 start, Int64 count, byte[] buffer, Int64 offset = 0, Int64 length = -1)
  11. {
  12. if (source == buffer) return 0;
  13. if (start < 0) start = 0;
  14. if (count <= 0 || count > source.Length - start) count = source.Length - start;
  15. if (length <= 0 || length > buffer.Length - offset) length = buffer.Length - offset;
  16. // 逐字节比较
  17. for (int i = 0; i < count && i < length; i++)
  18. {
  19. int rs = source[start + i].CompareTo(buffer[offset + i]);
  20. if (rs != 0) return i > 0 ? i : 1;
  21. }
  22. // 比较完成。如果长度不相等,则较长者较大
  23. if (count != length) return count > length ? 1 : -1;
  24. return 0;
  25. }
  26. }
  27. public class ByteBuffer
  28. {
  29. private readonly byte[] _bufferCache;
  30. /// <summary>
  31. /// 缓冲区
  32. /// </summary>
  33. public byte[] Buffer { get; private set; }
  34. /// <summary>
  35. /// 当前读取位置
  36. /// </summary>
  37. public int ReadIndex { get; private set; }
  38. /// <summary>
  39. /// 当前写入位置
  40. /// </summary>
  41. public int WriteIndex { get; private set; }
  42. /// <summary>
  43. /// 设置读取位置标记
  44. /// </summary>
  45. public int MarkReadIndex { get; private set; }
  46. /// <summary>
  47. /// 设置写入位置标记
  48. /// </summary>
  49. public int MarkWirteIndex { get; private set; }
  50. /// <summary>
  51. /// 当前缓冲大小
  52. /// </summary>
  53. public int Capacity { get; private set; }
  54. /// <summary>
  55. /// 缓冲扩充单位
  56. /// </summary>
  57. public int CapacityUnit { get; set; }
  58. /// <summary>
  59. /// 构造函数
  60. /// </summary>
  61. /// <param name="capacity"></param>
  62. private ByteBuffer(int capacity = 1024)
  63. {
  64. _bufferCache = new byte[0x10];
  65. Buffer = new byte[capacity];
  66. Capacity = capacity;
  67. CapacityUnit = Capacity;
  68. }
  69. /// <summary>
  70. /// 构建一个<see cref="ByteBuffer"/>对象
  71. /// </summary>
  72. /// <param name="capacity"></param>
  73. /// <returns></returns>
  74. public static ByteBuffer Allocate(int capacity = 1024)
  75. {
  76. return new ByteBuffer(capacity);
  77. }
  78. /// <summary>
  79. /// 计算扩容需量
  80. /// </summary>
  81. /// <param name="length"></param>
  82. /// <returns></returns>
  83. private int FixLength(int length)
  84. {
  85. int n = 2;
  86. int b = 2;
  87. while (b < length)
  88. {
  89. b = 2 << n;
  90. n++;
  91. }
  92. return (b / CapacityUnit + 1) * CapacityUnit;
  93. }
  94. /// <summary>
  95. /// 长度不够扩充<see cref="Buffer"/>容量
  96. /// </summary>
  97. /// <param name="currLen"></param>
  98. /// <param name="futureLen"></param>
  99. /// <returns></returns>
  100. private int FixSizeAndReset(int currLen, int futureLen)
  101. {
  102. if (futureLen > currLen)
  103. {
  104. int size = FixLength(currLen) + Capacity;
  105. byte[] newbuf = new byte[size];
  106. Array.Copy(Buffer, 0, newbuf, 0, currLen);
  107. Buffer = newbuf;
  108. Capacity = newbuf.Length;
  109. }
  110. return futureLen;
  111. }
  112. #region 压入对象
  113. public void Push(byte[] bytes, int startIndex, int length)
  114. {
  115. lock (this)
  116. {
  117. int offset = length - startIndex;
  118. if (offset <= 0) return;
  119. int total = offset + WriteIndex;
  120. int len = Buffer.Length;
  121. FixSizeAndReset(len, total);
  122. for (int i = WriteIndex, j = startIndex; i < total; i++, j++)
  123. {
  124. Buffer[i] = bytes[j];
  125. }
  126. WriteIndex = total;
  127. }
  128. }
  129. /// <summary>
  130. /// 写入字节数组
  131. /// </summary>
  132. /// <param name="bytes"></param>
  133. /// <param name="length"></param>
  134. /// <param name="reversed"></param>
  135. public void Push(byte[] bytes, int length, bool reversed = false)
  136. {
  137. if (reversed) bytes = bytes.Reverse(0, length);
  138. Push(bytes, 0, length);
  139. }
  140. /// <summary>
  141. /// 写入字节数组
  142. /// </summary>
  143. /// <param name="bytes"></param>
  144. /// <param name="reversed"></param>
  145. public void Push(byte[] bytes, bool reversed = false)
  146. {
  147. Push(bytes, bytes.Length, reversed);
  148. }
  149. /// <summary>
  150. /// 写入另一个<see cref="ByteBuffer"/>对象
  151. /// </summary>
  152. /// <param name="buffer"></param>
  153. /// <param name="reversed"></param>
  154. public void Push(ByteBuffer buffer, bool reversed = false)
  155. {
  156. if (buffer == null) return;
  157. if (buffer.ReadableBytes() <= 0) return;
  158. Push(buffer.ToArray(), reversed);
  159. }
  160. /// <summary>
  161. /// 写入一个<see cref="short"/>对象
  162. /// </summary>
  163. /// <param name="value"></param>
  164. /// <param name="reversed"></param>
  165. public void Push(short value, bool reversed = false)
  166. {
  167. Push((ushort)value, reversed);
  168. }
  169. /// <summary>
  170. /// 写入一个<see cref="ushort"/>对象
  171. /// </summary>
  172. /// <param name="value"></param>
  173. /// <param name="reversed"></param>
  174. public void Push(ushort value, bool reversed = false)
  175. {
  176. _bufferCache[0] = (byte)(value >> 8);
  177. _bufferCache[1] = (byte)value;
  178. Push(_bufferCache, 2, reversed);
  179. }
  180. public void Push(char value, bool reversed = false)
  181. {
  182. Push((short)value, reversed);
  183. }
  184. /// <summary>
  185. /// 写入一个<see cref="int"/>对象
  186. /// </summary>
  187. /// <param name="value"></param>
  188. /// <param name="reversed"></param>
  189. public void Push(int value, bool reversed = false)
  190. {
  191. Push((uint)value);
  192. }
  193. /// <summary>
  194. /// 写入一个<see cref="uint"/>对象
  195. /// </summary>
  196. /// <param name="value"></param>
  197. /// <param name="reversed"></param>
  198. public void Push(uint value, bool reversed = false)
  199. {
  200. _bufferCache[0] = (byte)(value >> 0x18);
  201. _bufferCache[1] = (byte)(value >> 0x10);
  202. _bufferCache[2] = (byte)(value >> 8);
  203. _bufferCache[3] = (byte)value;
  204. Push(_bufferCache, 4, reversed);
  205. }
  206. /// <summary>
  207. /// 写入一个<see cref="long"/>对象
  208. /// </summary>
  209. /// <param name="value"></param>
  210. /// <param name="reversed"></param>
  211. public void Push(long value, bool reversed = false)
  212. {
  213. Push((ulong)value);
  214. }
  215. /// <summary>
  216. /// 写入一个<see cref="ulong"/>对象
  217. /// </summary>
  218. /// <param name="value"></param>
  219. /// <param name="reversed"></param>
  220. public void Push(ulong value, bool reversed = false)
  221. {
  222. _bufferCache[0] = (byte)(value >> 0x38);
  223. _bufferCache[1] = (byte)(value >> 0x30);
  224. _bufferCache[2] = (byte)(value >> 0x28);
  225. _bufferCache[3] = (byte)(value >> 0x20);
  226. _bufferCache[4] = (byte)(value >> 0x18);
  227. _bufferCache[5] = (byte)(value >> 0x10);
  228. _bufferCache[6] = (byte)(value >> 8);
  229. _bufferCache[7] = (byte)value;
  230. Push(_bufferCache, 8, reversed);
  231. }
  232. /// <summary>
  233. /// 写入一个<see cref="float"/>对象
  234. /// </summary>
  235. /// <param name="value"></param>
  236. /// <param name="reversed"></param>
  237. public void Push(float value, bool reversed = false)
  238. {
  239. var buf = BitConverter.GetBytes(value);
  240. Push(buf, reversed);
  241. }
  242. /// <summary>
  243. /// 写入一个<see cref="byte"/>对象
  244. /// </summary>
  245. /// <param name="value"></param>
  246. public void Push(byte value)
  247. {
  248. lock (this)
  249. {
  250. int afterLen = WriteIndex + 1;
  251. int len = Buffer.Length;
  252. FixSizeAndReset(len, afterLen);
  253. Buffer[WriteIndex] = value;
  254. WriteIndex = afterLen;
  255. }
  256. }
  257. /// <summary>
  258. /// 写入一个<see cref="double"/>对象
  259. /// </summary>
  260. /// <param name="value"></param>
  261. /// <param name="reversed"></param>
  262. public void Push(double value, bool reversed = false)
  263. {
  264. var buf = BitConverter.GetBytes(value);
  265. Push(buf, reversed);
  266. }
  267. #endregion 压入对象
  268. #region pop出一个对象
  269. /// <summary>
  270. /// 读取一个<see cref="byte"/>
  271. /// </summary>
  272. /// <returns></returns>
  273. public byte PopByte()
  274. {
  275. byte b = Buffer[ReadIndex];
  276. ReadIndex++;
  277. return b;
  278. }
  279. /// <summary>
  280. /// 读取指定的<see cref="byte"/>[]
  281. /// </summary>
  282. /// <param name="len"></param>
  283. /// <param name="reversed"></param>
  284. /// <returns></returns>
  285. private byte[] Pop(int len, bool reversed = false)
  286. {
  287. byte[] bytes = new byte[len];
  288. Array.Copy(Buffer, ReadIndex, bytes, 0, len);
  289. if (reversed)
  290. Array.Reverse(bytes);
  291. ReadIndex += len;
  292. return bytes;
  293. }
  294. /// <summary>
  295. /// 读取指定的<see cref="ushort"/>
  296. /// </summary>
  297. /// <returns></returns>
  298. public ushort PopUshort(bool reversed = false)
  299. {
  300. var buf = Pop(2, reversed);
  301. return (ushort)(buf[0] << 8 | buf[1]);
  302. }
  303. /// <summary>
  304. /// 读取指定的<see cref="ushort"/>
  305. /// </summary>
  306. /// <returns></returns>
  307. public char PopChar(bool reversed = false)
  308. {
  309. var buf = Pop(2, reversed);
  310. return (char)(buf[0] << 8 | buf[1]);
  311. }
  312. /// <summary>
  313. /// 读取指定的<see cref="short"/>
  314. /// </summary>
  315. /// <param name="reversed"></param>
  316. /// <returns></returns>
  317. public short PopShort(bool reversed = false)
  318. {
  319. var buf = Pop(2, reversed);
  320. return (short)(buf[0] << 8 | buf[1]);
  321. }
  322. /// <summary>
  323. /// 读取指定的<see cref="uint"/>
  324. /// </summary>
  325. /// <param name="reversed"></param>
  326. /// <returns></returns>
  327. public uint PopUint(bool reversed = false)
  328. {
  329. var buf = Pop(4, reversed);
  330. return (uint)(buf[0] << 0x18 | buf[1] << 0x10 | buf[2] << 0x8 | buf[3]);
  331. }
  332. /// <summary>
  333. /// 读取指定的<see cref="int"/>
  334. /// </summary>
  335. /// <param name="reversed"></param>
  336. /// <returns></returns>
  337. public int PopInt(bool reversed = false)
  338. {
  339. var buf = Pop(4, reversed);
  340. return buf[0] << 0x18 |
  341. buf[1] << 0x10 |
  342. buf[2] << 0x8 |
  343. buf[3];
  344. }
  345. /// <summary>
  346. /// 读取指定的<see cref="ulong"/>
  347. /// </summary>
  348. /// <param name="reversed"></param>
  349. /// <returns></returns>
  350. public ulong PopUlong(bool reversed = false)
  351. {
  352. var buf = Pop(8, reversed);
  353. return (ulong)(buf[0] << 0x38 |
  354. buf[1] << 0x30 |
  355. buf[2] << 0x28 |
  356. buf[3] << 0x20 |
  357. buf[4] << 0x18 |
  358. buf[5] << 0x10 |
  359. buf[6] << 0x08 |
  360. buf[7]);
  361. }
  362. /// <summary>
  363. /// 读取指定的<see cref="long"/>
  364. /// </summary>
  365. /// <param name="reversed"></param>
  366. /// <returns></returns>
  367. public long PopLong(bool reversed = false)
  368. {
  369. var buf = Pop(8, reversed);
  370. return buf[0] << 0x38 |
  371. buf[1] << 0x30 |
  372. buf[2] << 0x28 |
  373. buf[3] << 0x20 |
  374. buf[4] << 0x18 |
  375. buf[5] << 0x10 |
  376. buf[6] << 0x08 |
  377. buf[7];
  378. }
  379. /// <summary>
  380. /// 读取指定的<see cref="float"/>
  381. /// </summary>
  382. /// <param name="reversed"></param>
  383. /// <returns></returns>
  384. public float PopFloat(bool reversed = false)
  385. {
  386. return BitConverter.ToSingle(Pop(4, reversed), 0);
  387. }
  388. /// <summary>
  389. /// 读取指定的<see cref="double"/>
  390. /// </summary>
  391. /// <param name="reversed"></param>
  392. /// <returns></returns>
  393. public double PopDouble(bool reversed = false)
  394. {
  395. return BitConverter.ToDouble(Pop(8, reversed), 0);
  396. }
  397. /// <summary>
  398. /// 读取指定长度的<see cref="byte"/>[]
  399. /// </summary>
  400. /// <param name="desBytes"></param>
  401. /// <param name="desStart"></param>
  402. /// <param name="len"></param>
  403. public void PopBytes(byte[] desBytes, int desStart, int len)
  404. {
  405. int size = desStart + len;
  406. for (int i = desStart; i < size; i++)
  407. {
  408. desBytes[i] = PopByte();
  409. }
  410. }
  411. public byte[] PopBytes(int len)
  412. {
  413. var buf = new byte[len];
  414. for (int i = 0; i < len; i++)
  415. {
  416. buf[i] = PopByte();
  417. }
  418. return buf;
  419. }
  420. #endregion pop出一个对象
  421. /// <summary>
  422. /// 清除已读缓冲 后续队列前移
  423. /// </summary>
  424. public void DiscardReadBytes()
  425. {
  426. if (ReadIndex <= 0) return;
  427. int len = Buffer.Length - ReadIndex;
  428. byte[] newbuf = new byte[Buffer.Length];
  429. Array.Copy(Buffer, ReadIndex, newbuf, 0, len);
  430. Buffer = newbuf;
  431. WriteIndex -= ReadIndex;
  432. MarkReadIndex -= ReadIndex;
  433. if (MarkReadIndex < 0)
  434. {
  435. MarkReadIndex = ReadIndex;
  436. }
  437. MarkWirteIndex -= ReadIndex;
  438. if (MarkWirteIndex < 0 || MarkWirteIndex < ReadIndex || MarkWirteIndex < MarkReadIndex)
  439. {
  440. MarkWirteIndex = WriteIndex;
  441. }
  442. ReadIndex = 0;
  443. }
  444. /// <summary>
  445. /// 清空缓存
  446. /// </summary>
  447. public void Clear()
  448. {
  449. Buffer = new byte[Buffer.Length];
  450. ReadIndex = 0;
  451. WriteIndex = 0;
  452. MarkReadIndex = 0;
  453. MarkWirteIndex = 0;
  454. }
  455. /// <summary>
  456. /// 设置缓存读取位置
  457. /// </summary>
  458. /// <param name="index"></param>
  459. public void SetReaderIndex(int index)
  460. {
  461. if (index < 0) return;
  462. ReadIndex = index;
  463. }
  464. /// <summary>
  465. /// 标记当前读取的索引位置
  466. /// </summary>
  467. public void MarkReaderIndex()
  468. {
  469. MarkReadIndex = ReadIndex;
  470. }
  471. /// <summary>
  472. /// 标记当前写入的索引位置
  473. /// </summary>
  474. public void MarkWriterIndex()
  475. {
  476. MarkWirteIndex = WriteIndex;
  477. }
  478. /// <summary>
  479. /// 将读取的索引位置重置为标记的读取索引位置
  480. /// </summary>
  481. public void ResetReaderIndex()
  482. {
  483. ReadIndex = MarkReadIndex;
  484. }
  485. /// <summary>
  486. /// 将写入的索引位置重置为标记的写入索引位置
  487. /// </summary>
  488. public void ResetWriterIndex()
  489. {
  490. WriteIndex = MarkWirteIndex;
  491. }
  492. /// <summary>
  493. /// 剩余可读数量
  494. /// </summary>
  495. /// <returns></returns>
  496. public int ReadableBytes()
  497. {
  498. return WriteIndex - ReadIndex;
  499. }
  500. /// <summary>
  501. /// 剩余可读缓存转数组
  502. /// </summary>
  503. /// <returns></returns>
  504. public byte[] ToArray()
  505. {
  506. byte[] bytes = new byte[WriteIndex];
  507. Array.Copy(Buffer, 0, bytes, 0, bytes.Length);
  508. return bytes;
  509. }
  510. public int IndexOf(byte[] buf, int offset = 0, int length = -1)
  511. {
  512. if (length <= 0) length = buf.Length - offset;
  513. // 位置
  514. int p = -1;
  515. for (int i = 0; i < length;)
  516. {
  517. if (ReadableBytes() < 1) return -1;
  518. int c = PopByte();
  519. if (c == -1) return -1;
  520. p++;
  521. if (c == buf[offset + i])
  522. {
  523. i++;
  524. // 全部匹配,退出
  525. if (i >= length) return p - length + 1;
  526. }
  527. else
  528. {
  529. int n = i;
  530. i = 0;
  531. for (int j = 1; j < n; j++)
  532. {
  533. // 在字节数组前(j,n)里面找自己(0,n-j)
  534. if (buf.CompareTo(j, n, buf, 0, n - j) == 0)
  535. {
  536. // 前面(0,n-j)相等,窗口退回到这里
  537. i = n - j;
  538. break;
  539. }
  540. }
  541. }
  542. }
  543. return -1;
  544. }
  545. public bool EnsureStartWith(byte[] buf, int offset = 0, int length = -1)
  546. {
  547. if (buf.Length < offset) throw new ArgumentOutOfRangeException("offset");
  548. if (offset < 0) offset = 0;
  549. if (length < 0 || buf.Length < (offset + length)) length = buf.Length - offset;
  550. int index = IndexOf(buf, offset, length);
  551. if (index == -1)
  552. {
  553. //重建缓冲清除数据
  554. //DiscardReadBytes();
  555. //不能重建缓冲 有可能尾部有数据部分匹配而导致数据丢失
  556. //重置ReaderIndex即可
  557. SetReaderIndex(0);
  558. return false;
  559. }
  560. if (index == 0) return true;
  561. SetReaderIndex(index);
  562. DiscardReadBytes();
  563. return true;
  564. }
  565. }
  566. }