Utf8Reader.cs 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446
  1. using System.Buffers;
  2. using System.Text;
  3. namespace Lua.Internal;
  4. sealed class Utf8Reader
  5. {
  6. [ThreadStatic]
  7. static byte[]? scratchBuffer;
  8. [ThreadStatic]
  9. internal static bool scratchBufferUsed;
  10. readonly byte[] buffer;
  11. int bufPos, bufLen;
  12. Decoder? decoder;
  13. const int ThreadStaticBufferSize = 1024;
  14. public Utf8Reader()
  15. {
  16. if (scratchBufferUsed)
  17. {
  18. buffer = new byte[ThreadStaticBufferSize];
  19. return;
  20. }
  21. scratchBuffer ??= new byte[ThreadStaticBufferSize];
  22. buffer = scratchBuffer;
  23. scratchBufferUsed = true;
  24. }
  25. public long Remain => bufLen - bufPos;
  26. public string? ReadLine(Stream stream, bool keepEol = false)
  27. {
  28. var resultBuffer = ArrayPool<byte>.Shared.Rent(1024);
  29. var lineLen = 0;
  30. try
  31. {
  32. while (true)
  33. {
  34. if (bufPos >= bufLen)
  35. {
  36. bufLen = stream.Read(buffer, 0, buffer.Length);
  37. bufPos = 0;
  38. if (bufLen == 0)
  39. {
  40. break; // EOF
  41. }
  42. }
  43. Span<byte> span = new(buffer, bufPos, bufLen - bufPos);
  44. var idx = span.IndexOfAny((byte)'\r', (byte)'\n');
  45. if (idx >= 0)
  46. {
  47. // Add the line content (before the newline)
  48. AppendToBuffer(ref resultBuffer, span[..idx], ref lineLen);
  49. var nl = span[idx];
  50. var eolStart = bufPos + idx;
  51. bufPos += idx + 1;
  52. // Handle CRLF - check if we have \r\n
  53. var isCRLF = false;
  54. if (nl == (byte)'\r' && bufPos < bufLen && buffer[bufPos] == (byte)'\n')
  55. {
  56. isCRLF = true;
  57. bufPos++; // Skip the \n as well
  58. }
  59. // Add end-of-line characters if keepEol is true
  60. if (keepEol)
  61. {
  62. if (isCRLF)
  63. {
  64. // Add \r\n
  65. AppendToBuffer(ref resultBuffer, new(new byte[] { (byte)'\r', (byte)'\n' }), ref lineLen);
  66. }
  67. else
  68. {
  69. // Add just the single newline character (\r or \n)
  70. AppendToBuffer(ref resultBuffer, new(new byte[] { nl }), ref lineLen);
  71. }
  72. }
  73. return Encoding.UTF8.GetString(resultBuffer, 0, lineLen);
  74. }
  75. else
  76. {
  77. // No newline found → add all to line buffer
  78. AppendToBuffer(ref resultBuffer, span, ref lineLen);
  79. bufPos = bufLen;
  80. }
  81. }
  82. if (lineLen == 0)
  83. {
  84. return null;
  85. }
  86. return Encoding.UTF8.GetString(resultBuffer, 0, lineLen);
  87. }
  88. finally
  89. {
  90. ArrayPool<byte>.Shared.Return(resultBuffer);
  91. }
  92. }
  93. public string ReadToEnd(Stream stream)
  94. {
  95. var resultBuffer = ArrayPool<byte>.Shared.Rent(1024);
  96. var len = 0;
  97. try
  98. {
  99. while (true)
  100. {
  101. if (bufPos >= bufLen)
  102. {
  103. bufLen = stream.Read(buffer, 0, buffer.Length);
  104. bufPos = 0;
  105. if (bufLen == 0)
  106. {
  107. break; // EOF
  108. }
  109. }
  110. Span<byte> span = new(buffer, bufPos, bufLen - bufPos);
  111. AppendToBuffer(ref resultBuffer, span, ref len);
  112. bufPos = bufLen;
  113. }
  114. if (len == 0)
  115. {
  116. return "";
  117. }
  118. return Encoding.UTF8.GetString(resultBuffer, 0, len);
  119. }
  120. finally
  121. {
  122. ArrayPool<byte>.Shared.Return(resultBuffer);
  123. }
  124. }
  125. public byte ReadByte(Stream stream)
  126. {
  127. if (buffer.Length == 0)
  128. {
  129. return 0;
  130. }
  131. var len = 0;
  132. while (len < 1)
  133. {
  134. if (bufPos >= bufLen)
  135. {
  136. bufLen = stream.Read(buffer, 0, buffer.Length);
  137. bufPos = 0;
  138. if (bufLen == 0)
  139. {
  140. break; // EOF
  141. }
  142. }
  143. var bytesToRead = Math.Min(1, bufLen - bufPos);
  144. if (bytesToRead == 0)
  145. {
  146. break;
  147. }
  148. if (bytesToRead > 0)
  149. {
  150. len += bytesToRead;
  151. }
  152. }
  153. return buffer[bufPos++];
  154. }
  155. public string? Read(Stream stream, int charCount)
  156. {
  157. if (charCount < 0)
  158. {
  159. throw new ArgumentOutOfRangeException(nameof(charCount));
  160. }
  161. if (charCount == 0)
  162. {
  163. return string.Empty;
  164. }
  165. var len = 0;
  166. var dataRead = false;
  167. var resultBuffer = ArrayPool<char>.Shared.Rent(charCount);
  168. try
  169. {
  170. while (len < charCount)
  171. {
  172. if (bufPos >= bufLen)
  173. {
  174. bufLen = stream.Read(buffer, 0, buffer.Length);
  175. bufPos = 0;
  176. if (bufLen == 0)
  177. {
  178. break; // EOF
  179. }
  180. }
  181. ReadOnlySpan<byte> byteSpan = new(buffer, bufPos, bufLen - bufPos);
  182. Span<char> charSpan = new(resultBuffer, len, charCount - len);
  183. decoder ??= Encoding.UTF8.GetDecoder();
  184. decoder.Convert(
  185. byteSpan,
  186. charSpan,
  187. false,
  188. out var bytesUsed,
  189. out var charsUsed,
  190. out _);
  191. if (charsUsed > 0)
  192. {
  193. len += charsUsed;
  194. dataRead = true;
  195. }
  196. bufPos += bytesUsed;
  197. if (bytesUsed == 0)
  198. {
  199. break;
  200. }
  201. }
  202. if (!dataRead || len != charCount)
  203. {
  204. return null;
  205. }
  206. return resultBuffer.AsSpan(0, len).ToString();
  207. }
  208. finally
  209. {
  210. ArrayPool<char>.Shared.Return(resultBuffer);
  211. }
  212. }
  213. static void AppendToBuffer(ref byte[] buffer, ReadOnlySpan<byte> segment, ref int length)
  214. {
  215. if (length + segment.Length > buffer.Length)
  216. {
  217. var newSize = Math.Max(buffer.Length * 2, length + segment.Length);
  218. var newBuffer = ArrayPool<byte>.Shared.Rent(newSize);
  219. Array.Copy(buffer, newBuffer, length);
  220. ArrayPool<byte>.Shared.Return(buffer);
  221. buffer = newBuffer;
  222. }
  223. segment.CopyTo(buffer.AsSpan(length));
  224. length += segment.Length;
  225. }
  226. public void Clear()
  227. {
  228. bufPos = 0;
  229. bufLen = 0;
  230. }
  231. public string? ReadNumber(Stream stream)
  232. {
  233. var resultBuffer = ArrayPool<char>.Shared.Rent(64); // Numbers shouldn't be too long
  234. var len = 0;
  235. var hasStarted = false;
  236. var isHex = false;
  237. var hasDecimal = false;
  238. var lastWasE = false;
  239. try
  240. {
  241. // Skip leading whitespace
  242. while (true)
  243. {
  244. var b = PeekByte(stream);
  245. if (b == -1)
  246. {
  247. return null; // EOF
  248. }
  249. var c = (char)b;
  250. if (!char.IsWhiteSpace(c))
  251. {
  252. break;
  253. }
  254. ReadByte(stream); // Consume whitespace
  255. }
  256. // Check for hex prefix at the start
  257. if (PeekByte(stream) == '0')
  258. {
  259. var nextByte = PeekByte(stream, 1);
  260. if (nextByte == 'x' || nextByte == 'X')
  261. {
  262. isHex = true;
  263. resultBuffer[len++] = '0';
  264. ReadByte(stream);
  265. resultBuffer[len++] = (char)ReadByte(stream);
  266. hasStarted = true;
  267. }
  268. }
  269. // Read number characters
  270. while (true)
  271. {
  272. var b = PeekByte(stream);
  273. if (b == -1)
  274. {
  275. break; // EOF
  276. }
  277. var c = (char)b;
  278. var shouldConsume = false;
  279. if (!hasStarted && (c == '+' || c == '-'))
  280. {
  281. shouldConsume = true;
  282. hasStarted = true;
  283. }
  284. else if (isHex)
  285. {
  286. // Hex digits
  287. if ((c >= '0' && c <= '9') || (c >= 'a' && c <= 'f') || (c >= 'A' && c <= 'F'))
  288. {
  289. shouldConsume = true;
  290. hasStarted = true;
  291. }
  292. // Hex decimal point
  293. else if (c == '.' && !hasDecimal)
  294. {
  295. shouldConsume = true;
  296. hasDecimal = true;
  297. }
  298. // Hex exponent (p or P)
  299. else if ((c == 'p' || c == 'P') && hasStarted)
  300. {
  301. shouldConsume = true;
  302. lastWasE = true;
  303. }
  304. // Sign after exponent
  305. else if (lastWasE && (c == '+' || c == '-'))
  306. {
  307. shouldConsume = true;
  308. lastWasE = false;
  309. }
  310. }
  311. else
  312. {
  313. // Decimal digits
  314. if (c >= '0' && c <= '9')
  315. {
  316. shouldConsume = true;
  317. hasStarted = true;
  318. lastWasE = false;
  319. }
  320. // Decimal point
  321. else if (c == '.' && !hasDecimal)
  322. {
  323. shouldConsume = true;
  324. hasDecimal = true;
  325. lastWasE = false;
  326. }
  327. // Exponent (e or E)
  328. else if ((c == 'e' || c == 'E') && hasStarted)
  329. {
  330. shouldConsume = true;
  331. lastWasE = true;
  332. }
  333. // Sign after exponent
  334. else if (lastWasE && (c == '+' || c == '-'))
  335. {
  336. shouldConsume = true;
  337. lastWasE = false;
  338. }
  339. }
  340. if (shouldConsume)
  341. {
  342. if (len >= resultBuffer.Length)
  343. {
  344. // Number too long, expand buffer
  345. var newBuffer = ArrayPool<char>.Shared.Rent(resultBuffer.Length * 2);
  346. resultBuffer.AsSpan(0, len).CopyTo(newBuffer);
  347. ArrayPool<char>.Shared.Return(resultBuffer);
  348. resultBuffer = newBuffer;
  349. }
  350. resultBuffer[len++] = c;
  351. ReadByte(stream); // Consume the byte
  352. }
  353. else
  354. {
  355. break; // Not part of the number
  356. }
  357. }
  358. return len == 0 ? null : resultBuffer.AsSpan(0, len).ToString();
  359. }
  360. finally
  361. {
  362. ArrayPool<char>.Shared.Return(resultBuffer);
  363. }
  364. }
  365. int PeekByte(Stream stream, int offset = 0)
  366. {
  367. // Ensure we have enough data in buffer
  368. while (bufPos + offset >= bufLen)
  369. {
  370. if (bufLen == 0 || bufPos == bufLen)
  371. {
  372. bufLen = stream.Read(buffer, 0, buffer.Length);
  373. bufPos = 0;
  374. if (bufLen == 0)
  375. {
  376. return -1; // EOF
  377. }
  378. }
  379. else
  380. {
  381. // We need more data but buffer has some - this shouldn't happen with small offsets
  382. return -1;
  383. }
  384. }
  385. return buffer[bufPos + offset];
  386. }
  387. public void Dispose()
  388. {
  389. scratchBufferUsed = false;
  390. }
  391. }