WritingPrimitives.cs 26 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654
  1. #region Copyright notice and license
  2. // Protocol Buffers - Google's data interchange format
  3. // Copyright 2008 Google Inc. All rights reserved.
  4. // https://developers.google.com/protocol-buffers/
  5. //
  6. // Redistribution and use in source and binary forms, with or without
  7. // modification, are permitted provided that the following conditions are
  8. // met:
  9. //
  10. // * Redistributions of source code must retain the above copyright
  11. // notice, this list of conditions and the following disclaimer.
  12. // * Redistributions in binary form must reproduce the above
  13. // copyright notice, this list of conditions and the following disclaimer
  14. // in the documentation and/or other materials provided with the
  15. // distribution.
  16. // * Neither the name of Google Inc. nor the names of its
  17. // contributors may be used to endorse or promote products derived from
  18. // this software without specific prior written permission.
  19. //
  20. // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
  21. // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
  22. // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
  23. // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
  24. // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
  25. // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
  26. // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
  27. // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
  28. // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
  29. // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
  30. // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  31. #endregion
  32. using System;
  33. using System.Buffers.Binary;
  34. using System.Runtime.CompilerServices;
  35. using System.Runtime.InteropServices;
  36. using System.Security;
  37. using System.Text;
  38. namespace Google.Protobuf
  39. {
  40. /// <summary>
  41. /// Primitives for encoding protobuf wire format.
  42. /// </summary>
  43. [SecuritySafeCritical]
  44. internal static class WritingPrimitives
  45. {
  46. // "Local" copy of Encoding.UTF8, for efficiency. (Yes, it makes a difference.)
  47. internal static readonly Encoding Utf8Encoding = Encoding.UTF8;
  48. #region Writing of values (not including tags)
  49. /// <summary>
  50. /// Writes a double field value, without a tag, to the stream.
  51. /// </summary>
  52. public static void WriteDouble(ref Span<byte> buffer, ref WriterInternalState state, double value)
  53. {
  54. WriteRawLittleEndian64(ref buffer, ref state, (ulong)BitConverter.DoubleToInt64Bits(value));
  55. }
  56. /// <summary>
  57. /// Writes a float field value, without a tag, to the stream.
  58. /// </summary>
  59. public static unsafe void WriteFloat(ref Span<byte> buffer, ref WriterInternalState state, float value)
  60. {
  61. const int length = sizeof(float);
  62. if (buffer.Length - state.position >= length)
  63. {
  64. // if there's enough space in the buffer, write the float directly into the buffer
  65. var floatSpan = buffer.Slice(state.position, length);
  66. Unsafe.WriteUnaligned(ref MemoryMarshal.GetReference(floatSpan), value);
  67. if (!BitConverter.IsLittleEndian)
  68. {
  69. floatSpan.Reverse();
  70. }
  71. state.position += length;
  72. }
  73. else
  74. {
  75. WriteFloatSlowPath(ref buffer, ref state, value);
  76. }
  77. }
  78. [MethodImpl(MethodImplOptions.NoInlining)]
  79. private static unsafe void WriteFloatSlowPath(ref Span<byte> buffer, ref WriterInternalState state, float value)
  80. {
  81. const int length = sizeof(float);
  82. // TODO(jtattermusch): deduplicate the code. Populating the span is the same as for the fastpath.
  83. Span<byte> floatSpan = stackalloc byte[length];
  84. Unsafe.WriteUnaligned(ref MemoryMarshal.GetReference(floatSpan), value);
  85. if (!BitConverter.IsLittleEndian)
  86. {
  87. floatSpan.Reverse();
  88. }
  89. WriteRawByte(ref buffer, ref state, floatSpan[0]);
  90. WriteRawByte(ref buffer, ref state, floatSpan[1]);
  91. WriteRawByte(ref buffer, ref state, floatSpan[2]);
  92. WriteRawByte(ref buffer, ref state, floatSpan[3]);
  93. }
  94. /// <summary>
  95. /// Writes a uint64 field value, without a tag, to the stream.
  96. /// </summary>
  97. public static void WriteUInt64(ref Span<byte> buffer, ref WriterInternalState state, ulong value)
  98. {
  99. WriteRawVarint64(ref buffer, ref state, value);
  100. }
  101. /// <summary>
  102. /// Writes an int64 field value, without a tag, to the stream.
  103. /// </summary>
  104. public static void WriteInt64(ref Span<byte> buffer, ref WriterInternalState state, long value)
  105. {
  106. WriteRawVarint64(ref buffer, ref state, (ulong)value);
  107. }
  108. /// <summary>
  109. /// Writes an int32 field value, without a tag, to the stream.
  110. /// </summary>
  111. public static void WriteInt32(ref Span<byte> buffer, ref WriterInternalState state, int value)
  112. {
  113. if (value >= 0)
  114. {
  115. WriteRawVarint32(ref buffer, ref state, (uint)value);
  116. }
  117. else
  118. {
  119. // Must sign-extend.
  120. WriteRawVarint64(ref buffer, ref state, (ulong)value);
  121. }
  122. }
  123. /// <summary>
  124. /// Writes a fixed64 field value, without a tag, to the stream.
  125. /// </summary>
  126. public static void WriteFixed64(ref Span<byte> buffer, ref WriterInternalState state, ulong value)
  127. {
  128. WriteRawLittleEndian64(ref buffer, ref state, value);
  129. }
  130. /// <summary>
  131. /// Writes a fixed32 field value, without a tag, to the stream.
  132. /// </summary>
  133. public static void WriteFixed32(ref Span<byte> buffer, ref WriterInternalState state, uint value)
  134. {
  135. WriteRawLittleEndian32(ref buffer, ref state, value);
  136. }
  137. /// <summary>
  138. /// Writes a bool field value, without a tag, to the stream.
  139. /// </summary>
  140. public static void WriteBool(ref Span<byte> buffer, ref WriterInternalState state, bool value)
  141. {
  142. WriteRawByte(ref buffer, ref state, value ? (byte)1 : (byte)0);
  143. }
  144. /// <summary>
  145. /// Writes a string field value, without a tag, to the stream.
  146. /// The data is length-prefixed.
  147. /// </summary>
  148. public static void WriteString(ref Span<byte> buffer, ref WriterInternalState state, string value)
  149. {
  150. const int MaxBytesPerChar = 3;
  151. const int MaxSmallStringLength = 128 / MaxBytesPerChar;
  152. // The string is small enough that the length will always be a 1 byte varint.
  153. // Also there is enough space to write length + bytes to buffer.
  154. // Write string directly to the buffer, and then write length.
  155. // This saves calling GetByteCount on the string. We get the string length from GetBytes.
  156. if (value.Length <= MaxSmallStringLength && buffer.Length - state.position - 1 >= value.Length * MaxBytesPerChar)
  157. {
  158. int indexOfLengthDelimiter = state.position++;
  159. buffer[indexOfLengthDelimiter] = (byte)WriteStringToBuffer(buffer, ref state, value);
  160. return;
  161. }
  162. int length = Utf8Encoding.GetByteCount(value);
  163. WriteLength(ref buffer, ref state, length);
  164. // Optimise the case where we have enough space to write
  165. // the string directly to the buffer, which should be common.
  166. if (buffer.Length - state.position >= length)
  167. {
  168. if (length == value.Length) // Must be all ASCII...
  169. {
  170. for (int i = 0; i < length; i++)
  171. {
  172. buffer[state.position + i] = (byte)value[i];
  173. }
  174. state.position += length;
  175. }
  176. else
  177. {
  178. WriteStringToBuffer(buffer, ref state, value);
  179. }
  180. }
  181. else
  182. {
  183. // Opportunity for future optimization:
  184. // Large strings that don't fit into the current buffer segment
  185. // can probably be optimized by using Utf8Encoding.GetEncoder()
  186. // but more benchmarks would need to be added as evidence.
  187. byte[] bytes = Utf8Encoding.GetBytes(value);
  188. WriteRawBytes(ref buffer, ref state, bytes);
  189. }
  190. }
  191. private static int WriteStringToBuffer(Span<byte> buffer, ref WriterInternalState state, string value)
  192. {
  193. #if NETSTANDARD1_1
  194. // slowpath when Encoding.GetBytes(Char*, Int32, Byte*, Int32) is not available
  195. byte[] bytes = Utf8Encoding.GetBytes(value);
  196. WriteRawBytes(ref buffer, ref state, bytes);
  197. return bytes.Length;
  198. #else
  199. ReadOnlySpan<char> source = value.AsSpan();
  200. int bytesUsed;
  201. unsafe
  202. {
  203. fixed (char* sourceChars = &MemoryMarshal.GetReference(source))
  204. fixed (byte* destinationBytes = &MemoryMarshal.GetReference(buffer))
  205. {
  206. bytesUsed = Utf8Encoding.GetBytes(
  207. sourceChars,
  208. source.Length,
  209. destinationBytes + state.position,
  210. buffer.Length - state.position);
  211. }
  212. }
  213. state.position += bytesUsed;
  214. return bytesUsed;
  215. #endif
  216. }
  217. /// <summary>
  218. /// Write a byte string, without a tag, to the stream.
  219. /// The data is length-prefixed.
  220. /// </summary>
  221. public static void WriteBytes(ref Span<byte> buffer, ref WriterInternalState state, ByteString value)
  222. {
  223. WriteLength(ref buffer, ref state, value.Length);
  224. WriteRawBytes(ref buffer, ref state, value.Span);
  225. }
  226. /// <summary>
  227. /// Writes a uint32 value, without a tag, to the stream.
  228. /// </summary>
  229. public static void WriteUInt32(ref Span<byte> buffer, ref WriterInternalState state, uint value)
  230. {
  231. WriteRawVarint32(ref buffer, ref state, value);
  232. }
  233. /// <summary>
  234. /// Writes an enum value, without a tag, to the stream.
  235. /// </summary>
  236. public static void WriteEnum(ref Span<byte> buffer, ref WriterInternalState state, int value)
  237. {
  238. WriteInt32(ref buffer, ref state, value);
  239. }
  240. /// <summary>
  241. /// Writes an sfixed32 value, without a tag, to the stream.
  242. /// </summary>
  243. public static void WriteSFixed32(ref Span<byte> buffer, ref WriterInternalState state, int value)
  244. {
  245. WriteRawLittleEndian32(ref buffer, ref state, (uint)value);
  246. }
  247. /// <summary>
  248. /// Writes an sfixed64 value, without a tag, to the stream.
  249. /// </summary>
  250. public static void WriteSFixed64(ref Span<byte> buffer, ref WriterInternalState state, long value)
  251. {
  252. WriteRawLittleEndian64(ref buffer, ref state, (ulong)value);
  253. }
  254. /// <summary>
  255. /// Writes an sint32 value, without a tag, to the stream.
  256. /// </summary>
  257. public static void WriteSInt32(ref Span<byte> buffer, ref WriterInternalState state, int value)
  258. {
  259. WriteRawVarint32(ref buffer, ref state, EncodeZigZag32(value));
  260. }
  261. /// <summary>
  262. /// Writes an sint64 value, without a tag, to the stream.
  263. /// </summary>
  264. public static void WriteSInt64(ref Span<byte> buffer, ref WriterInternalState state, long value)
  265. {
  266. WriteRawVarint64(ref buffer, ref state, EncodeZigZag64(value));
  267. }
  268. /// <summary>
  269. /// Writes a length (in bytes) for length-delimited data.
  270. /// </summary>
  271. /// <remarks>
  272. /// This method simply writes a rawint, but exists for clarity in calling code.
  273. /// </remarks>
  274. public static void WriteLength(ref Span<byte> buffer, ref WriterInternalState state, int length)
  275. {
  276. WriteRawVarint32(ref buffer, ref state, (uint)length);
  277. }
  278. #endregion
  279. #region Writing primitives
  280. /// <summary>
  281. /// Writes a 32 bit value as a varint. The fast route is taken when
  282. /// there's enough buffer space left to whizz through without checking
  283. /// for each byte; otherwise, we resort to calling WriteRawByte each time.
  284. /// </summary>
  285. public static void WriteRawVarint32(ref Span<byte> buffer, ref WriterInternalState state, uint value)
  286. {
  287. // Optimize for the common case of a single byte value
  288. if (value < 128 && state.position < buffer.Length)
  289. {
  290. buffer[state.position++] = (byte)value;
  291. return;
  292. }
  293. // Fast path when capacity is available
  294. while (state.position < buffer.Length)
  295. {
  296. if (value > 127)
  297. {
  298. buffer[state.position++] = (byte)((value & 0x7F) | 0x80);
  299. value >>= 7;
  300. }
  301. else
  302. {
  303. buffer[state.position++] = (byte)value;
  304. return;
  305. }
  306. }
  307. while (value > 127)
  308. {
  309. WriteRawByte(ref buffer, ref state, (byte)((value & 0x7F) | 0x80));
  310. value >>= 7;
  311. }
  312. WriteRawByte(ref buffer, ref state, (byte)value);
  313. }
  314. public static void WriteRawVarint64(ref Span<byte> buffer, ref WriterInternalState state, ulong value)
  315. {
  316. // Optimize for the common case of a single byte value
  317. if (value < 128 && state.position < buffer.Length)
  318. {
  319. buffer[state.position++] = (byte)value;
  320. return;
  321. }
  322. // Fast path when capacity is available
  323. while (state.position < buffer.Length)
  324. {
  325. if (value > 127)
  326. {
  327. buffer[state.position++] = (byte)((value & 0x7F) | 0x80);
  328. value >>= 7;
  329. }
  330. else
  331. {
  332. buffer[state.position++] = (byte)value;
  333. return;
  334. }
  335. }
  336. while (value > 127)
  337. {
  338. WriteRawByte(ref buffer, ref state, (byte)((value & 0x7F) | 0x80));
  339. value >>= 7;
  340. }
  341. WriteRawByte(ref buffer, ref state, (byte)value);
  342. }
  343. public static void WriteRawLittleEndian32(ref Span<byte> buffer, ref WriterInternalState state, uint value)
  344. {
  345. const int length = sizeof(uint);
  346. if (state.position + length > buffer.Length)
  347. {
  348. WriteRawLittleEndian32SlowPath(ref buffer, ref state, value);
  349. }
  350. else
  351. {
  352. BinaryPrimitives.WriteUInt32LittleEndian(buffer.Slice(state.position), value);
  353. state.position += length;
  354. }
  355. }
  356. [MethodImpl(MethodImplOptions.NoInlining)]
  357. private static void WriteRawLittleEndian32SlowPath(ref Span<byte> buffer, ref WriterInternalState state, uint value)
  358. {
  359. WriteRawByte(ref buffer, ref state, (byte)value);
  360. WriteRawByte(ref buffer, ref state, (byte)(value >> 8));
  361. WriteRawByte(ref buffer, ref state, (byte)(value >> 16));
  362. WriteRawByte(ref buffer, ref state, (byte)(value >> 24));
  363. }
  364. public static void WriteRawLittleEndian64(ref Span<byte> buffer, ref WriterInternalState state, ulong value)
  365. {
  366. const int length = sizeof(ulong);
  367. if (state.position + length > buffer.Length)
  368. {
  369. WriteRawLittleEndian64SlowPath(ref buffer, ref state, value);
  370. }
  371. else
  372. {
  373. BinaryPrimitives.WriteUInt64LittleEndian(buffer.Slice(state.position), value);
  374. state.position += length;
  375. }
  376. }
  377. [MethodImpl(MethodImplOptions.NoInlining)]
  378. public static void WriteRawLittleEndian64SlowPath(ref Span<byte> buffer, ref WriterInternalState state, ulong value)
  379. {
  380. WriteRawByte(ref buffer, ref state, (byte)value);
  381. WriteRawByte(ref buffer, ref state, (byte)(value >> 8));
  382. WriteRawByte(ref buffer, ref state, (byte)(value >> 16));
  383. WriteRawByte(ref buffer, ref state, (byte)(value >> 24));
  384. WriteRawByte(ref buffer, ref state, (byte)(value >> 32));
  385. WriteRawByte(ref buffer, ref state, (byte)(value >> 40));
  386. WriteRawByte(ref buffer, ref state, (byte)(value >> 48));
  387. WriteRawByte(ref buffer, ref state, (byte)(value >> 56));
  388. }
  389. private static void WriteRawByte(ref Span<byte> buffer, ref WriterInternalState state, byte value)
  390. {
  391. if (state.position == buffer.Length)
  392. {
  393. WriteBufferHelper.RefreshBuffer(ref buffer, ref state);
  394. }
  395. buffer[state.position++] = value;
  396. }
  397. /// <summary>
  398. /// Writes out an array of bytes.
  399. /// </summary>
  400. public static void WriteRawBytes(ref Span<byte> buffer, ref WriterInternalState state, byte[] value)
  401. {
  402. WriteRawBytes(ref buffer, ref state, new ReadOnlySpan<byte>(value));
  403. }
  404. /// <summary>
  405. /// Writes out part of an array of bytes.
  406. /// </summary>
  407. public static void WriteRawBytes(ref Span<byte> buffer, ref WriterInternalState state, byte[] value, int offset, int length)
  408. {
  409. WriteRawBytes(ref buffer, ref state, new ReadOnlySpan<byte>(value, offset, length));
  410. }
  411. /// <summary>
  412. /// Writes out part of an array of bytes.
  413. /// </summary>
  414. public static void WriteRawBytes(ref Span<byte> buffer, ref WriterInternalState state, ReadOnlySpan<byte> value)
  415. {
  416. if (buffer.Length - state.position >= value.Length)
  417. {
  418. // We have room in the current buffer.
  419. value.CopyTo(buffer.Slice(state.position, value.Length));
  420. state.position += value.Length;
  421. }
  422. else
  423. {
  424. // When writing to a CodedOutputStream backed by a Stream, we could avoid
  425. // copying the data twice (first copying to the current buffer and
  426. // and later writing from the current buffer to the underlying Stream)
  427. // in some circumstances by writing the data directly to the underlying Stream.
  428. // Current this is not being done to avoid specialcasing the code for
  429. // CodedOutputStream vs IBufferWriter<byte>.
  430. int bytesWritten = 0;
  431. while (buffer.Length - state.position < value.Length - bytesWritten)
  432. {
  433. int length = buffer.Length - state.position;
  434. value.Slice(bytesWritten, length).CopyTo(buffer.Slice(state.position, length));
  435. bytesWritten += length;
  436. state.position += length;
  437. WriteBufferHelper.RefreshBuffer(ref buffer, ref state);
  438. }
  439. // copy the remaining data
  440. int remainderLength = value.Length - bytesWritten;
  441. value.Slice(bytesWritten, remainderLength).CopyTo(buffer.Slice(state.position, remainderLength));
  442. state.position += remainderLength;
  443. }
  444. }
  445. #endregion
  446. #region Raw tag writing
  447. /// <summary>
  448. /// Encodes and writes a tag.
  449. /// </summary>
  450. public static void WriteTag(ref Span<byte> buffer, ref WriterInternalState state, int fieldNumber, WireFormat.WireType type)
  451. {
  452. WriteRawVarint32(ref buffer, ref state, WireFormat.MakeTag(fieldNumber, type));
  453. }
  454. /// <summary>
  455. /// Writes an already-encoded tag.
  456. /// </summary>
  457. public static void WriteTag(ref Span<byte> buffer, ref WriterInternalState state, uint tag)
  458. {
  459. WriteRawVarint32(ref buffer, ref state, tag);
  460. }
  461. /// <summary>
  462. /// Writes the given single-byte tag directly to the stream.
  463. /// </summary>
  464. public static void WriteRawTag(ref Span<byte> buffer, ref WriterInternalState state, byte b1)
  465. {
  466. WriteRawByte(ref buffer, ref state, b1);
  467. }
  468. /// <summary>
  469. /// Writes the given two-byte tag directly to the stream.
  470. /// </summary>
  471. public static void WriteRawTag(ref Span<byte> buffer, ref WriterInternalState state, byte b1, byte b2)
  472. {
  473. if (state.position + 2 > buffer.Length)
  474. {
  475. WriteRawTagSlowPath(ref buffer, ref state, b1, b2);
  476. }
  477. else
  478. {
  479. buffer[state.position++] = b1;
  480. buffer[state.position++] = b2;
  481. }
  482. }
  483. [MethodImpl(MethodImplOptions.NoInlining)]
  484. private static void WriteRawTagSlowPath(ref Span<byte> buffer, ref WriterInternalState state, byte b1, byte b2)
  485. {
  486. WriteRawByte(ref buffer, ref state, b1);
  487. WriteRawByte(ref buffer, ref state, b2);
  488. }
  489. /// <summary>
  490. /// Writes the given three-byte tag directly to the stream.
  491. /// </summary>
  492. public static void WriteRawTag(ref Span<byte> buffer, ref WriterInternalState state, byte b1, byte b2, byte b3)
  493. {
  494. if (state.position + 3 > buffer.Length)
  495. {
  496. WriteRawTagSlowPath(ref buffer, ref state, b1, b2, b3);
  497. }
  498. else
  499. {
  500. buffer[state.position++] = b1;
  501. buffer[state.position++] = b2;
  502. buffer[state.position++] = b3;
  503. }
  504. }
  505. [MethodImpl(MethodImplOptions.NoInlining)]
  506. private static void WriteRawTagSlowPath(ref Span<byte> buffer, ref WriterInternalState state, byte b1, byte b2, byte b3)
  507. {
  508. WriteRawByte(ref buffer, ref state, b1);
  509. WriteRawByte(ref buffer, ref state, b2);
  510. WriteRawByte(ref buffer, ref state, b3);
  511. }
  512. /// <summary>
  513. /// Writes the given four-byte tag directly to the stream.
  514. /// </summary>
  515. public static void WriteRawTag(ref Span<byte> buffer, ref WriterInternalState state, byte b1, byte b2, byte b3, byte b4)
  516. {
  517. if (state.position + 4 > buffer.Length)
  518. {
  519. WriteRawTagSlowPath(ref buffer, ref state, b1, b2, b3, b4);
  520. }
  521. else
  522. {
  523. buffer[state.position++] = b1;
  524. buffer[state.position++] = b2;
  525. buffer[state.position++] = b3;
  526. buffer[state.position++] = b4;
  527. }
  528. }
  529. [MethodImpl(MethodImplOptions.NoInlining)]
  530. private static void WriteRawTagSlowPath(ref Span<byte> buffer, ref WriterInternalState state, byte b1, byte b2, byte b3, byte b4)
  531. {
  532. WriteRawByte(ref buffer, ref state, b1);
  533. WriteRawByte(ref buffer, ref state, b2);
  534. WriteRawByte(ref buffer, ref state, b3);
  535. WriteRawByte(ref buffer, ref state, b4);
  536. }
  537. /// <summary>
  538. /// Writes the given five-byte tag directly to the stream.
  539. /// </summary>
  540. public static void WriteRawTag(ref Span<byte> buffer, ref WriterInternalState state, byte b1, byte b2, byte b3, byte b4, byte b5)
  541. {
  542. if (state.position + 5 > buffer.Length)
  543. {
  544. WriteRawTagSlowPath(ref buffer, ref state, b1, b2, b3, b4, b5);
  545. }
  546. else
  547. {
  548. buffer[state.position++] = b1;
  549. buffer[state.position++] = b2;
  550. buffer[state.position++] = b3;
  551. buffer[state.position++] = b4;
  552. buffer[state.position++] = b5;
  553. }
  554. }
  555. [MethodImpl(MethodImplOptions.NoInlining)]
  556. private static void WriteRawTagSlowPath(ref Span<byte> buffer, ref WriterInternalState state, byte b1, byte b2, byte b3, byte b4, byte b5)
  557. {
  558. WriteRawByte(ref buffer, ref state, b1);
  559. WriteRawByte(ref buffer, ref state, b2);
  560. WriteRawByte(ref buffer, ref state, b3);
  561. WriteRawByte(ref buffer, ref state, b4);
  562. WriteRawByte(ref buffer, ref state, b5);
  563. }
  564. #endregion
  565. /// <summary>
  566. /// Encode a 32-bit value with ZigZag encoding.
  567. /// </summary>
  568. /// <remarks>
  569. /// ZigZag encodes signed integers into values that can be efficiently
  570. /// encoded with varint. (Otherwise, negative values must be
  571. /// sign-extended to 64 bits to be varint encoded, thus always taking
  572. /// 10 bytes on the wire.)
  573. /// </remarks>
  574. public static uint EncodeZigZag32(int n)
  575. {
  576. // Note: the right-shift must be arithmetic
  577. return (uint)((n << 1) ^ (n >> 31));
  578. }
  579. /// <summary>
  580. /// Encode a 64-bit value with ZigZag encoding.
  581. /// </summary>
  582. /// <remarks>
  583. /// ZigZag encodes signed integers into values that can be efficiently
  584. /// encoded with varint. (Otherwise, negative values must be
  585. /// sign-extended to 64 bits to be varint encoded, thus always taking
  586. /// 10 bytes on the wire.)
  587. /// </remarks>
  588. public static ulong EncodeZigZag64(long n)
  589. {
  590. return (ulong)((n << 1) ^ (n >> 63));
  591. }
  592. }
  593. }