ProtoReader.cs 55 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421
  1. 
  2. using System;
  3. using System.IO;
  4. using System.Text;
  5. using ProtoBuf.Meta;
  6. #if FEAT_IKVM
  7. using Type = IKVM.Reflection.Type;
  8. #endif
  9. #if MF
  10. using EndOfStreamException = System.ApplicationException;
  11. using OverflowException = System.ApplicationException;
  12. #endif
  13. namespace ProtoBuf
  14. {
  15. /// <summary>
  16. /// A stateful reader, used to read a protobuf stream. Typical usage would be (sequentially) to call
  17. /// ReadFieldHeader and (after matching the field) an appropriate Read* method.
  18. /// </summary>
  19. public sealed class ProtoReader : IDisposable
  20. {
  21. Stream source;
  22. byte[] ioBuffer;
  23. TypeModel model;
  24. int fieldNumber, depth, dataRemaining, ioIndex, position, available, blockEnd;
  25. WireType wireType;
  26. bool isFixedLength, internStrings;
  27. private NetObjectCache netCache;
  28. // this is how many outstanding objects do not currently have
  29. // values for the purposes of reference tracking; we'll default
  30. // to just trapping the root object
  31. // note: objects are trapped (the ref and key mapped) via NoteObject
  32. uint trapCount; // uint is so we can use beq/bne more efficiently than bgt
  33. /// <summary>
  34. /// Gets the number of the field being processed.
  35. /// </summary>
  36. public int FieldNumber { get { return fieldNumber; } }
  37. /// <summary>
  38. /// Indicates the underlying proto serialization format on the wire.
  39. /// </summary>
  40. public WireType WireType { get { return wireType; } }
  41. /// <summary>
  42. /// Creates a new reader against a stream
  43. /// </summary>
  44. /// <param name="source">The source stream</param>
  45. /// <param name="model">The model to use for serialization; this can be null, but this will impair the ability to deserialize sub-objects</param>
  46. /// <param name="context">Additional context about this serialization operation</param>
  47. public ProtoReader(Stream source, TypeModel model, SerializationContext context)
  48. {
  49. Init(this, source, model, context, TO_EOF);
  50. }
  51. internal const int TO_EOF = -1;
  52. /// <summary>
  53. /// Gets / sets a flag indicating whether strings should be checked for repetition; if
  54. /// true, any repeated UTF-8 byte sequence will result in the same String instance, rather
  55. /// than a second instance of the same string. Enabled by default. Note that this uses
  56. /// a <i>custom</i> interner - the system-wide string interner is not used.
  57. /// </summary>
  58. public bool InternStrings { get { return internStrings; } set { internStrings = value; } }
  59. /// <summary>
  60. /// Creates a new reader against a stream
  61. /// </summary>
  62. /// <param name="source">The source stream</param>
  63. /// <param name="model">The model to use for serialization; this can be null, but this will impair the ability to deserialize sub-objects</param>
  64. /// <param name="context">Additional context about this serialization operation</param>
  65. /// <param name="length">The number of bytes to read, or -1 to read until the end of the stream</param>
  66. public ProtoReader(Stream source, TypeModel model, SerializationContext context, int length)
  67. {
  68. Init(this, source, model, context, length);
  69. }
  70. private static void Init(ProtoReader reader, Stream source, TypeModel model, SerializationContext context, int length)
  71. {
  72. if (source == null) throw new ArgumentNullException("source");
  73. if (!source.CanRead) throw new ArgumentException("Cannot read from stream", "source");
  74. reader.source = source;
  75. reader.ioBuffer = BufferPool.GetBuffer();
  76. reader.model = model;
  77. bool isFixedLength = length >= 0;
  78. reader.isFixedLength = isFixedLength;
  79. reader.dataRemaining = isFixedLength ? length : 0;
  80. if (context == null) { context = SerializationContext.Default; }
  81. else { context.Freeze(); }
  82. reader.context = context;
  83. reader.position = reader.available = reader.depth = reader.fieldNumber = reader.ioIndex = 0;
  84. reader.blockEnd = int.MaxValue;
  85. reader.internStrings = true;
  86. reader.wireType = WireType.None;
  87. reader.trapCount = 1;
  88. if(reader.netCache == null) reader.netCache = new NetObjectCache();
  89. }
  90. private SerializationContext context;
  91. /// <summary>
  92. /// Addition information about this deserialization operation.
  93. /// </summary>
  94. public SerializationContext Context { get { return context; } }
  95. /// <summary>
  96. /// Releases resources used by the reader, but importantly <b>does not</b> Dispose the
  97. /// underlying stream; in many typical use-cases the stream is used for different
  98. /// processes, so it is assumed that the consumer will Dispose their stream separately.
  99. /// </summary>
  100. public void Dispose()
  101. {
  102. // importantly, this does **not** own the stream, and does not dispose it
  103. source = null;
  104. model = null;
  105. BufferPool.ReleaseBufferToPool(ref ioBuffer);
  106. if(stringInterner != null) stringInterner.Clear();
  107. if(netCache != null) netCache.Clear();
  108. }
  109. internal int TryReadUInt32VariantWithoutMoving(bool trimNegative, out uint value)
  110. {
  111. if (available < 10) Ensure(10, false);
  112. if (available == 0)
  113. {
  114. value = 0;
  115. return 0;
  116. }
  117. int readPos = ioIndex;
  118. value = ioBuffer[readPos++];
  119. if ((value & 0x80) == 0) return 1;
  120. value &= 0x7F;
  121. if (available == 1) throw EoF(this);
  122. uint chunk = ioBuffer[readPos++];
  123. value |= (chunk & 0x7F) << 7;
  124. if ((chunk & 0x80) == 0) return 2;
  125. if (available == 2) throw EoF(this);
  126. chunk = ioBuffer[readPos++];
  127. value |= (chunk & 0x7F) << 14;
  128. if ((chunk & 0x80) == 0) return 3;
  129. if (available == 3) throw EoF(this);
  130. chunk = ioBuffer[readPos++];
  131. value |= (chunk & 0x7F) << 21;
  132. if ((chunk & 0x80) == 0) return 4;
  133. if (available == 4) throw EoF(this);
  134. chunk = ioBuffer[readPos];
  135. value |= chunk << 28; // can only use 4 bits from this chunk
  136. if ((chunk & 0xF0) == 0) return 5;
  137. if (trimNegative // allow for -ve values
  138. && (chunk & 0xF0) == 0xF0
  139. && available >= 10
  140. && ioBuffer[++readPos] == 0xFF
  141. && ioBuffer[++readPos] == 0xFF
  142. && ioBuffer[++readPos] == 0xFF
  143. && ioBuffer[++readPos] == 0xFF
  144. && ioBuffer[++readPos] == 0x01)
  145. {
  146. return 10;
  147. }
  148. throw AddErrorData(new OverflowException(), this);
  149. }
  150. private uint ReadUInt32Variant(bool trimNegative)
  151. {
  152. uint value;
  153. int read = TryReadUInt32VariantWithoutMoving(trimNegative, out value);
  154. if (read > 0)
  155. {
  156. ioIndex += read;
  157. available -= read;
  158. position += read;
  159. return value;
  160. }
  161. throw EoF(this);
  162. }
  163. private bool TryReadUInt32Variant(out uint value)
  164. {
  165. int read = TryReadUInt32VariantWithoutMoving(false, out value);
  166. if (read > 0)
  167. {
  168. ioIndex += read;
  169. available -= read;
  170. position += read;
  171. return true;
  172. }
  173. return false;
  174. }
  175. /// <summary>
  176. /// Reads an unsigned 32-bit integer from the stream; supported wire-types: Variant, Fixed32, Fixed64
  177. /// </summary>
  178. public uint ReadUInt32()
  179. {
  180. switch (wireType)
  181. {
  182. case WireType.Variant:
  183. return ReadUInt32Variant(false);
  184. case WireType.Fixed32:
  185. if (available < 4) Ensure(4, true);
  186. position += 4;
  187. available -= 4;
  188. return ((uint)ioBuffer[ioIndex++])
  189. | (((uint)ioBuffer[ioIndex++]) << 8)
  190. | (((uint)ioBuffer[ioIndex++]) << 16)
  191. | (((uint)ioBuffer[ioIndex++]) << 24);
  192. case WireType.Fixed64:
  193. ulong val = ReadUInt64();
  194. checked { return (uint)val; }
  195. default:
  196. throw CreateWireTypeException();
  197. }
  198. }
  199. /// <summary>
  200. /// Returns the position of the current reader (note that this is not necessarily the same as the position
  201. /// in the underlying stream, if multiple readers are used on the same stream)
  202. /// </summary>
  203. public int Position { get { return position; } }
  204. internal void Ensure(int count, bool strict)
  205. {
  206. Helpers.DebugAssert(available <= count, "Asking for data without checking first");
  207. if (count > ioBuffer.Length)
  208. {
  209. BufferPool.ResizeAndFlushLeft(ref ioBuffer, count, ioIndex, available);
  210. ioIndex = 0;
  211. }
  212. else if (ioIndex + count >= ioBuffer.Length)
  213. {
  214. // need to shift the buffer data to the left to make space
  215. Helpers.BlockCopy(ioBuffer, ioIndex, ioBuffer, 0, available);
  216. ioIndex = 0;
  217. }
  218. count -= available;
  219. int writePos = ioIndex + available, bytesRead;
  220. int canRead = ioBuffer.Length - writePos;
  221. if (isFixedLength)
  222. { // throttle it if needed
  223. if (dataRemaining < canRead) canRead = dataRemaining;
  224. }
  225. while (count > 0 && canRead > 0 && (bytesRead = source.Read(ioBuffer, writePos, canRead)) > 0)
  226. {
  227. available += bytesRead;
  228. count -= bytesRead;
  229. canRead -= bytesRead;
  230. writePos += bytesRead;
  231. if (isFixedLength) { dataRemaining -= bytesRead; }
  232. }
  233. if (strict && count > 0)
  234. {
  235. throw EoF(this);
  236. }
  237. }
  238. /// <summary>
  239. /// Reads a signed 16-bit integer from the stream: Variant, Fixed32, Fixed64, SignedVariant
  240. /// </summary>
  241. public short ReadInt16()
  242. {
  243. checked { return (short)ReadInt32(); }
  244. }
  245. /// <summary>
  246. /// Reads an unsigned 16-bit integer from the stream; supported wire-types: Variant, Fixed32, Fixed64
  247. /// </summary>
  248. public ushort ReadUInt16()
  249. {
  250. checked { return (ushort)ReadUInt32(); }
  251. }
  252. /// <summary>
  253. /// Reads an unsigned 8-bit integer from the stream; supported wire-types: Variant, Fixed32, Fixed64
  254. /// </summary>
  255. public byte ReadByte()
  256. {
  257. checked { return (byte)ReadUInt32(); }
  258. }
  259. /// <summary>
  260. /// Reads a signed 8-bit integer from the stream; supported wire-types: Variant, Fixed32, Fixed64, SignedVariant
  261. /// </summary>
  262. public sbyte ReadSByte()
  263. {
  264. checked { return (sbyte)ReadInt32(); }
  265. }
  266. /// <summary>
  267. /// Reads a signed 32-bit integer from the stream; supported wire-types: Variant, Fixed32, Fixed64, SignedVariant
  268. /// </summary>
  269. public int ReadInt32()
  270. {
  271. switch (wireType)
  272. {
  273. case WireType.Variant:
  274. return (int)ReadUInt32Variant(true);
  275. case WireType.Fixed32:
  276. if (available < 4) Ensure(4, true);
  277. position += 4;
  278. available -= 4;
  279. return ((int)ioBuffer[ioIndex++])
  280. | (((int)ioBuffer[ioIndex++]) << 8)
  281. | (((int)ioBuffer[ioIndex++]) << 16)
  282. | (((int)ioBuffer[ioIndex++]) << 24);
  283. case WireType.Fixed64:
  284. long l = ReadInt64();
  285. checked { return (int)l; }
  286. case WireType.SignedVariant:
  287. return Zag(ReadUInt32Variant(true));
  288. default:
  289. throw CreateWireTypeException();
  290. }
  291. }
  292. private const long Int64Msb = ((long)1) << 63;
  293. private const int Int32Msb = ((int)1) << 31;
  294. private static int Zag(uint ziggedValue)
  295. {
  296. int value = (int)ziggedValue;
  297. return (-(value & 0x01)) ^ ((value >> 1) & ~ProtoReader.Int32Msb);
  298. }
  299. private static long Zag(ulong ziggedValue)
  300. {
  301. long value = (long)ziggedValue;
  302. return (-(value & 0x01L)) ^ ((value >> 1) & ~ProtoReader.Int64Msb);
  303. }
  304. /// <summary>
  305. /// Reads a signed 64-bit integer from the stream; supported wire-types: Variant, Fixed32, Fixed64, SignedVariant
  306. /// </summary>
  307. public long ReadInt64()
  308. {
  309. switch (wireType)
  310. {
  311. case WireType.Variant:
  312. return (long)ReadUInt64Variant();
  313. case WireType.Fixed32:
  314. return ReadInt32();
  315. case WireType.Fixed64:
  316. if (available < 8) Ensure(8, true);
  317. position += 8;
  318. available -= 8;
  319. return ((long)ioBuffer[ioIndex++])
  320. | (((long)ioBuffer[ioIndex++]) << 8)
  321. | (((long)ioBuffer[ioIndex++]) << 16)
  322. | (((long)ioBuffer[ioIndex++]) << 24)
  323. | (((long)ioBuffer[ioIndex++]) << 32)
  324. | (((long)ioBuffer[ioIndex++]) << 40)
  325. | (((long)ioBuffer[ioIndex++]) << 48)
  326. | (((long)ioBuffer[ioIndex++]) << 56);
  327. case WireType.SignedVariant:
  328. return Zag(ReadUInt64Variant());
  329. default:
  330. throw CreateWireTypeException();
  331. }
  332. }
  333. private int TryReadUInt64VariantWithoutMoving(out ulong value)
  334. {
  335. if (available < 10) Ensure(10, false);
  336. if (available == 0)
  337. {
  338. value = 0;
  339. return 0;
  340. }
  341. int readPos = ioIndex;
  342. value = ioBuffer[readPos++];
  343. if ((value & 0x80) == 0) return 1;
  344. value &= 0x7F;
  345. if (available == 1) throw EoF(this);
  346. ulong chunk = ioBuffer[readPos++];
  347. value |= (chunk & 0x7F) << 7;
  348. if ((chunk & 0x80) == 0) return 2;
  349. if (available == 2) throw EoF(this);
  350. chunk = ioBuffer[readPos++];
  351. value |= (chunk & 0x7F) << 14;
  352. if ((chunk & 0x80) == 0) return 3;
  353. if (available == 3) throw EoF(this);
  354. chunk = ioBuffer[readPos++];
  355. value |= (chunk & 0x7F) << 21;
  356. if ((chunk & 0x80) == 0) return 4;
  357. if (available == 4) throw EoF(this);
  358. chunk = ioBuffer[readPos++];
  359. value |= (chunk & 0x7F) << 28;
  360. if ((chunk & 0x80) == 0) return 5;
  361. if (available == 5) throw EoF(this);
  362. chunk = ioBuffer[readPos++];
  363. value |= (chunk & 0x7F) << 35;
  364. if ((chunk & 0x80) == 0) return 6;
  365. if (available == 6) throw EoF(this);
  366. chunk = ioBuffer[readPos++];
  367. value |= (chunk & 0x7F) << 42;
  368. if ((chunk & 0x80) == 0) return 7;
  369. if (available == 7) throw EoF(this);
  370. chunk = ioBuffer[readPos++];
  371. value |= (chunk & 0x7F) << 49;
  372. if ((chunk & 0x80) == 0) return 8;
  373. if (available == 8) throw EoF(this);
  374. chunk = ioBuffer[readPos++];
  375. value |= (chunk & 0x7F) << 56;
  376. if ((chunk & 0x80) == 0) return 9;
  377. if (available == 9) throw EoF(this);
  378. chunk = ioBuffer[readPos];
  379. value |= chunk << 63; // can only use 1 bit from this chunk
  380. if ((chunk & ~(ulong)0x01) != 0) throw AddErrorData(new OverflowException(), this);
  381. return 10;
  382. }
  383. private ulong ReadUInt64Variant()
  384. {
  385. ulong value;
  386. int read = TryReadUInt64VariantWithoutMoving(out value);
  387. if (read > 0)
  388. {
  389. ioIndex += read;
  390. available -= read;
  391. position += read;
  392. return value;
  393. }
  394. throw EoF(this);
  395. }
  396. #if NO_GENERICS
  397. private System.Collections.Hashtable stringInterner;
  398. private string Intern(string value)
  399. {
  400. if (value == null) return null;
  401. if (value.Length == 0) return "";
  402. if (stringInterner == null)
  403. {
  404. stringInterner = new System.Collections.Hashtable();
  405. stringInterner.Add(value, value);
  406. }
  407. else if (stringInterner.ContainsKey(value))
  408. {
  409. value = (string)stringInterner[value];
  410. }
  411. else
  412. {
  413. stringInterner.Add(value, value);
  414. }
  415. return value;
  416. }
  417. #else
  418. private System.Collections.Generic.Dictionary<string,string> stringInterner;
  419. private string Intern(string value)
  420. {
  421. if (value == null) return null;
  422. if (value.Length == 0) return "";
  423. string found;
  424. if (stringInterner == null)
  425. {
  426. stringInterner = new System.Collections.Generic.Dictionary<string, string>();
  427. stringInterner.Add(value, value);
  428. }
  429. else if (stringInterner.TryGetValue(value, out found))
  430. {
  431. value = found;
  432. }
  433. else
  434. {
  435. stringInterner.Add(value, value);
  436. }
  437. return value;
  438. }
  439. #endif
  440. #if COREFX
  441. static readonly Encoding encoding = Encoding.UTF8;
  442. #else
  443. static readonly UTF8Encoding encoding = new UTF8Encoding();
  444. #endif
  445. /// <summary>
  446. /// Reads a string from the stream (using UTF8); supported wire-types: String
  447. /// </summary>
  448. public string ReadString()
  449. {
  450. if (wireType == WireType.String)
  451. {
  452. int bytes = (int)ReadUInt32Variant(false);
  453. if (bytes == 0) return "";
  454. if (available < bytes) Ensure(bytes, true);
  455. #if MF
  456. byte[] tmp;
  457. if(ioIndex == 0 && bytes == ioBuffer.Length) {
  458. // unlikely, but...
  459. tmp = ioBuffer;
  460. } else {
  461. tmp = new byte[bytes];
  462. Helpers.BlockCopy(ioBuffer, ioIndex, tmp, 0, bytes);
  463. }
  464. string s = new string(encoding.GetChars(tmp));
  465. #else
  466. string s = encoding.GetString(ioBuffer, ioIndex, bytes);
  467. #endif
  468. if (internStrings) { s = Intern(s); }
  469. available -= bytes;
  470. position += bytes;
  471. ioIndex += bytes;
  472. return s;
  473. }
  474. throw CreateWireTypeException();
  475. }
  476. /// <summary>
  477. /// Throws an exception indication that the given value cannot be mapped to an enum.
  478. /// </summary>
  479. public void ThrowEnumException(System.Type type, int value)
  480. {
  481. string desc = type == null ? "<null>" : type.FullName;
  482. throw AddErrorData(new ProtoException("No " + desc + " enum is mapped to the wire-value " + value.ToString()), this);
  483. }
  484. private Exception CreateWireTypeException()
  485. {
  486. return CreateException("Invalid wire-type; this usually means you have over-written a file without truncating or setting the length; see http://stackoverflow.com/q/2152978/23354");
  487. }
  488. private Exception CreateException(string message)
  489. {
  490. return AddErrorData(new ProtoException(message), this);
  491. }
  492. /// <summary>
  493. /// Reads a double-precision number from the stream; supported wire-types: Fixed32, Fixed64
  494. /// </summary>
  495. public
  496. #if !FEAT_SAFE
  497. unsafe
  498. #endif
  499. double ReadDouble()
  500. {
  501. switch (wireType)
  502. {
  503. case WireType.Fixed32:
  504. return ReadSingle();
  505. case WireType.Fixed64:
  506. long value = ReadInt64();
  507. #if FEAT_SAFE
  508. return BitConverter.ToDouble(BitConverter.GetBytes(value), 0);
  509. #else
  510. return *(double*)&value;
  511. #endif
  512. default:
  513. throw CreateWireTypeException();
  514. }
  515. }
  516. /// <summary>
  517. /// Reads (merges) a sub-message from the stream, internally calling StartSubItem and EndSubItem, and (in between)
  518. /// parsing the message in accordance with the model associated with the reader
  519. /// </summary>
  520. public static object ReadObject(object value, int key, ProtoReader reader)
  521. {
  522. #if FEAT_IKVM
  523. throw new NotSupportedException();
  524. #else
  525. return ReadTypedObject(value, key, reader, null);
  526. #endif
  527. }
  528. #if !FEAT_IKVM
  529. internal static object ReadTypedObject(object value, int key, ProtoReader reader, Type type)
  530. {
  531. if (reader.model == null)
  532. {
  533. throw AddErrorData(new InvalidOperationException("Cannot deserialize sub-objects unless a model is provided"), reader);
  534. }
  535. SubItemToken token = ProtoReader.StartSubItem(reader);
  536. if (key >= 0)
  537. {
  538. value = reader.model.Deserialize(key, value, reader);
  539. }
  540. else if (type != null && reader.model.TryDeserializeAuxiliaryType(reader, DataFormat.Default, Serializer.ListItemTag, type, ref value, true, false, true, false))
  541. {
  542. // ok
  543. }
  544. else
  545. {
  546. TypeModel.ThrowUnexpectedType(type);
  547. }
  548. ProtoReader.EndSubItem(token, reader);
  549. return value;
  550. }
  551. #endif
  552. /// <summary>
  553. /// Makes the end of consuming a nested message in the stream; the stream must be either at the correct EndGroup
  554. /// marker, or all fields of the sub-message must have been consumed (in either case, this means ReadFieldHeader
  555. /// should return zero)
  556. /// </summary>
  557. public static void EndSubItem(SubItemToken token, ProtoReader reader)
  558. {
  559. if (reader == null) throw new ArgumentNullException("reader");
  560. int value = token.value;
  561. switch (reader.wireType)
  562. {
  563. case WireType.EndGroup:
  564. if (value >= 0) throw AddErrorData(new ArgumentException("token"), reader);
  565. if (-value != reader.fieldNumber) throw reader.CreateException("Wrong group was ended"); // wrong group ended!
  566. reader.wireType = WireType.None; // this releases ReadFieldHeader
  567. reader.depth--;
  568. break;
  569. // case WireType.None: // TODO reinstate once reads reset the wire-type
  570. default:
  571. if (value < reader.position) throw reader.CreateException("Sub-message not read entirely");
  572. if (reader.blockEnd != reader.position && reader.blockEnd != int.MaxValue)
  573. {
  574. throw reader.CreateException("Sub-message not read correctly");
  575. }
  576. reader.blockEnd = value;
  577. reader.depth--;
  578. break;
  579. /*default:
  580. throw reader.BorkedIt(); */
  581. }
  582. }
  583. /// <summary>
  584. /// Begins consuming a nested message in the stream; supported wire-types: StartGroup, String
  585. /// </summary>
  586. /// <remarks>The token returned must be help and used when callining EndSubItem</remarks>
  587. public static SubItemToken StartSubItem(ProtoReader reader)
  588. {
  589. if (reader == null) throw new ArgumentNullException("reader");
  590. switch (reader.wireType)
  591. {
  592. case WireType.StartGroup:
  593. reader.wireType = WireType.None; // to prevent glitches from double-calling
  594. reader.depth++;
  595. return new SubItemToken(-reader.fieldNumber);
  596. case WireType.String:
  597. int len = (int)reader.ReadUInt32Variant(false);
  598. if (len < 0) throw AddErrorData(new InvalidOperationException(), reader);
  599. int lastEnd = reader.blockEnd;
  600. reader.blockEnd = reader.position + len;
  601. reader.depth++;
  602. return new SubItemToken(lastEnd);
  603. default:
  604. throw reader.CreateWireTypeException(); // throws
  605. }
  606. }
  607. /// <summary>
  608. /// Reads a field header from the stream, setting the wire-type and retuning the field number. If no
  609. /// more fields are available, then 0 is returned. This methods respects sub-messages.
  610. /// </summary>
  611. public int ReadFieldHeader()
  612. {
  613. // at the end of a group the caller must call EndSubItem to release the
  614. // reader (which moves the status to Error, since ReadFieldHeader must
  615. // then be called)
  616. if (blockEnd <= position || wireType == WireType.EndGroup) { return 0; }
  617. uint tag;
  618. if (TryReadUInt32Variant(out tag) && tag != 0)
  619. {
  620. wireType = (WireType)(tag & 7);
  621. fieldNumber = (int)(tag >> 3);
  622. if(fieldNumber < 1) throw new ProtoException("Invalid field in source data: " + fieldNumber.ToString());
  623. }
  624. else
  625. {
  626. wireType = WireType.None;
  627. fieldNumber = 0;
  628. }
  629. if (wireType == ProtoBuf.WireType.EndGroup)
  630. {
  631. if (depth > 0) return 0; // spoof an end, but note we still set the field-number
  632. throw new ProtoException("Unexpected end-group in source data; this usually means the source data is corrupt");
  633. }
  634. return fieldNumber;
  635. }
  636. /// <summary>
  637. /// Looks ahead to see whether the next field in the stream is what we expect
  638. /// (typically; what we've just finished reading - for example ot read successive list items)
  639. /// </summary>
  640. public bool TryReadFieldHeader(int field)
  641. {
  642. // check for virtual end of stream
  643. if (blockEnd <= position || wireType == WireType.EndGroup) { return false; }
  644. uint tag;
  645. int read = TryReadUInt32VariantWithoutMoving(false, out tag);
  646. WireType tmpWireType; // need to catch this to exclude (early) any "end group" tokens
  647. if (read > 0 && ((int)tag >> 3) == field
  648. && (tmpWireType = (WireType)(tag & 7)) != WireType.EndGroup)
  649. {
  650. wireType = tmpWireType;
  651. fieldNumber = field;
  652. position += read;
  653. ioIndex += read;
  654. available -= read;
  655. return true;
  656. }
  657. return false;
  658. }
  659. /// <summary>
  660. /// Get the TypeModel associated with this reader
  661. /// </summary>
  662. public TypeModel Model { get { return model; } }
  663. /// <summary>
  664. /// Compares the streams current wire-type to the hinted wire-type, updating the reader if necessary; for example,
  665. /// a Variant may be updated to SignedVariant. If the hinted wire-type is unrelated then no change is made.
  666. /// </summary>
  667. public void Hint(WireType wireType)
  668. {
  669. if (this.wireType == wireType) { } // fine; everything as we expect
  670. else if (((int)wireType & 7) == (int)this.wireType)
  671. { // the underling type is a match; we're customising it with an extension
  672. this.wireType = wireType;
  673. }
  674. // note no error here; we're OK about using alternative data
  675. }
  676. /// <summary>
  677. /// Verifies that the stream's current wire-type is as expected, or a specialized sub-type (for example,
  678. /// SignedVariant) - in which case the current wire-type is updated. Otherwise an exception is thrown.
  679. /// </summary>
  680. public void Assert(WireType wireType)
  681. {
  682. if (this.wireType == wireType) { } // fine; everything as we expect
  683. else if (((int)wireType & 7) == (int)this.wireType)
  684. { // the underling type is a match; we're customising it with an extension
  685. this.wireType = wireType;
  686. }
  687. else
  688. { // nope; that is *not* what we were expecting!
  689. throw CreateWireTypeException();
  690. }
  691. }
  692. /// <summary>
  693. /// Discards the data for the current field.
  694. /// </summary>
  695. public void SkipField()
  696. {
  697. switch (wireType)
  698. {
  699. case WireType.Fixed32:
  700. if(available < 4) Ensure(4, true);
  701. available -= 4;
  702. ioIndex += 4;
  703. position += 4;
  704. return;
  705. case WireType.Fixed64:
  706. if (available < 8) Ensure(8, true);
  707. available -= 8;
  708. ioIndex += 8;
  709. position += 8;
  710. return;
  711. case WireType.String:
  712. int len = (int)ReadUInt32Variant(false);
  713. if (len <= available)
  714. { // just jump it!
  715. available -= len;
  716. ioIndex += len;
  717. position += len;
  718. return;
  719. }
  720. // everything remaining in the buffer is garbage
  721. position += len; // assumes success, but if it fails we're screwed anyway
  722. len -= available; // discount anything we've got to-hand
  723. ioIndex = available = 0; // note that we have no data in the buffer
  724. if (isFixedLength)
  725. {
  726. if (len > dataRemaining) throw EoF(this);
  727. // else assume we're going to be OK
  728. dataRemaining -= len;
  729. }
  730. ProtoReader.Seek(source, len, ioBuffer);
  731. return;
  732. case WireType.Variant:
  733. case WireType.SignedVariant:
  734. ReadUInt64Variant(); // and drop it
  735. return;
  736. case WireType.StartGroup:
  737. int originalFieldNumber = this.fieldNumber;
  738. depth++; // need to satisfy the sanity-checks in ReadFieldHeader
  739. while (ReadFieldHeader() > 0) { SkipField(); }
  740. depth--;
  741. if (wireType == WireType.EndGroup && fieldNumber == originalFieldNumber)
  742. { // we expect to exit in a similar state to how we entered
  743. wireType = ProtoBuf.WireType.None;
  744. return;
  745. }
  746. throw CreateWireTypeException();
  747. case WireType.None: // treat as explicit errorr
  748. case WireType.EndGroup: // treat as explicit error
  749. default: // treat as implicit error
  750. throw CreateWireTypeException();
  751. }
  752. }
  753. /// <summary>
  754. /// Reads an unsigned 64-bit integer from the stream; supported wire-types: Variant, Fixed32, Fixed64
  755. /// </summary>
  756. public ulong ReadUInt64()
  757. {
  758. switch (wireType)
  759. {
  760. case WireType.Variant:
  761. return ReadUInt64Variant();
  762. case WireType.Fixed32:
  763. return ReadUInt32();
  764. case WireType.Fixed64:
  765. if (available < 8) Ensure(8, true);
  766. position += 8;
  767. available -= 8;
  768. return ((ulong)ioBuffer[ioIndex++])
  769. | (((ulong)ioBuffer[ioIndex++]) << 8)
  770. | (((ulong)ioBuffer[ioIndex++]) << 16)
  771. | (((ulong)ioBuffer[ioIndex++]) << 24)
  772. | (((ulong)ioBuffer[ioIndex++]) << 32)
  773. | (((ulong)ioBuffer[ioIndex++]) << 40)
  774. | (((ulong)ioBuffer[ioIndex++]) << 48)
  775. | (((ulong)ioBuffer[ioIndex++]) << 56);
  776. default:
  777. throw CreateWireTypeException();
  778. }
  779. }
  780. /// <summary>
  781. /// Reads a single-precision number from the stream; supported wire-types: Fixed32, Fixed64
  782. /// </summary>
  783. public
  784. #if !FEAT_SAFE
  785. unsafe
  786. #endif
  787. float ReadSingle()
  788. {
  789. switch (wireType)
  790. {
  791. case WireType.Fixed32:
  792. {
  793. int value = ReadInt32();
  794. #if FEAT_SAFE
  795. return BitConverter.ToSingle(BitConverter.GetBytes(value), 0);
  796. #else
  797. return *(float*)&value;
  798. #endif
  799. }
  800. case WireType.Fixed64:
  801. {
  802. double value = ReadDouble();
  803. float f = (float)value;
  804. if (Helpers.IsInfinity(f)
  805. && !Helpers.IsInfinity(value))
  806. {
  807. throw AddErrorData(new OverflowException(), this);
  808. }
  809. return f;
  810. }
  811. default:
  812. throw CreateWireTypeException();
  813. }
  814. }
  815. /// <summary>
  816. /// Reads a boolean value from the stream; supported wire-types: Variant, Fixed32, Fixed64
  817. /// </summary>
  818. /// <returns></returns>
  819. public bool ReadBoolean()
  820. {
  821. switch (ReadUInt32())
  822. {
  823. case 0: return false;
  824. case 1: return true;
  825. default: throw CreateException("Unexpected boolean value");
  826. }
  827. }
  828. private static readonly byte[] EmptyBlob = new byte[0];
  829. /// <summary>
  830. /// Reads a byte-sequence from the stream, appending them to an existing byte-sequence (which can be null); supported wire-types: String
  831. /// </summary>
  832. public static byte[] AppendBytes(byte[] value, ProtoReader reader)
  833. {
  834. if (reader == null) throw new ArgumentNullException("reader");
  835. switch (reader.wireType)
  836. {
  837. case WireType.String:
  838. int len = (int)reader.ReadUInt32Variant(false);
  839. reader.wireType = WireType.None;
  840. if (len == 0) return value == null ? EmptyBlob : value;
  841. int offset;
  842. if (value == null || value.Length == 0)
  843. {
  844. offset = 0;
  845. value = new byte[len];
  846. }
  847. else
  848. {
  849. offset = value.Length;
  850. byte[] tmp = new byte[value.Length + len];
  851. Helpers.BlockCopy(value, 0, tmp, 0, value.Length);
  852. value = tmp;
  853. }
  854. // value is now sized with the final length, and (if necessary)
  855. // contains the old data up to "offset"
  856. reader.position += len; // assume success
  857. while (len > reader.available)
  858. {
  859. if (reader.available > 0)
  860. {
  861. // copy what we *do* have
  862. Helpers.BlockCopy(reader.ioBuffer, reader.ioIndex, value, offset, reader.available);
  863. len -= reader.available;
  864. offset += reader.available;
  865. reader.ioIndex = reader.available = 0; // we've drained the buffer
  866. }
  867. // now refill the buffer (without overflowing it)
  868. int count = len > reader.ioBuffer.Length ? reader.ioBuffer.Length : len;
  869. if (count > 0) reader.Ensure(count, true);
  870. }
  871. // at this point, we know that len <= available
  872. if (len > 0)
  873. { // still need data, but we have enough buffered
  874. Helpers.BlockCopy(reader.ioBuffer, reader.ioIndex, value, offset, len);
  875. reader.ioIndex += len;
  876. reader.available -= len;
  877. }
  878. return value;
  879. case WireType.Variant:
  880. return new byte[0];
  881. default:
  882. throw reader.CreateWireTypeException();
  883. }
  884. }
  885. //static byte[] ReadBytes(Stream stream, int length)
  886. //{
  887. // if (stream == null) throw new ArgumentNullException("stream");
  888. // if (length < 0) throw new ArgumentOutOfRangeException("length");
  889. // byte[] buffer = new byte[length];
  890. // int offset = 0, read;
  891. // while (length > 0 && (read = stream.Read(buffer, offset, length)) > 0)
  892. // {
  893. // length -= read;
  894. // }
  895. // if (length > 0) throw EoF(null);
  896. // return buffer;
  897. //}
  898. private static int ReadByteOrThrow(Stream source)
  899. {
  900. int val = source.ReadByte();
  901. if (val < 0) throw EoF(null);
  902. return val;
  903. }
  904. /// <summary>
  905. /// Reads the length-prefix of a message from a stream without buffering additional data, allowing a fixed-length
  906. /// reader to be created.
  907. /// </summary>
  908. public static int ReadLengthPrefix(Stream source, bool expectHeader, PrefixStyle style, out int fieldNumber)
  909. {
  910. int bytesRead;
  911. return ReadLengthPrefix(source, expectHeader, style, out fieldNumber, out bytesRead);
  912. }
  913. /// <summary>
  914. /// Reads a little-endian encoded integer. An exception is thrown if the data is not all available.
  915. /// </summary>
  916. public static int DirectReadLittleEndianInt32(Stream source)
  917. {
  918. return ReadByteOrThrow(source)
  919. | (ReadByteOrThrow(source) << 8)
  920. | (ReadByteOrThrow(source) << 16)
  921. | (ReadByteOrThrow(source) << 24);
  922. }
  923. /// <summary>
  924. /// Reads a big-endian encoded integer. An exception is thrown if the data is not all available.
  925. /// </summary>
  926. public static int DirectReadBigEndianInt32(Stream source)
  927. {
  928. return (ReadByteOrThrow(source) << 24)
  929. | (ReadByteOrThrow(source) << 16)
  930. | (ReadByteOrThrow(source) << 8)
  931. | ReadByteOrThrow(source);
  932. }
  933. /// <summary>
  934. /// Reads a varint encoded integer. An exception is thrown if the data is not all available.
  935. /// </summary>
  936. public static int DirectReadVarintInt32(Stream source)
  937. {
  938. uint val;
  939. int bytes = TryReadUInt32Variant(source, out val);
  940. if (bytes <= 0) throw EoF(null);
  941. return (int) val;
  942. }
  943. /// <summary>
  944. /// Reads a string (of a given lenth, in bytes) directly from the source into a pre-existing buffer. An exception is thrown if the data is not all available.
  945. /// </summary>
  946. public static void DirectReadBytes(Stream source, byte[] buffer, int offset, int count)
  947. {
  948. int read;
  949. if (source == null) throw new ArgumentNullException("source");
  950. while(count > 0 && (read = source.Read(buffer, offset, count)) > 0)
  951. {
  952. count -= read;
  953. offset += read;
  954. }
  955. if (count > 0) throw EoF(null);
  956. }
  957. /// <summary>
  958. /// Reads a given number of bytes directly from the source. An exception is thrown if the data is not all available.
  959. /// </summary>
  960. public static byte[] DirectReadBytes(Stream source, int count)
  961. {
  962. byte[] buffer = new byte[count];
  963. DirectReadBytes(source, buffer, 0, count);
  964. return buffer;
  965. }
  966. /// <summary>
  967. /// Reads a string (of a given lenth, in bytes) directly from the source. An exception is thrown if the data is not all available.
  968. /// </summary>
  969. public static string DirectReadString(Stream source, int length)
  970. {
  971. byte[] buffer = new byte[length];
  972. DirectReadBytes(source, buffer, 0, length);
  973. return Encoding.UTF8.GetString(buffer, 0, length);
  974. }
  975. /// <summary>
  976. /// Reads the length-prefix of a message from a stream without buffering additional data, allowing a fixed-length
  977. /// reader to be created.
  978. /// </summary>
  979. public static int ReadLengthPrefix(Stream source, bool expectHeader, PrefixStyle style, out int fieldNumber, out int bytesRead)
  980. {
  981. fieldNumber = 0;
  982. switch (style)
  983. {
  984. case PrefixStyle.None:
  985. bytesRead = 0;
  986. return int.MaxValue;
  987. case PrefixStyle.Base128:
  988. uint val;
  989. int tmpBytesRead;
  990. bytesRead = 0;
  991. if (expectHeader)
  992. {
  993. tmpBytesRead = ProtoReader.TryReadUInt32Variant(source, out val);
  994. bytesRead += tmpBytesRead;
  995. if (tmpBytesRead > 0)
  996. {
  997. if ((val & 7) != (uint)WireType.String)
  998. { // got a header, but it isn't a string
  999. throw new InvalidOperationException();
  1000. }
  1001. fieldNumber = (int)(val >> 3);
  1002. tmpBytesRead = ProtoReader.TryReadUInt32Variant(source, out val);
  1003. bytesRead += tmpBytesRead;
  1004. if (bytesRead == 0)
  1005. { // got a header, but no length
  1006. throw EoF(null);
  1007. }
  1008. return (int)val;
  1009. }
  1010. else
  1011. { // no header
  1012. bytesRead = 0;
  1013. return -1;
  1014. }
  1015. }
  1016. // check for a length
  1017. tmpBytesRead = ProtoReader.TryReadUInt32Variant(source, out val);
  1018. bytesRead += tmpBytesRead;
  1019. return bytesRead < 0 ? -1 : (int)val;
  1020. case PrefixStyle.Fixed32:
  1021. {
  1022. int b = source.ReadByte();
  1023. if (b < 0)
  1024. {
  1025. bytesRead = 0;
  1026. return -1;
  1027. }
  1028. bytesRead = 4;
  1029. return b
  1030. | (ReadByteOrThrow(source) << 8)
  1031. | (ReadByteOrThrow(source) << 16)
  1032. | (ReadByteOrThrow(source) << 24);
  1033. }
  1034. case PrefixStyle.Fixed32BigEndian:
  1035. {
  1036. int b = source.ReadByte();
  1037. if (b < 0)
  1038. {
  1039. bytesRead = 0;
  1040. return -1;
  1041. }
  1042. bytesRead = 4;
  1043. return (b << 24)
  1044. | (ReadByteOrThrow(source) << 16)
  1045. | (ReadByteOrThrow(source) << 8)
  1046. | ReadByteOrThrow(source);
  1047. }
  1048. default:
  1049. throw new ArgumentOutOfRangeException("style");
  1050. }
  1051. }
  1052. /// <returns>The number of bytes consumed; 0 if no data available</returns>
  1053. private static int TryReadUInt32Variant(Stream source, out uint value)
  1054. {
  1055. value = 0;
  1056. int b = source.ReadByte();
  1057. if (b < 0) { return 0; }
  1058. value = (uint)b;
  1059. if ((value & 0x80) == 0) { return 1; }
  1060. value &= 0x7F;
  1061. b = source.ReadByte();
  1062. if (b < 0) throw EoF(null);
  1063. value |= ((uint)b & 0x7F) << 7;
  1064. if ((b & 0x80) == 0) return 2;
  1065. b = source.ReadByte();
  1066. if (b < 0) throw EoF(null);
  1067. value |= ((uint)b & 0x7F) << 14;
  1068. if ((b & 0x80) == 0) return 3;
  1069. b = source.ReadByte();
  1070. if (b < 0) throw EoF(null);
  1071. value |= ((uint)b & 0x7F) << 21;
  1072. if ((b & 0x80) == 0) return 4;
  1073. b = source.ReadByte();
  1074. if (b < 0) throw EoF(null);
  1075. value |= (uint)b << 28; // can only use 4 bits from this chunk
  1076. if ((b & 0xF0) == 0) return 5;
  1077. throw new OverflowException();
  1078. }
  1079. internal static void Seek(Stream source, int count, byte[] buffer)
  1080. {
  1081. if (source.CanSeek)
  1082. {
  1083. source.Seek(count, SeekOrigin.Current);
  1084. count = 0;
  1085. }
  1086. else if (buffer != null)
  1087. {
  1088. int bytesRead;
  1089. while (count > buffer.Length && (bytesRead = source.Read(buffer, 0, buffer.Length)) > 0)
  1090. {
  1091. count -= bytesRead;
  1092. }
  1093. while (count > 0 && (bytesRead = source.Read(buffer, 0, count)) > 0)
  1094. {
  1095. count -= bytesRead;
  1096. }
  1097. }
  1098. else // borrow a buffer
  1099. {
  1100. buffer = BufferPool.GetBuffer();
  1101. try
  1102. {
  1103. int bytesRead;
  1104. while (count > buffer.Length && (bytesRead = source.Read(buffer, 0, buffer.Length)) > 0)
  1105. {
  1106. count -= bytesRead;
  1107. }
  1108. while (count > 0 && (bytesRead = source.Read(buffer, 0, count)) > 0)
  1109. {
  1110. count -= bytesRead;
  1111. }
  1112. }
  1113. finally
  1114. {
  1115. BufferPool.ReleaseBufferToPool(ref buffer);
  1116. }
  1117. }
  1118. if (count > 0) throw EoF(null);
  1119. }
  1120. internal static Exception AddErrorData(Exception exception, ProtoReader source)
  1121. {
  1122. #if !CF && !FX11 && !PORTABLE
  1123. if (exception != null && source != null && !exception.Data.Contains("protoSource"))
  1124. {
  1125. exception.Data.Add("protoSource", string.Format("tag={0}; wire-type={1}; offset={2}; depth={3}",
  1126. source.fieldNumber, source.wireType, source.position, source.depth));
  1127. }
  1128. #endif
  1129. return exception;
  1130. }
  1131. private static Exception EoF(ProtoReader source)
  1132. {
  1133. return AddErrorData(new EndOfStreamException(), source);
  1134. }
  1135. /// <summary>
  1136. /// Copies the current field into the instance as extension data
  1137. /// </summary>
  1138. public void AppendExtensionData(IExtensible instance)
  1139. {
  1140. if (instance == null) throw new ArgumentNullException("instance");
  1141. IExtension extn = instance.GetExtensionObject(true);
  1142. bool commit = false;
  1143. // unusually we *don't* want "using" here; the "finally" does that, with
  1144. // the extension object being responsible for disposal etc
  1145. Stream dest = extn.BeginAppend();
  1146. try
  1147. {
  1148. //TODO: replace this with stream-based, buffered raw copying
  1149. using (ProtoWriter writer = new ProtoWriter(dest, model, null))
  1150. {
  1151. AppendExtensionField(writer);
  1152. writer.Close();
  1153. }
  1154. commit = true;
  1155. }
  1156. finally { extn.EndAppend(dest, commit); }
  1157. }
  1158. private void AppendExtensionField(ProtoWriter writer)
  1159. {
  1160. //TODO: replace this with stream-based, buffered raw copying
  1161. ProtoWriter.WriteFieldHeader(fieldNumber, wireType, writer);
  1162. switch (wireType)
  1163. {
  1164. case WireType.Fixed32:
  1165. ProtoWriter.WriteInt32(ReadInt32(), writer);
  1166. return;
  1167. case WireType.Variant:
  1168. case WireType.SignedVariant:
  1169. case WireType.Fixed64:
  1170. ProtoWriter.WriteInt64(ReadInt64(), writer);
  1171. return;
  1172. case WireType.String:
  1173. ProtoWriter.WriteBytes(AppendBytes(null, this), writer);
  1174. return;
  1175. case WireType.StartGroup:
  1176. SubItemToken readerToken = StartSubItem(this),
  1177. writerToken = ProtoWriter.StartSubItem(null, writer);
  1178. while (ReadFieldHeader() > 0) { AppendExtensionField(writer); }
  1179. EndSubItem(readerToken, this);
  1180. ProtoWriter.EndSubItem(writerToken, writer);
  1181. return;
  1182. case WireType.None: // treat as explicit errorr
  1183. case WireType.EndGroup: // treat as explicit error
  1184. default: // treat as implicit error
  1185. throw CreateWireTypeException();
  1186. }
  1187. }
  1188. /// <summary>
  1189. /// Indicates whether the reader still has data remaining in the current sub-item,
  1190. /// additionally setting the wire-type for the next field if there is more data.
  1191. /// This is used when decoding packed data.
  1192. /// </summary>
  1193. public static bool HasSubValue(ProtoBuf.WireType wireType, ProtoReader source)
  1194. {
  1195. if (source == null) throw new ArgumentNullException("source");
  1196. // check for virtual end of stream
  1197. if (source.blockEnd <= source.position || wireType == WireType.EndGroup) { return false; }
  1198. source.wireType = wireType;
  1199. return true;
  1200. }
  1201. internal int GetTypeKey(ref Type type)
  1202. {
  1203. return model.GetKey(ref type);
  1204. }
  1205. internal NetObjectCache NetCache
  1206. {
  1207. get { return netCache; }
  1208. }
  1209. internal System.Type DeserializeType(string value)
  1210. {
  1211. return TypeModel.DeserializeType(model, value);
  1212. }
  1213. internal void SetRootObject(object value)
  1214. {
  1215. netCache.SetKeyedObject(NetObjectCache.Root, value);
  1216. trapCount--;
  1217. }
  1218. /// <summary>
  1219. /// Utility method, not intended for public use; this helps maintain the root object is complex scenarios
  1220. /// </summary>
  1221. public static void NoteObject(object value, ProtoReader reader)
  1222. {
  1223. if (reader == null) throw new ArgumentNullException("reader");
  1224. if(reader.trapCount != 0)
  1225. {
  1226. reader.netCache.RegisterTrappedObject(value);
  1227. reader.trapCount--;
  1228. }
  1229. }
  1230. /// <summary>
  1231. /// Reads a Type from the stream, using the model's DynamicTypeFormatting if appropriate; supported wire-types: String
  1232. /// </summary>
  1233. public System.Type ReadType()
  1234. {
  1235. return TypeModel.DeserializeType(model, ReadString());
  1236. }
  1237. internal void TrapNextObject(int newObjectKey)
  1238. {
  1239. trapCount++;
  1240. netCache.SetKeyedObject(newObjectKey, null); // use null as a temp
  1241. }
  1242. internal void CheckFullyConsumed()
  1243. {
  1244. if (isFixedLength)
  1245. {
  1246. if (dataRemaining != 0) throw new ProtoException("Incorrect number of bytes consumed");
  1247. }
  1248. else
  1249. {
  1250. if (available != 0) throw new ProtoException("Unconsumed data left in the buffer; this suggests corrupt input");
  1251. }
  1252. }
  1253. /// <summary>
  1254. /// Merge two objects using the details from the current reader; this is used to change the type
  1255. /// of objects when an inheritance relationship is discovered later than usual during deserilazation.
  1256. /// </summary>
  1257. public static object Merge(ProtoReader parent, object from, object to)
  1258. {
  1259. if (parent == null) throw new ArgumentNullException("parent");
  1260. TypeModel model = parent.Model;
  1261. SerializationContext ctx = parent.Context;
  1262. if(model == null) throw new InvalidOperationException("Types cannot be merged unless a type-model has been specified");
  1263. using (MemoryStream ms = new MemoryStream())
  1264. {
  1265. model.Serialize(ms, from, ctx);
  1266. ms.Position = 0;
  1267. return model.Deserialize(ms, to, null);
  1268. }
  1269. }
  1270. #region RECYCLER
  1271. internal static ProtoReader Create(Stream source, TypeModel model, SerializationContext context, int len)
  1272. {
  1273. ProtoReader reader = GetRecycled();
  1274. if (reader == null)
  1275. {
  1276. return new ProtoReader(source, model, context, len);
  1277. }
  1278. Init(reader, source, model, context, len);
  1279. return reader;
  1280. }
  1281. #if !PLAT_NO_THREADSTATIC
  1282. [ThreadStatic]
  1283. private static ProtoReader lastReader;
  1284. private static ProtoReader GetRecycled()
  1285. {
  1286. ProtoReader tmp = lastReader;
  1287. lastReader = null;
  1288. return tmp;
  1289. }
  1290. internal static void Recycle(ProtoReader reader)
  1291. {
  1292. if(reader != null)
  1293. {
  1294. reader.Dispose();
  1295. lastReader = reader;
  1296. }
  1297. }
  1298. #elif !PLAT_NO_INTERLOCKED
  1299. private static object lastReader;
  1300. private static ProtoReader GetRecycled()
  1301. {
  1302. return (ProtoReader)System.Threading.Interlocked.Exchange(ref lastReader, null);
  1303. }
  1304. internal static void Recycle(ProtoReader reader)
  1305. {
  1306. if(reader != null)
  1307. {
  1308. reader.Dispose();
  1309. System.Threading.Interlocked.Exchange(ref lastReader, reader);
  1310. }
  1311. }
  1312. #else
  1313. private static readonly object recycleLock = new object();
  1314. private static ProtoReader lastReader;
  1315. private static ProtoReader GetRecycled()
  1316. {
  1317. lock(recycleLock)
  1318. {
  1319. ProtoReader tmp = lastReader;
  1320. lastReader = null;
  1321. return tmp;
  1322. }
  1323. }
  1324. internal static void Recycle(ProtoReader reader)
  1325. {
  1326. if(reader != null)
  1327. {
  1328. reader.Dispose();
  1329. lock(recycleLock)
  1330. {
  1331. lastReader = reader;
  1332. }
  1333. }
  1334. }
  1335. #endif
  1336. #endregion
  1337. }
  1338. }