ProtoReader.cs 57 KB

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