You can not select more than 25 topics Topics must start with a chinese character,a letter or number, can include dashes ('-') and can be up to 35 characters long.

LineReader.cs 7.5 kB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231
  1. using System;
  2. using System.Text;
  3. namespace Shadowsocks.Util.Sockets
  4. {
  5. public class LineReader
  6. {
  7. private readonly WrappedSocket _socket;
  8. private readonly Func<string, object, bool> _onLineRead;
  9. private readonly Action<Exception, object> _onException;
  10. private readonly Action<byte[], int, int, object> _onFinish;
  11. private readonly Encoding _encoding;
  12. // private readonly string _delimiter;
  13. private readonly byte[] _delimiterBytes;
  14. private readonly int[] _delimiterSearchCharTable;
  15. private readonly int[] _delimiterSearchOffsetTable;
  16. private readonly object _state;
  17. private readonly byte[] _lineBuffer;
  18. private int _bufferIndex;
  19. public LineReader(WrappedSocket socket, Func<string, object, bool> onLineRead, Action<Exception, object> onException,
  20. Action<byte[], int, int, object> onFinish, Encoding encoding, string delimiter, int maxLineBytes, object state)
  21. {
  22. if (socket == null)
  23. {
  24. throw new ArgumentNullException(nameof(socket));
  25. }
  26. if (onLineRead == null)
  27. {
  28. throw new ArgumentNullException(nameof(onLineRead));
  29. }
  30. if (encoding == null)
  31. {
  32. throw new ArgumentNullException(nameof(encoding));
  33. }
  34. if (delimiter == null)
  35. {
  36. throw new ArgumentNullException(nameof(delimiter));
  37. }
  38. _socket = socket;
  39. _onLineRead = onLineRead;
  40. _onException = onException;
  41. _onFinish = onFinish;
  42. _encoding = encoding;
  43. // _delimiter = delimiter;
  44. _state = state;
  45. // decode delimiter
  46. _delimiterBytes = encoding.GetBytes(delimiter);
  47. if (_delimiterBytes.Length == 0)
  48. {
  49. throw new ArgumentException("Too short!", nameof(delimiter));
  50. }
  51. if (maxLineBytes < _delimiterBytes.Length)
  52. {
  53. throw new ArgumentException("Too small!", nameof(maxLineBytes));
  54. }
  55. _delimiterSearchCharTable = MakeCharTable(_delimiterBytes);
  56. _delimiterSearchOffsetTable = MakeOffsetTable(_delimiterBytes);
  57. _lineBuffer = new byte[maxLineBytes];
  58. // start reading
  59. socket.BeginReceive(_lineBuffer, 0, maxLineBytes, 0, ReceiveCallback, 0);
  60. }
  61. private void ReceiveCallback(IAsyncResult ar)
  62. {
  63. int length = (int)ar.AsyncState;
  64. try
  65. {
  66. var bytesRead = _socket.EndReceive(ar);
  67. if (bytesRead == 0)
  68. {
  69. OnFinish(length);
  70. return;
  71. }
  72. length += bytesRead;
  73. int i;
  74. while ((i = IndexOf(_lineBuffer, _bufferIndex, length, _delimiterBytes, _delimiterSearchOffsetTable,
  75. _delimiterSearchCharTable)) != -1)
  76. {
  77. var decodeLen = i - _bufferIndex;
  78. string line = _encoding.GetString(_lineBuffer, _bufferIndex, decodeLen);
  79. _bufferIndex = i + _delimiterBytes.Length;
  80. length -= decodeLen;
  81. length -= _delimiterBytes.Length;
  82. var stop = _onLineRead(line, _state);
  83. if (stop)
  84. {
  85. OnFinish(length);
  86. return;
  87. }
  88. }
  89. if (length == _lineBuffer.Length)
  90. {
  91. OnException(new IndexOutOfRangeException("LineBuffer full! Try increace maxLineBytes!"));
  92. OnFinish(length);
  93. return;
  94. }
  95. if (_bufferIndex > 0)
  96. {
  97. Buffer.BlockCopy(_lineBuffer, _bufferIndex, _lineBuffer, 0, length);
  98. _bufferIndex = 0;
  99. }
  100. _socket.BeginReceive(_lineBuffer, length, _lineBuffer.Length - length, 0, ReceiveCallback, length);
  101. }
  102. catch (Exception ex)
  103. {
  104. OnException(ex);
  105. OnFinish(length);
  106. }
  107. }
  108. private void OnException(Exception ex)
  109. {
  110. _onException?.Invoke(ex, _state);
  111. }
  112. private void OnFinish(int length)
  113. {
  114. _onFinish?.Invoke(_lineBuffer, _bufferIndex, length, _state);
  115. }
  116. #region Boyer-Moore string search
  117. public static int IndexOf(byte[] haystack, int index, int length, byte[] needle, int[] offsetTable, int[] charTable)
  118. {
  119. var end = index + length;
  120. for (int i = needle.Length - 1 + index, j; i < end;)
  121. {
  122. for (j = needle.Length - 1; needle[j] == haystack[i]; --i, --j)
  123. {
  124. if (j == 0)
  125. {
  126. return i;
  127. }
  128. }
  129. // i += needle.length - j; // For naive method
  130. i += Math.Max(offsetTable[needle.Length - 1 - j], charTable[haystack[i]]);
  131. }
  132. return -1;
  133. }
  134. /**
  135. * Makes the jump table based on the mismatched character information.
  136. */
  137. private static int[] MakeCharTable(byte[] needle)
  138. {
  139. const int ALPHABET_SIZE = 256;
  140. int[] table = new int[ALPHABET_SIZE];
  141. for (int i = 0; i < table.Length; ++i)
  142. {
  143. table[i] = needle.Length;
  144. }
  145. for (int i = 0; i < needle.Length - 1; ++i)
  146. {
  147. table[needle[i]] = needle.Length - 1 - i;
  148. }
  149. return table;
  150. }
  151. /**
  152. * Makes the jump table based on the scan offset which mismatch occurs.
  153. */
  154. private static int[] MakeOffsetTable(byte[] needle)
  155. {
  156. int[] table = new int[needle.Length];
  157. int lastPrefixPosition = needle.Length;
  158. for (int i = needle.Length - 1; i >= 0; --i)
  159. {
  160. if (IsPrefix(needle, i + 1))
  161. {
  162. lastPrefixPosition = i + 1;
  163. }
  164. table[needle.Length - 1 - i] = lastPrefixPosition - i + needle.Length - 1;
  165. }
  166. for (int i = 0; i < needle.Length - 1; ++i)
  167. {
  168. int slen = SuffixLength(needle, i);
  169. table[slen] = needle.Length - 1 - i + slen;
  170. }
  171. return table;
  172. }
  173. /**
  174. * Is needle[p:end] a prefix of needle?
  175. */
  176. private static bool IsPrefix(byte[] needle, int p)
  177. {
  178. for (int i = p, j = 0; i < needle.Length; ++i, ++j)
  179. {
  180. if (needle[i] != needle[j])
  181. {
  182. return false;
  183. }
  184. }
  185. return true;
  186. }
  187. /**
  188. * Returns the maximum length of the substring ends at p and is a suffix.
  189. */
  190. private static int SuffixLength(byte[] needle, int p)
  191. {
  192. int len = 0;
  193. for (int i = p, j = needle.Length - 1;
  194. i >= 0 && needle[i] == needle[j]; --i, --j)
  195. {
  196. len += 1;
  197. }
  198. return len;
  199. }
  200. #endregion
  201. }
  202. }