ProtoReader.cs 55 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414
  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. #if !FEAT_SAFE
  493. unsafe
  494. #endif
  495. double ReadDouble()
  496. {
  497. switch (wireType)
  498. {
  499. case WireType.Fixed32:
  500. return ReadSingle();
  501. case WireType.Fixed64:
  502. long value = ReadInt64();
  503. #if FEAT_SAFE
  504. return BitConverter.ToDouble(BitConverter.GetBytes(value), 0);
  505. #else
  506. return *(double*)&value;
  507. #endif
  508. default:
  509. throw CreateWireTypeException();
  510. }
  511. }
  512. /// <summary>
  513. /// Reads (merges) a sub-message from the stream, internally calling StartSubItem and EndSubItem, and (in between)
  514. /// parsing the message in accordance with the model associated with the reader
  515. /// </summary>
  516. public static object ReadObject(object value, int key, ProtoReader reader)
  517. {
  518. #if FEAT_IKVM
  519. throw new NotSupportedException();
  520. #else
  521. return ReadTypedObject(value, key, reader, null);
  522. #endif
  523. }
  524. #if !FEAT_IKVM
  525. internal static object ReadTypedObject(object value, int key, ProtoReader reader, Type type)
  526. {
  527. if (reader.model == null)
  528. {
  529. throw AddErrorData(new InvalidOperationException("Cannot deserialize sub-objects unless a model is provided"), reader);
  530. }
  531. SubItemToken token = ProtoReader.StartSubItem(reader);
  532. if (key >= 0)
  533. {
  534. value = reader.model.Deserialize(key, value, reader);
  535. }
  536. else if (type != null && reader.model.TryDeserializeAuxiliaryType(reader, DataFormat.Default, Serializer.ListItemTag, type, ref value, true, false, true, false))
  537. {
  538. // ok
  539. }
  540. else
  541. {
  542. TypeModel.ThrowUnexpectedType(type);
  543. }
  544. ProtoReader.EndSubItem(token, reader);
  545. return value;
  546. }
  547. #endif
  548. /// <summary>
  549. /// Makes the end of consuming a nested message in the stream; the stream must be either at the correct EndGroup
  550. /// marker, or all fields of the sub-message must have been consumed (in either case, this means ReadFieldHeader
  551. /// should return zero)
  552. /// </summary>
  553. public static void EndSubItem(SubItemToken token, ProtoReader reader)
  554. {
  555. if (reader == null) throw new ArgumentNullException("reader");
  556. int value = token.value;
  557. switch (reader.wireType)
  558. {
  559. case WireType.EndGroup:
  560. if (value >= 0) throw AddErrorData(new ArgumentException("token"), reader);
  561. if (-value != reader.fieldNumber) throw reader.CreateException("Wrong group was ended"); // wrong group ended!
  562. reader.wireType = WireType.None; // this releases ReadFieldHeader
  563. reader.depth--;
  564. break;
  565. // case WireType.None: // TODO reinstate once reads reset the wire-type
  566. default:
  567. if (value < reader.position) throw reader.CreateException("Sub-message not read entirely");
  568. if (reader.blockEnd != reader.position && reader.blockEnd != int.MaxValue)
  569. {
  570. throw reader.CreateException("Sub-message not read correctly");
  571. }
  572. reader.blockEnd = value;
  573. reader.depth--;
  574. break;
  575. /*default:
  576. throw reader.BorkedIt(); */
  577. }
  578. }
  579. /// <summary>
  580. /// Begins consuming a nested message in the stream; supported wire-types: StartGroup, String
  581. /// </summary>
  582. /// <remarks>The token returned must be help and used when callining EndSubItem</remarks>
  583. public static SubItemToken StartSubItem(ProtoReader reader)
  584. {
  585. if (reader == null) throw new ArgumentNullException("reader");
  586. switch (reader.wireType)
  587. {
  588. case WireType.StartGroup:
  589. reader.wireType = WireType.None; // to prevent glitches from double-calling
  590. reader.depth++;
  591. return new SubItemToken(-reader.fieldNumber);
  592. case WireType.String:
  593. int len = (int)reader.ReadUInt32Variant(false);
  594. if (len < 0) throw AddErrorData(new InvalidOperationException(), reader);
  595. int lastEnd = reader.blockEnd;
  596. reader.blockEnd = reader.position + len;
  597. reader.depth++;
  598. return new SubItemToken(lastEnd);
  599. default:
  600. throw reader.CreateWireTypeException(); // throws
  601. }
  602. }
  603. /// <summary>
  604. /// Reads a field header from the stream, setting the wire-type and retuning the field number. If no
  605. /// more fields are available, then 0 is returned. This methods respects sub-messages.
  606. /// </summary>
  607. public int ReadFieldHeader()
  608. {
  609. // at the end of a group the caller must call EndSubItem to release the
  610. // reader (which moves the status to Error, since ReadFieldHeader must
  611. // then be called)
  612. if (blockEnd <= position || wireType == WireType.EndGroup) { return 0; }
  613. uint tag;
  614. if (TryReadUInt32Variant(out tag))
  615. {
  616. wireType = (WireType)(tag & 7);
  617. fieldNumber = (int)(tag >> 3);
  618. if(fieldNumber < 1) throw new ProtoException("Invalid field in source data: " + fieldNumber.ToString());
  619. }
  620. else
  621. {
  622. wireType = WireType.None;
  623. fieldNumber = 0;
  624. }
  625. if (wireType == ProtoBuf.WireType.EndGroup)
  626. {
  627. if (depth > 0) return 0; // spoof an end, but note we still set the field-number
  628. throw new ProtoException("Unexpected end-group in source data; this usually means the source data is corrupt");
  629. }
  630. return fieldNumber;
  631. }
  632. /// <summary>
  633. /// Looks ahead to see whether the next field in the stream is what we expect
  634. /// (typically; what we've just finished reading - for example ot read successive list items)
  635. /// </summary>
  636. public bool TryReadFieldHeader(int field)
  637. {
  638. // check for virtual end of stream
  639. if (blockEnd <= position || wireType == WireType.EndGroup) { return false; }
  640. uint tag;
  641. int read = TryReadUInt32VariantWithoutMoving(false, out tag);
  642. WireType tmpWireType; // need to catch this to exclude (early) any "end group" tokens
  643. if (read > 0 && ((int)tag >> 3) == field
  644. && (tmpWireType = (WireType)(tag & 7)) != WireType.EndGroup)
  645. {
  646. wireType = tmpWireType;
  647. fieldNumber = field;
  648. position += read;
  649. ioIndex += read;
  650. available -= read;
  651. return true;
  652. }
  653. return false;
  654. }
  655. /// <summary>
  656. /// Get the TypeModel associated with this reader
  657. /// </summary>
  658. public TypeModel Model { get { return model; } }
  659. /// <summary>
  660. /// Compares the streams current wire-type to the hinted wire-type, updating the reader if necessary; for example,
  661. /// a Variant may be updated to SignedVariant. If the hinted wire-type is unrelated then no change is made.
  662. /// </summary>
  663. public void Hint(WireType wireType)
  664. {
  665. if (this.wireType == wireType) { } // fine; everything as we expect
  666. else if (((int)wireType & 7) == (int)this.wireType)
  667. { // the underling type is a match; we're customising it with an extension
  668. this.wireType = wireType;
  669. }
  670. // note no error here; we're OK about using alternative data
  671. }
  672. /// <summary>
  673. /// Verifies that the stream's current wire-type is as expected, or a specialized sub-type (for example,
  674. /// SignedVariant) - in which case the current wire-type is updated. Otherwise an exception is thrown.
  675. /// </summary>
  676. public void Assert(WireType wireType)
  677. {
  678. if (this.wireType == wireType) { } // fine; everything as we expect
  679. else if (((int)wireType & 7) == (int)this.wireType)
  680. { // the underling type is a match; we're customising it with an extension
  681. this.wireType = wireType;
  682. }
  683. else
  684. { // nope; that is *not* what we were expecting!
  685. throw CreateWireTypeException();
  686. }
  687. }
  688. /// <summary>
  689. /// Discards the data for the current field.
  690. /// </summary>
  691. public void SkipField()
  692. {
  693. switch (wireType)
  694. {
  695. case WireType.Fixed32:
  696. if(available < 4) Ensure(4, true);
  697. available -= 4;
  698. ioIndex += 4;
  699. position += 4;
  700. return;
  701. case WireType.Fixed64:
  702. if (available < 8) Ensure(8, true);
  703. available -= 8;
  704. ioIndex += 8;
  705. position += 8;
  706. return;
  707. case WireType.String:
  708. int len = (int)ReadUInt32Variant(false);
  709. if (len <= available)
  710. { // just jump it!
  711. available -= len;
  712. ioIndex += len;
  713. position += len;
  714. return;
  715. }
  716. // everything remaining in the buffer is garbage
  717. position += len; // assumes success, but if it fails we're screwed anyway
  718. len -= available; // discount anything we've got to-hand
  719. ioIndex = available = 0; // note that we have no data in the buffer
  720. if (isFixedLength)
  721. {
  722. if (len > dataRemaining) throw EoF(this);
  723. // else assume we're going to be OK
  724. dataRemaining -= len;
  725. }
  726. ProtoReader.Seek(source, len, ioBuffer);
  727. return;
  728. case WireType.Variant:
  729. case WireType.SignedVariant:
  730. ReadUInt64Variant(); // and drop it
  731. return;
  732. case WireType.StartGroup:
  733. int originalFieldNumber = this.fieldNumber;
  734. depth++; // need to satisfy the sanity-checks in ReadFieldHeader
  735. while (ReadFieldHeader() > 0) { SkipField(); }
  736. depth--;
  737. if (wireType == WireType.EndGroup && fieldNumber == originalFieldNumber)
  738. { // we expect to exit in a similar state to how we entered
  739. wireType = ProtoBuf.WireType.None;
  740. return;
  741. }
  742. throw CreateWireTypeException();
  743. case WireType.None: // treat as explicit errorr
  744. case WireType.EndGroup: // treat as explicit error
  745. default: // treat as implicit error
  746. throw CreateWireTypeException();
  747. }
  748. }
  749. /// <summary>
  750. /// Reads an unsigned 64-bit integer from the stream; supported wire-types: Variant, Fixed32, Fixed64
  751. /// </summary>
  752. public ulong ReadUInt64()
  753. {
  754. switch (wireType)
  755. {
  756. case WireType.Variant:
  757. return ReadUInt64Variant();
  758. case WireType.Fixed32:
  759. return ReadUInt32();
  760. case WireType.Fixed64:
  761. if (available < 8) Ensure(8, true);
  762. position += 8;
  763. available -= 8;
  764. return ((ulong)ioBuffer[ioIndex++])
  765. | (((ulong)ioBuffer[ioIndex++]) << 8)
  766. | (((ulong)ioBuffer[ioIndex++]) << 16)
  767. | (((ulong)ioBuffer[ioIndex++]) << 24)
  768. | (((ulong)ioBuffer[ioIndex++]) << 32)
  769. | (((ulong)ioBuffer[ioIndex++]) << 40)
  770. | (((ulong)ioBuffer[ioIndex++]) << 48)
  771. | (((ulong)ioBuffer[ioIndex++]) << 56);
  772. default:
  773. throw CreateWireTypeException();
  774. }
  775. }
  776. /// <summary>
  777. /// Reads a single-precision number from the stream; supported wire-types: Fixed32, Fixed64
  778. /// </summary>
  779. public
  780. #if !FEAT_SAFE
  781. unsafe
  782. #endif
  783. float ReadSingle()
  784. {
  785. switch (wireType)
  786. {
  787. case WireType.Fixed32:
  788. {
  789. int value = ReadInt32();
  790. #if FEAT_SAFE
  791. return BitConverter.ToSingle(BitConverter.GetBytes(value), 0);
  792. #else
  793. return *(float*)&value;
  794. #endif
  795. }
  796. case WireType.Fixed64:
  797. {
  798. double value = ReadDouble();
  799. float f = (float)value;
  800. if (Helpers.IsInfinity(f)
  801. && !Helpers.IsInfinity(value))
  802. {
  803. throw AddErrorData(new OverflowException(), this);
  804. }
  805. return f;
  806. }
  807. default:
  808. throw CreateWireTypeException();
  809. }
  810. }
  811. /// <summary>
  812. /// Reads a boolean value from the stream; supported wire-types: Variant, Fixed32, Fixed64
  813. /// </summary>
  814. /// <returns></returns>
  815. public bool ReadBoolean()
  816. {
  817. switch (ReadUInt32())
  818. {
  819. case 0: return false;
  820. case 1: return true;
  821. default: throw CreateException("Unexpected boolean value");
  822. }
  823. }
  824. private static readonly byte[] EmptyBlob = new byte[0];
  825. /// <summary>
  826. /// Reads a byte-sequence from the stream, appending them to an existing byte-sequence (which can be null); supported wire-types: String
  827. /// </summary>
  828. public static byte[] AppendBytes(byte[] value, ProtoReader reader)
  829. {
  830. if (reader == null) throw new ArgumentNullException("reader");
  831. switch (reader.wireType)
  832. {
  833. case WireType.String:
  834. int len = (int)reader.ReadUInt32Variant(false);
  835. reader.wireType = WireType.None;
  836. if (len == 0) return value == null ? EmptyBlob : value;
  837. int offset;
  838. if (value == null || value.Length == 0)
  839. {
  840. offset = 0;
  841. value = new byte[len];
  842. }
  843. else
  844. {
  845. offset = value.Length;
  846. byte[] tmp = new byte[value.Length + len];
  847. Helpers.BlockCopy(value, 0, tmp, 0, value.Length);
  848. value = tmp;
  849. }
  850. // value is now sized with the final length, and (if necessary)
  851. // contains the old data up to "offset"
  852. reader.position += len; // assume success
  853. while (len > reader.available)
  854. {
  855. if (reader.available > 0)
  856. {
  857. // copy what we *do* have
  858. Helpers.BlockCopy(reader.ioBuffer, reader.ioIndex, value, offset, reader.available);
  859. len -= reader.available;
  860. offset += reader.available;
  861. reader.ioIndex = reader.available = 0; // we've drained the buffer
  862. }
  863. // now refill the buffer (without overflowing it)
  864. int count = len > reader.ioBuffer.Length ? reader.ioBuffer.Length : len;
  865. if (count > 0) reader.Ensure(count, true);
  866. }
  867. // at this point, we know that len <= available
  868. if (len > 0)
  869. { // still need data, but we have enough buffered
  870. Helpers.BlockCopy(reader.ioBuffer, reader.ioIndex, value, offset, len);
  871. reader.ioIndex += len;
  872. reader.available -= len;
  873. }
  874. return value;
  875. default:
  876. throw reader.CreateWireTypeException();
  877. }
  878. }
  879. //static byte[] ReadBytes(Stream stream, int length)
  880. //{
  881. // if (stream == null) throw new ArgumentNullException("stream");
  882. // if (length < 0) throw new ArgumentOutOfRangeException("length");
  883. // byte[] buffer = new byte[length];
  884. // int offset = 0, read;
  885. // while (length > 0 && (read = stream.Read(buffer, offset, length)) > 0)
  886. // {
  887. // length -= read;
  888. // }
  889. // if (length > 0) throw EoF(null);
  890. // return buffer;
  891. //}
  892. private static int ReadByteOrThrow(Stream source)
  893. {
  894. int val = source.ReadByte();
  895. if (val < 0) throw EoF(null);
  896. return val;
  897. }
  898. /// <summary>
  899. /// Reads the length-prefix of a message from a stream without buffering additional data, allowing a fixed-length
  900. /// reader to be created.
  901. /// </summary>
  902. public static int ReadLengthPrefix(Stream source, bool expectHeader, PrefixStyle style, out int fieldNumber)
  903. {
  904. int bytesRead;
  905. return ReadLengthPrefix(source, expectHeader, style, out fieldNumber, out bytesRead);
  906. }
  907. /// <summary>
  908. /// Reads a little-endian encoded integer. An exception is thrown if the data is not all available.
  909. /// </summary>
  910. public static int DirectReadLittleEndianInt32(Stream source)
  911. {
  912. return ReadByteOrThrow(source)
  913. | (ReadByteOrThrow(source) << 8)
  914. | (ReadByteOrThrow(source) << 16)
  915. | (ReadByteOrThrow(source) << 24);
  916. }
  917. /// <summary>
  918. /// Reads a big-endian encoded integer. An exception is thrown if the data is not all available.
  919. /// </summary>
  920. public static int DirectReadBigEndianInt32(Stream source)
  921. {
  922. return (ReadByteOrThrow(source) << 24)
  923. | (ReadByteOrThrow(source) << 16)
  924. | (ReadByteOrThrow(source) << 8)
  925. | ReadByteOrThrow(source);
  926. }
  927. /// <summary>
  928. /// Reads a varint encoded integer. An exception is thrown if the data is not all available.
  929. /// </summary>
  930. public static int DirectReadVarintInt32(Stream source)
  931. {
  932. uint val;
  933. int bytes = TryReadUInt32Variant(source, out val);
  934. if (bytes <= 0) throw EoF(null);
  935. return (int) val;
  936. }
  937. /// <summary>
  938. /// 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.
  939. /// </summary>
  940. public static void DirectReadBytes(Stream source, byte[] buffer, int offset, int count)
  941. {
  942. int read;
  943. if (source == null) throw new ArgumentNullException("source");
  944. while(count > 0 && (read = source.Read(buffer, offset, count)) > 0)
  945. {
  946. count -= read;
  947. offset += read;
  948. }
  949. if (count > 0) throw EoF(null);
  950. }
  951. /// <summary>
  952. /// Reads a given number of bytes directly from the source. An exception is thrown if the data is not all available.
  953. /// </summary>
  954. public static byte[] DirectReadBytes(Stream source, int count)
  955. {
  956. byte[] buffer = new byte[count];
  957. DirectReadBytes(source, buffer, 0, count);
  958. return buffer;
  959. }
  960. /// <summary>
  961. /// Reads a string (of a given lenth, in bytes) directly from the source. An exception is thrown if the data is not all available.
  962. /// </summary>
  963. public static string DirectReadString(Stream source, int length)
  964. {
  965. byte[] buffer = new byte[length];
  966. DirectReadBytes(source, buffer, 0, length);
  967. return Encoding.UTF8.GetString(buffer, 0, length);
  968. }
  969. /// <summary>
  970. /// Reads the length-prefix of a message from a stream without buffering additional data, allowing a fixed-length
  971. /// reader to be created.
  972. /// </summary>
  973. public static int ReadLengthPrefix(Stream source, bool expectHeader, PrefixStyle style, out int fieldNumber, out int bytesRead)
  974. {
  975. fieldNumber = 0;
  976. switch (style)
  977. {
  978. case PrefixStyle.None:
  979. bytesRead = 0;
  980. return int.MaxValue;
  981. case PrefixStyle.Base128:
  982. uint val;
  983. int tmpBytesRead;
  984. bytesRead = 0;
  985. if (expectHeader)
  986. {
  987. tmpBytesRead = ProtoReader.TryReadUInt32Variant(source, out val);
  988. bytesRead += tmpBytesRead;
  989. if (tmpBytesRead > 0)
  990. {
  991. if ((val & 7) != (uint)WireType.String)
  992. { // got a header, but it isn't a string
  993. throw new InvalidOperationException();
  994. }
  995. fieldNumber = (int)(val >> 3);
  996. tmpBytesRead = ProtoReader.TryReadUInt32Variant(source, out val);
  997. bytesRead += tmpBytesRead;
  998. if (bytesRead == 0)
  999. { // got a header, but no length
  1000. throw EoF(null);
  1001. }
  1002. return (int)val;
  1003. }
  1004. else
  1005. { // no header
  1006. bytesRead = 0;
  1007. return -1;
  1008. }
  1009. }
  1010. // check for a length
  1011. tmpBytesRead = ProtoReader.TryReadUInt32Variant(source, out val);
  1012. bytesRead += tmpBytesRead;
  1013. return bytesRead < 0 ? -1 : (int)val;
  1014. case PrefixStyle.Fixed32:
  1015. {
  1016. int b = source.ReadByte();
  1017. if (b < 0)
  1018. {
  1019. bytesRead = 0;
  1020. return -1;
  1021. }
  1022. bytesRead = 4;
  1023. return b
  1024. | (ReadByteOrThrow(source) << 8)
  1025. | (ReadByteOrThrow(source) << 16)
  1026. | (ReadByteOrThrow(source) << 24);
  1027. }
  1028. case PrefixStyle.Fixed32BigEndian:
  1029. {
  1030. int b = source.ReadByte();
  1031. if (b < 0)
  1032. {
  1033. bytesRead = 0;
  1034. return -1;
  1035. }
  1036. bytesRead = 4;
  1037. return (b << 24)
  1038. | (ReadByteOrThrow(source) << 16)
  1039. | (ReadByteOrThrow(source) << 8)
  1040. | ReadByteOrThrow(source);
  1041. }
  1042. default:
  1043. throw new ArgumentOutOfRangeException("style");
  1044. }
  1045. }
  1046. /// <returns>The number of bytes consumed; 0 if no data available</returns>
  1047. private static int TryReadUInt32Variant(Stream source, out uint value)
  1048. {
  1049. value = 0;
  1050. int b = source.ReadByte();
  1051. if (b < 0) { return 0; }
  1052. value = (uint)b;
  1053. if ((value & 0x80) == 0) { return 1; }
  1054. value &= 0x7F;
  1055. b = source.ReadByte();
  1056. if (b < 0) throw EoF(null);
  1057. value |= ((uint)b & 0x7F) << 7;
  1058. if ((b & 0x80) == 0) return 2;
  1059. b = source.ReadByte();
  1060. if (b < 0) throw EoF(null);
  1061. value |= ((uint)b & 0x7F) << 14;
  1062. if ((b & 0x80) == 0) return 3;
  1063. b = source.ReadByte();
  1064. if (b < 0) throw EoF(null);
  1065. value |= ((uint)b & 0x7F) << 21;
  1066. if ((b & 0x80) == 0) return 4;
  1067. b = source.ReadByte();
  1068. if (b < 0) throw EoF(null);
  1069. value |= (uint)b << 28; // can only use 4 bits from this chunk
  1070. if ((b & 0xF0) == 0) return 5;
  1071. throw new OverflowException();
  1072. }
  1073. internal static void Seek(Stream source, int count, byte[] buffer)
  1074. {
  1075. if (source.CanSeek)
  1076. {
  1077. source.Seek(count, SeekOrigin.Current);
  1078. count = 0;
  1079. }
  1080. else if (buffer != null)
  1081. {
  1082. int bytesRead;
  1083. while (count > buffer.Length && (bytesRead = source.Read(buffer, 0, buffer.Length)) > 0)
  1084. {
  1085. count -= bytesRead;
  1086. }
  1087. while (count > 0 && (bytesRead = source.Read(buffer, 0, count)) > 0)
  1088. {
  1089. count -= bytesRead;
  1090. }
  1091. }
  1092. else // borrow a buffer
  1093. {
  1094. buffer = BufferPool.GetBuffer();
  1095. try
  1096. {
  1097. int bytesRead;
  1098. while (count > buffer.Length && (bytesRead = source.Read(buffer, 0, buffer.Length)) > 0)
  1099. {
  1100. count -= bytesRead;
  1101. }
  1102. while (count > 0 && (bytesRead = source.Read(buffer, 0, count)) > 0)
  1103. {
  1104. count -= bytesRead;
  1105. }
  1106. }
  1107. finally
  1108. {
  1109. BufferPool.ReleaseBufferToPool(ref buffer);
  1110. }
  1111. }
  1112. if (count > 0) throw EoF(null);
  1113. }
  1114. internal static Exception AddErrorData(Exception exception, ProtoReader source)
  1115. {
  1116. #if !CF && !FX11 && !PORTABLE
  1117. if (exception != null && source != null && !exception.Data.Contains("protoSource"))
  1118. {
  1119. exception.Data.Add("protoSource", string.Format("tag={0}; wire-type={1}; offset={2}; depth={3}",
  1120. source.fieldNumber, source.wireType, source.position, source.depth));
  1121. }
  1122. #endif
  1123. return exception;
  1124. }
  1125. private static Exception EoF(ProtoReader source)
  1126. {
  1127. return AddErrorData(new EndOfStreamException(), source);
  1128. }
  1129. /// <summary>
  1130. /// Copies the current field into the instance as extension data
  1131. /// </summary>
  1132. public void AppendExtensionData(IExtensible instance)
  1133. {
  1134. if (instance == null) throw new ArgumentNullException("instance");
  1135. IExtension extn = instance.GetExtensionObject(true);
  1136. bool commit = false;
  1137. // unusually we *don't* want "using" here; the "finally" does that, with
  1138. // the extension object being responsible for disposal etc
  1139. Stream dest = extn.BeginAppend();
  1140. try
  1141. {
  1142. //TODO: replace this with stream-based, buffered raw copying
  1143. using (ProtoWriter writer = new ProtoWriter(dest, model, null))
  1144. {
  1145. AppendExtensionField(writer);
  1146. writer.Close();
  1147. }
  1148. commit = true;
  1149. }
  1150. finally { extn.EndAppend(dest, commit); }
  1151. }
  1152. private void AppendExtensionField(ProtoWriter writer)
  1153. {
  1154. //TODO: replace this with stream-based, buffered raw copying
  1155. ProtoWriter.WriteFieldHeader(fieldNumber, wireType, writer);
  1156. switch (wireType)
  1157. {
  1158. case WireType.Fixed32:
  1159. ProtoWriter.WriteInt32(ReadInt32(), writer);
  1160. return;
  1161. case WireType.Variant:
  1162. case WireType.SignedVariant:
  1163. case WireType.Fixed64:
  1164. ProtoWriter.WriteInt64(ReadInt64(), writer);
  1165. return;
  1166. case WireType.String:
  1167. ProtoWriter.WriteBytes(AppendBytes(null, this), writer);
  1168. return;
  1169. case WireType.StartGroup:
  1170. SubItemToken readerToken = StartSubItem(this),
  1171. writerToken = ProtoWriter.StartSubItem(null, writer);
  1172. while (ReadFieldHeader() > 0) { AppendExtensionField(writer); }
  1173. EndSubItem(readerToken, this);
  1174. ProtoWriter.EndSubItem(writerToken, writer);
  1175. return;
  1176. case WireType.None: // treat as explicit errorr
  1177. case WireType.EndGroup: // treat as explicit error
  1178. default: // treat as implicit error
  1179. throw CreateWireTypeException();
  1180. }
  1181. }
  1182. /// <summary>
  1183. /// Indicates whether the reader still has data remaining in the current sub-item,
  1184. /// additionally setting the wire-type for the next field if there is more data.
  1185. /// This is used when decoding packed data.
  1186. /// </summary>
  1187. public static bool HasSubValue(ProtoBuf.WireType wireType, ProtoReader source)
  1188. {
  1189. if (source == null) throw new ArgumentNullException("source");
  1190. // check for virtual end of stream
  1191. if (source.blockEnd <= source.position || wireType == WireType.EndGroup) { return false; }
  1192. source.wireType = wireType;
  1193. return true;
  1194. }
  1195. internal int GetTypeKey(ref Type type)
  1196. {
  1197. return model.GetKey(ref type);
  1198. }
  1199. internal NetObjectCache NetCache
  1200. {
  1201. get { return netCache; }
  1202. }
  1203. internal System.Type DeserializeType(string value)
  1204. {
  1205. return TypeModel.DeserializeType(model, value);
  1206. }
  1207. internal void SetRootObject(object value)
  1208. {
  1209. netCache.SetKeyedObject(NetObjectCache.Root, value);
  1210. trapCount--;
  1211. }
  1212. /// <summary>
  1213. /// Utility method, not intended for public use; this helps maintain the root object is complex scenarios
  1214. /// </summary>
  1215. public static void NoteObject(object value, ProtoReader reader)
  1216. {
  1217. if (reader == null) throw new ArgumentNullException("reader");
  1218. if(reader.trapCount != 0)
  1219. {
  1220. reader.netCache.RegisterTrappedObject(value);
  1221. reader.trapCount--;
  1222. }
  1223. }
  1224. /// <summary>
  1225. /// Reads a Type from the stream, using the model's DynamicTypeFormatting if appropriate; supported wire-types: String
  1226. /// </summary>
  1227. public System.Type ReadType()
  1228. {
  1229. return TypeModel.DeserializeType(model, ReadString());
  1230. }
  1231. internal void TrapNextObject(int newObjectKey)
  1232. {
  1233. trapCount++;
  1234. netCache.SetKeyedObject(newObjectKey, null); // use null as a temp
  1235. }
  1236. internal void CheckFullyConsumed()
  1237. {
  1238. if (isFixedLength)
  1239. {
  1240. if (dataRemaining != 0) throw new ProtoException("Incorrect number of bytes consumed");
  1241. }
  1242. else
  1243. {
  1244. if (available != 0) throw new ProtoException("Unconsumed data left in the buffer; this suggests corrupt input");
  1245. }
  1246. }
  1247. /// <summary>
  1248. /// Merge two objects using the details from the current reader; this is used to change the type
  1249. /// of objects when an inheritance relationship is discovered later than usual during deserilazation.
  1250. /// </summary>
  1251. public static object Merge(ProtoReader parent, object from, object to)
  1252. {
  1253. if (parent == null) throw new ArgumentNullException("parent");
  1254. TypeModel model = parent.Model;
  1255. SerializationContext ctx = parent.Context;
  1256. if(model == null) throw new InvalidOperationException("Types cannot be merged unless a type-model has been specified");
  1257. using (MemoryStream ms = new MemoryStream())
  1258. {
  1259. model.Serialize(ms, from, ctx);
  1260. ms.Position = 0;
  1261. return model.Deserialize(ms, to, null);
  1262. }
  1263. }
  1264. #region RECYCLER
  1265. internal static ProtoReader Create(Stream source, TypeModel model, SerializationContext context, int len)
  1266. {
  1267. ProtoReader reader = GetRecycled();
  1268. if (reader == null)
  1269. {
  1270. return new ProtoReader(source, model, context, len);
  1271. }
  1272. Init(reader, source, model, context, len);
  1273. return reader;
  1274. }
  1275. #if !PLAT_NO_THREADSTATIC
  1276. [ThreadStatic]
  1277. private static ProtoReader lastReader;
  1278. private static ProtoReader GetRecycled()
  1279. {
  1280. ProtoReader tmp = lastReader;
  1281. lastReader = null;
  1282. return tmp;
  1283. }
  1284. internal static void Recycle(ProtoReader reader)
  1285. {
  1286. if(reader != null)
  1287. {
  1288. reader.Dispose();
  1289. lastReader = reader;
  1290. }
  1291. }
  1292. #elif !PLAT_NO_INTERLOCKED
  1293. private static object lastReader;
  1294. private static ProtoReader GetRecycled()
  1295. {
  1296. return (ProtoReader)System.Threading.Interlocked.Exchange(ref lastReader, null);
  1297. }
  1298. internal static void Recycle(ProtoReader reader)
  1299. {
  1300. if(reader != null)
  1301. {
  1302. reader.Dispose();
  1303. System.Threading.Interlocked.Exchange(ref lastReader, reader);
  1304. }
  1305. }
  1306. #else
  1307. private static readonly object recycleLock = new object();
  1308. private static ProtoReader lastReader;
  1309. private static ProtoReader GetRecycled()
  1310. {
  1311. lock(recycleLock)
  1312. {
  1313. ProtoReader tmp = lastReader;
  1314. lastReader = null;
  1315. return tmp;
  1316. }
  1317. }
  1318. internal static void Recycle(ProtoReader reader)
  1319. {
  1320. if(reader != null)
  1321. {
  1322. reader.Dispose();
  1323. lock(recycleLock)
  1324. {
  1325. lastReader = reader;
  1326. }
  1327. }
  1328. }
  1329. #endif
  1330. #endregion
  1331. }
  1332. }