ProtoReader.cs 55 KB

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