ProtoReader.cs 57 KB

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