ParseContext.cs 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322
  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;
  34. using System.Buffers.Binary;
  35. using System.Collections.Generic;
  36. using System.IO;
  37. using System.Runtime.CompilerServices;
  38. using System.Runtime.InteropServices;
  39. using System.Security;
  40. using System.Text;
  41. using Google.Protobuf.Collections;
  42. namespace Google.Protobuf
  43. {
  44. /// <summary>
  45. /// An opaque struct that represents the current parsing state and is passed along
  46. /// as the parsing proceeds.
  47. /// All the public methods are intended to be invoked only by the generated code,
  48. /// users should never invoke them directly.
  49. /// </summary>
  50. [SecuritySafeCritical]
  51. public ref struct ParseContext
  52. {
  53. internal const int DefaultRecursionLimit = 100;
  54. internal const int DefaultSizeLimit = Int32.MaxValue;
  55. internal ReadOnlySpan<byte> buffer;
  56. internal ParserInternalState state;
  57. internal ParseContext(ref ReadOnlySpan<byte> buffer, ref ParserInternalState state)
  58. {
  59. this.buffer = buffer;
  60. this.state = state;
  61. }
  62. /// <summary>
  63. /// Creates a ParseContext instance from CodedInputStream.
  64. /// WARNING: internally this copies the CodedInputStream's state, so after done with the ParseContext,
  65. /// the CodedInputStream's state needs to be updated.
  66. /// </summary>
  67. internal ParseContext(CodedInputStream input)
  68. {
  69. this.buffer = new ReadOnlySpan<byte>(input.InternalBuffer);
  70. // TODO: ideally we would use a reference to the original state, but that doesn't seem possible
  71. this.state = input.InternalState; // creates copy of the state
  72. }
  73. internal ParseContext(ReadOnlySequence<byte> input) : this(input, DefaultRecursionLimit)
  74. {
  75. }
  76. internal ParseContext(ReadOnlySequence<byte> input, int recursionLimit)
  77. {
  78. this.buffer = default;
  79. this.state = default;
  80. this.state.lastTag = 0;
  81. this.state.recursionDepth = 0;
  82. this.state.sizeLimit = DefaultSizeLimit;
  83. this.state.recursionLimit = recursionLimit;
  84. this.state.currentLimit = int.MaxValue;
  85. this.state.segmentedBufferHelper = new SegmentedBufferHelper(input, out this.buffer);
  86. this.state.bufferPos = 0;
  87. this.state.bufferSize = this.buffer.Length;
  88. this.state.codedInputStream = null;
  89. this.state.DiscardUnknownFields = false;
  90. this.state.ExtensionRegistry = null;
  91. }
  92. /// <summary>
  93. /// Returns the last tag read, or 0 if no tags have been read or we've read beyond
  94. /// the end of the input.
  95. /// </summary>
  96. internal uint LastTag { get { return state.lastTag; } }
  97. /// <summary>
  98. /// Internal-only property; when set to true, unknown fields will be discarded while parsing.
  99. /// </summary>
  100. internal bool DiscardUnknownFields {
  101. get { return state.DiscardUnknownFields; }
  102. set { state.DiscardUnknownFields = value; }
  103. }
  104. /// <summary>
  105. /// Internal-only property; provides extension identifiers to compatible messages while parsing.
  106. /// </summary>
  107. internal ExtensionRegistry ExtensionRegistry
  108. {
  109. get { return state.ExtensionRegistry; }
  110. set { state.ExtensionRegistry = value; }
  111. }
  112. /// <summary>
  113. /// Reads a field tag, returning the tag of 0 for "end of input".
  114. /// </summary>
  115. /// <remarks>
  116. /// If this method returns 0, it doesn't necessarily mean the end of all
  117. /// the data in this CodedInputReader; it may be the end of the logical input
  118. /// for an embedded message, for example.
  119. /// </remarks>
  120. /// <returns>The next field tag, or 0 for end of input. (0 is never a valid tag.)</returns>
  121. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  122. public uint ReadTag()
  123. {
  124. return ParsingPrimitives.ParseTag(ref buffer, ref state);
  125. }
  126. /// <summary>
  127. /// Reads a double field from the input.
  128. /// </summary>
  129. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  130. public double ReadDouble()
  131. {
  132. return ParsingPrimitives.ParseDouble(ref buffer, ref state);
  133. }
  134. /// <summary>
  135. /// Reads a float field from the input.
  136. /// </summary>
  137. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  138. public float ReadFloat()
  139. {
  140. return ParsingPrimitives.ParseFloat(ref buffer, ref state);
  141. }
  142. /// <summary>
  143. /// Reads a uint64 field from the input.
  144. /// </summary>
  145. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  146. public ulong ReadUInt64()
  147. {
  148. return ParsingPrimitives.ParseRawVarint64(ref buffer, ref state);
  149. }
  150. /// <summary>
  151. /// Reads an int64 field from the input.
  152. /// </summary>
  153. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  154. public long ReadInt64()
  155. {
  156. return (long)ParsingPrimitives.ParseRawVarint64(ref buffer, ref state);
  157. }
  158. /// <summary>
  159. /// Reads an int32 field from the input.
  160. /// </summary>
  161. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  162. public int ReadInt32()
  163. {
  164. return (int)ParsingPrimitives.ParseRawVarint32(ref buffer, ref state);
  165. }
  166. /// <summary>
  167. /// Reads a fixed64 field from the input.
  168. /// </summary>
  169. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  170. public ulong ReadFixed64()
  171. {
  172. return ParsingPrimitives.ParseRawLittleEndian64(ref buffer, ref state);
  173. }
  174. /// <summary>
  175. /// Reads a fixed32 field from the input.
  176. /// </summary>
  177. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  178. public uint ReadFixed32()
  179. {
  180. return ParsingPrimitives.ParseRawLittleEndian32(ref buffer, ref state);
  181. }
  182. /// <summary>
  183. /// Reads a bool field from the input.
  184. /// </summary>
  185. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  186. public bool ReadBool()
  187. {
  188. return ParsingPrimitives.ParseRawVarint64(ref buffer, ref state) != 0;
  189. }
  190. /// <summary>
  191. /// Reads a string field from the input.
  192. /// </summary>
  193. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  194. public string ReadString()
  195. {
  196. int length = ParsingPrimitives.ParseLength(ref buffer, ref state);
  197. return ParsingPrimitives.ReadRawString(ref buffer, ref state, length);
  198. }
  199. /// <summary>
  200. /// Reads an embedded message field value from the input.
  201. /// </summary>
  202. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  203. public void ReadMessage(IMessage message)
  204. {
  205. // TODO: add a fallback if IMessage does not implement IBufferMessage
  206. ParsingPrimitivesMessages.ReadMessage(ref this, message);
  207. }
  208. /// <summary>
  209. /// Reads an embedded group field from the input.
  210. /// </summary>
  211. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  212. public void ReadGroup(IMessage message)
  213. {
  214. ParsingPrimitivesMessages.ReadGroup(ref this, message);
  215. }
  216. /// <summary>
  217. /// Reads a bytes field value from the input.
  218. /// </summary>
  219. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  220. public ByteString ReadBytes()
  221. {
  222. int length = ParsingPrimitives.ParseLength(ref buffer, ref state);
  223. return ByteString.AttachBytes(ParsingPrimitives.ReadRawBytes(ref buffer, ref state, length));
  224. }
  225. /// <summary>
  226. /// Reads a uint32 field value from the input.
  227. /// </summary>
  228. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  229. public uint ReadUInt32()
  230. {
  231. return ParsingPrimitives.ParseRawVarint32(ref buffer, ref state);
  232. }
  233. /// <summary>
  234. /// Reads an enum field value from the input.
  235. /// </summary>
  236. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  237. public int ReadEnum()
  238. {
  239. // Currently just a pass-through, but it's nice to separate it logically from WriteInt32.
  240. return (int)ParsingPrimitives.ParseRawVarint32(ref buffer, ref state);
  241. }
  242. /// <summary>
  243. /// Reads an sfixed32 field value from the input.
  244. /// </summary>
  245. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  246. public int ReadSFixed32()
  247. {
  248. return (int)ParsingPrimitives.ParseRawLittleEndian32(ref buffer, ref state);
  249. }
  250. /// <summary>
  251. /// Reads an sfixed64 field value from the input.
  252. /// </summary>
  253. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  254. public long ReadSFixed64()
  255. {
  256. return (long)ParsingPrimitives.ParseRawLittleEndian64(ref buffer, ref state);
  257. }
  258. /// <summary>
  259. /// Reads an sint32 field value from the input.
  260. /// </summary>
  261. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  262. public int ReadSInt32()
  263. {
  264. return ParsingPrimitives.DecodeZigZag32(ParsingPrimitives.ParseRawVarint32(ref buffer, ref state));
  265. }
  266. /// <summary>
  267. /// Reads an sint64 field value from the input.
  268. /// </summary>
  269. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  270. public long ReadSInt64()
  271. {
  272. return ParsingPrimitives.DecodeZigZag64(ParsingPrimitives.ParseRawVarint64(ref buffer, ref state));
  273. }
  274. /// <summary>
  275. /// Reads a length for length-delimited data.
  276. /// </summary>
  277. /// <remarks>
  278. /// This is internally just reading a varint, but this method exists
  279. /// to make the calling code clearer.
  280. /// </remarks>
  281. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  282. public int ReadLength()
  283. {
  284. return (int)ParsingPrimitives.ParseRawVarint32(ref buffer, ref state);
  285. }
  286. internal void CopyStateTo(CodedInputStream input)
  287. {
  288. input.InternalState = state;
  289. }
  290. }
  291. }