12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421 |
-
- using System;
- using System.IO;
- using System.Text;
- using ProtoBuf.Meta;
- #if FEAT_IKVM
- using Type = IKVM.Reflection.Type;
- #endif
- #if MF
- using EndOfStreamException = System.ApplicationException;
- using OverflowException = System.ApplicationException;
- #endif
- namespace ProtoBuf
- {
-
-
-
-
- public sealed class ProtoReader : IDisposable
- {
- Stream source;
- byte[] ioBuffer;
- TypeModel model;
- int fieldNumber, depth, dataRemaining, ioIndex, position, available, blockEnd;
- WireType wireType;
- bool isFixedLength, internStrings;
- private NetObjectCache netCache;
-
-
-
-
- uint trapCount;
-
-
-
- public int FieldNumber { get { return fieldNumber; } }
-
-
-
- public WireType WireType { get { return wireType; } }
-
-
-
-
-
-
- public ProtoReader(Stream source, TypeModel model, SerializationContext context)
- {
- Init(this, source, model, context, TO_EOF);
- }
- internal const int TO_EOF = -1;
-
-
-
-
-
-
-
-
- public bool InternStrings { get { return internStrings; } set { internStrings = value; } }
-
-
-
-
-
-
-
- public ProtoReader(Stream source, TypeModel model, SerializationContext context, int length)
- {
- Init(this, source, model, context, length);
- }
- private static void Init(ProtoReader reader, Stream source, TypeModel model, SerializationContext context, int length)
- {
- if (source == null) throw new ArgumentNullException("source");
- if (!source.CanRead) throw new ArgumentException("Cannot read from stream", "source");
- reader.source = source;
- reader.ioBuffer = BufferPool.GetBuffer();
- reader.model = model;
- bool isFixedLength = length >= 0;
- reader.isFixedLength = isFixedLength;
- reader.dataRemaining = isFixedLength ? length : 0;
- if (context == null) { context = SerializationContext.Default; }
- else { context.Freeze(); }
- reader.context = context;
- reader.position = reader.available = reader.depth = reader.fieldNumber = reader.ioIndex = 0;
- reader.blockEnd = int.MaxValue;
- reader.internStrings = true;
- reader.wireType = WireType.None;
- reader.trapCount = 1;
- if(reader.netCache == null) reader.netCache = new NetObjectCache();
- }
- private SerializationContext context;
-
-
-
- public SerializationContext Context { get { return context; } }
-
-
-
-
-
- public void Dispose()
- {
-
- source = null;
- model = null;
- BufferPool.ReleaseBufferToPool(ref ioBuffer);
- if(stringInterner != null) stringInterner.Clear();
- if(netCache != null) netCache.Clear();
- }
- internal int TryReadUInt32VariantWithoutMoving(bool trimNegative, out uint value)
- {
- if (available < 10) Ensure(10, false);
- if (available == 0)
- {
- value = 0;
- return 0;
- }
- int readPos = ioIndex;
- value = ioBuffer[readPos++];
- if ((value & 0x80) == 0) return 1;
- value &= 0x7F;
- if (available == 1) throw EoF(this);
- uint chunk = ioBuffer[readPos++];
- value |= (chunk & 0x7F) << 7;
- if ((chunk & 0x80) == 0) return 2;
- if (available == 2) throw EoF(this);
- chunk = ioBuffer[readPos++];
- value |= (chunk & 0x7F) << 14;
- if ((chunk & 0x80) == 0) return 3;
- if (available == 3) throw EoF(this);
- chunk = ioBuffer[readPos++];
- value |= (chunk & 0x7F) << 21;
- if ((chunk & 0x80) == 0) return 4;
- if (available == 4) throw EoF(this);
- chunk = ioBuffer[readPos];
- value |= chunk << 28;
- if ((chunk & 0xF0) == 0) return 5;
- if (trimNegative
- && (chunk & 0xF0) == 0xF0
- && available >= 10
- && ioBuffer[++readPos] == 0xFF
- && ioBuffer[++readPos] == 0xFF
- && ioBuffer[++readPos] == 0xFF
- && ioBuffer[++readPos] == 0xFF
- && ioBuffer[++readPos] == 0x01)
- {
- return 10;
- }
- throw AddErrorData(new OverflowException(), this);
- }
- private uint ReadUInt32Variant(bool trimNegative)
- {
- uint value;
- int read = TryReadUInt32VariantWithoutMoving(trimNegative, out value);
- if (read > 0)
- {
- ioIndex += read;
- available -= read;
- position += read;
- return value;
- }
- throw EoF(this);
- }
- private bool TryReadUInt32Variant(out uint value)
- {
- int read = TryReadUInt32VariantWithoutMoving(false, out value);
- if (read > 0)
- {
- ioIndex += read;
- available -= read;
- position += read;
- return true;
- }
- return false;
- }
-
-
-
- public uint ReadUInt32()
- {
- switch (wireType)
- {
- case WireType.Variant:
- return ReadUInt32Variant(false);
- case WireType.Fixed32:
- if (available < 4) Ensure(4, true);
- position += 4;
- available -= 4;
- return ((uint)ioBuffer[ioIndex++])
- | (((uint)ioBuffer[ioIndex++]) << 8)
- | (((uint)ioBuffer[ioIndex++]) << 16)
- | (((uint)ioBuffer[ioIndex++]) << 24);
- case WireType.Fixed64:
- ulong val = ReadUInt64();
- checked { return (uint)val; }
- default:
- throw CreateWireTypeException();
- }
- }
-
-
-
-
-
- public int Position { get { return position; } }
- internal void Ensure(int count, bool strict)
- {
- Helpers.DebugAssert(available <= count, "Asking for data without checking first");
- if (count > ioBuffer.Length)
- {
- BufferPool.ResizeAndFlushLeft(ref ioBuffer, count, ioIndex, available);
- ioIndex = 0;
- }
- else if (ioIndex + count >= ioBuffer.Length)
- {
-
- Helpers.BlockCopy(ioBuffer, ioIndex, ioBuffer, 0, available);
- ioIndex = 0;
- }
- count -= available;
- int writePos = ioIndex + available, bytesRead;
- int canRead = ioBuffer.Length - writePos;
- if (isFixedLength)
- {
- if (dataRemaining < canRead) canRead = dataRemaining;
- }
- while (count > 0 && canRead > 0 && (bytesRead = source.Read(ioBuffer, writePos, canRead)) > 0)
- {
- available += bytesRead;
- count -= bytesRead;
- canRead -= bytesRead;
- writePos += bytesRead;
- if (isFixedLength) { dataRemaining -= bytesRead; }
- }
- if (strict && count > 0)
- {
- throw EoF(this);
- }
- }
-
-
-
- public short ReadInt16()
- {
- checked { return (short)ReadInt32(); }
- }
-
-
-
- public ushort ReadUInt16()
- {
- checked { return (ushort)ReadUInt32(); }
- }
-
-
-
- public byte ReadByte()
- {
- checked { return (byte)ReadUInt32(); }
- }
-
-
-
- public sbyte ReadSByte()
- {
- checked { return (sbyte)ReadInt32(); }
- }
-
-
-
- public int ReadInt32()
- {
- switch (wireType)
- {
- case WireType.Variant:
- return (int)ReadUInt32Variant(true);
- case WireType.Fixed32:
- if (available < 4) Ensure(4, true);
- position += 4;
- available -= 4;
- return ((int)ioBuffer[ioIndex++])
- | (((int)ioBuffer[ioIndex++]) << 8)
- | (((int)ioBuffer[ioIndex++]) << 16)
- | (((int)ioBuffer[ioIndex++]) << 24);
- case WireType.Fixed64:
- long l = ReadInt64();
- checked { return (int)l; }
- case WireType.SignedVariant:
- return Zag(ReadUInt32Variant(true));
- default:
- throw CreateWireTypeException();
- }
- }
- private const long Int64Msb = ((long)1) << 63;
- private const int Int32Msb = ((int)1) << 31;
- private static int Zag(uint ziggedValue)
- {
- int value = (int)ziggedValue;
- return (-(value & 0x01)) ^ ((value >> 1) & ~ProtoReader.Int32Msb);
- }
- private static long Zag(ulong ziggedValue)
- {
- long value = (long)ziggedValue;
- return (-(value & 0x01L)) ^ ((value >> 1) & ~ProtoReader.Int64Msb);
- }
-
-
-
- public long ReadInt64()
- {
- switch (wireType)
- {
- case WireType.Variant:
- return (long)ReadUInt64Variant();
- case WireType.Fixed32:
- return ReadInt32();
- case WireType.Fixed64:
- if (available < 8) Ensure(8, true);
- position += 8;
- available -= 8;
- return ((long)ioBuffer[ioIndex++])
- | (((long)ioBuffer[ioIndex++]) << 8)
- | (((long)ioBuffer[ioIndex++]) << 16)
- | (((long)ioBuffer[ioIndex++]) << 24)
- | (((long)ioBuffer[ioIndex++]) << 32)
- | (((long)ioBuffer[ioIndex++]) << 40)
- | (((long)ioBuffer[ioIndex++]) << 48)
- | (((long)ioBuffer[ioIndex++]) << 56);
- case WireType.SignedVariant:
- return Zag(ReadUInt64Variant());
- default:
- throw CreateWireTypeException();
- }
- }
- private int TryReadUInt64VariantWithoutMoving(out ulong value)
- {
- if (available < 10) Ensure(10, false);
- if (available == 0)
- {
- value = 0;
- return 0;
- }
- int readPos = ioIndex;
- value = ioBuffer[readPos++];
- if ((value & 0x80) == 0) return 1;
- value &= 0x7F;
- if (available == 1) throw EoF(this);
- ulong chunk = ioBuffer[readPos++];
- value |= (chunk & 0x7F) << 7;
- if ((chunk & 0x80) == 0) return 2;
- if (available == 2) throw EoF(this);
- chunk = ioBuffer[readPos++];
- value |= (chunk & 0x7F) << 14;
- if ((chunk & 0x80) == 0) return 3;
- if (available == 3) throw EoF(this);
- chunk = ioBuffer[readPos++];
- value |= (chunk & 0x7F) << 21;
- if ((chunk & 0x80) == 0) return 4;
- if (available == 4) throw EoF(this);
- chunk = ioBuffer[readPos++];
- value |= (chunk & 0x7F) << 28;
- if ((chunk & 0x80) == 0) return 5;
- if (available == 5) throw EoF(this);
- chunk = ioBuffer[readPos++];
- value |= (chunk & 0x7F) << 35;
- if ((chunk & 0x80) == 0) return 6;
- if (available == 6) throw EoF(this);
- chunk = ioBuffer[readPos++];
- value |= (chunk & 0x7F) << 42;
- if ((chunk & 0x80) == 0) return 7;
- if (available == 7) throw EoF(this);
- chunk = ioBuffer[readPos++];
- value |= (chunk & 0x7F) << 49;
- if ((chunk & 0x80) == 0) return 8;
- if (available == 8) throw EoF(this);
- chunk = ioBuffer[readPos++];
- value |= (chunk & 0x7F) << 56;
- if ((chunk & 0x80) == 0) return 9;
- if (available == 9) throw EoF(this);
- chunk = ioBuffer[readPos];
- value |= chunk << 63;
- if ((chunk & ~(ulong)0x01) != 0) throw AddErrorData(new OverflowException(), this);
- return 10;
- }
- private ulong ReadUInt64Variant()
- {
- ulong value;
- int read = TryReadUInt64VariantWithoutMoving(out value);
- if (read > 0)
- {
- ioIndex += read;
- available -= read;
- position += read;
- return value;
- }
- throw EoF(this);
- }
- #if NO_GENERICS
- private System.Collections.Hashtable stringInterner;
- private string Intern(string value)
- {
- if (value == null) return null;
- if (value.Length == 0) return "";
- if (stringInterner == null)
- {
- stringInterner = new System.Collections.Hashtable();
- stringInterner.Add(value, value);
- }
- else if (stringInterner.ContainsKey(value))
- {
- value = (string)stringInterner[value];
- }
- else
- {
- stringInterner.Add(value, value);
- }
- return value;
- }
- #else
- private System.Collections.Generic.Dictionary<string,string> stringInterner;
- private string Intern(string value)
- {
- if (value == null) return null;
- if (value.Length == 0) return "";
- string found;
- if (stringInterner == null)
- {
- stringInterner = new System.Collections.Generic.Dictionary<string, string>();
- stringInterner.Add(value, value);
- }
- else if (stringInterner.TryGetValue(value, out found))
- {
- value = found;
- }
- else
- {
- stringInterner.Add(value, value);
- }
- return value;
- }
- #endif
- #if COREFX
- static readonly Encoding encoding = Encoding.UTF8;
- #else
- static readonly UTF8Encoding encoding = new UTF8Encoding();
- #endif
-
-
-
- public string ReadString()
- {
- if (wireType == WireType.String)
- {
- int bytes = (int)ReadUInt32Variant(false);
- if (bytes == 0) return "";
- if (available < bytes) Ensure(bytes, true);
- #if MF
- byte[] tmp;
- if(ioIndex == 0 && bytes == ioBuffer.Length) {
-
- tmp = ioBuffer;
- } else {
- tmp = new byte[bytes];
- Helpers.BlockCopy(ioBuffer, ioIndex, tmp, 0, bytes);
- }
- string s = new string(encoding.GetChars(tmp));
- #else
- string s = encoding.GetString(ioBuffer, ioIndex, bytes);
- #endif
- if (internStrings) { s = Intern(s); }
- available -= bytes;
- position += bytes;
- ioIndex += bytes;
- return s;
- }
- throw CreateWireTypeException();
- }
-
-
-
- public void ThrowEnumException(System.Type type, int value)
- {
- string desc = type == null ? "<null>" : type.FullName;
- throw AddErrorData(new ProtoException("No " + desc + " enum is mapped to the wire-value " + value.ToString()), this);
- }
- private Exception CreateWireTypeException()
- {
- 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");
- }
- private Exception CreateException(string message)
- {
- return AddErrorData(new ProtoException(message), this);
- }
-
-
-
- public
- #if !FEAT_SAFE
- unsafe
- #endif
- double ReadDouble()
- {
- switch (wireType)
- {
- case WireType.Fixed32:
- return ReadSingle();
- case WireType.Fixed64:
- long value = ReadInt64();
- #if FEAT_SAFE
- return BitConverter.ToDouble(BitConverter.GetBytes(value), 0);
- #else
- return *(double*)&value;
- #endif
- default:
- throw CreateWireTypeException();
- }
- }
-
-
-
-
- public static object ReadObject(object value, int key, ProtoReader reader)
- {
- #if FEAT_IKVM
- throw new NotSupportedException();
- #else
- return ReadTypedObject(value, key, reader, null);
- #endif
- }
- #if !FEAT_IKVM
- internal static object ReadTypedObject(object value, int key, ProtoReader reader, Type type)
- {
- if (reader.model == null)
- {
- throw AddErrorData(new InvalidOperationException("Cannot deserialize sub-objects unless a model is provided"), reader);
- }
- SubItemToken token = ProtoReader.StartSubItem(reader);
- if (key >= 0)
- {
- value = reader.model.Deserialize(key, value, reader);
- }
- else if (type != null && reader.model.TryDeserializeAuxiliaryType(reader, DataFormat.Default, Serializer.ListItemTag, type, ref value, true, false, true, false))
- {
-
- }
- else
- {
- TypeModel.ThrowUnexpectedType(type);
- }
- ProtoReader.EndSubItem(token, reader);
- return value;
- }
- #endif
-
-
-
-
-
- public static void EndSubItem(SubItemToken token, ProtoReader reader)
- {
- if (reader == null) throw new ArgumentNullException("reader");
- int value = token.value;
- switch (reader.wireType)
- {
- case WireType.EndGroup:
- if (value >= 0) throw AddErrorData(new ArgumentException("token"), reader);
- if (-value != reader.fieldNumber) throw reader.CreateException("Wrong group was ended");
- reader.wireType = WireType.None;
- reader.depth--;
- break;
-
- default:
- if (value < reader.position) throw reader.CreateException("Sub-message not read entirely");
- if (reader.blockEnd != reader.position && reader.blockEnd != int.MaxValue)
- {
- throw reader.CreateException("Sub-message not read correctly");
- }
- reader.blockEnd = value;
- reader.depth--;
- break;
-
- }
- }
-
-
-
-
- public static SubItemToken StartSubItem(ProtoReader reader)
- {
- if (reader == null) throw new ArgumentNullException("reader");
- switch (reader.wireType)
- {
- case WireType.StartGroup:
- reader.wireType = WireType.None;
- reader.depth++;
- return new SubItemToken(-reader.fieldNumber);
- case WireType.String:
- int len = (int)reader.ReadUInt32Variant(false);
- if (len < 0) throw AddErrorData(new InvalidOperationException(), reader);
- int lastEnd = reader.blockEnd;
- reader.blockEnd = reader.position + len;
- reader.depth++;
- return new SubItemToken(lastEnd);
- default:
- throw reader.CreateWireTypeException();
- }
- }
-
-
-
-
- public int ReadFieldHeader()
- {
-
-
-
- if (blockEnd <= position || wireType == WireType.EndGroup) { return 0; }
- uint tag;
- if (TryReadUInt32Variant(out tag) && tag != 0)
- {
- wireType = (WireType)(tag & 7);
- fieldNumber = (int)(tag >> 3);
- if(fieldNumber < 1) throw new ProtoException("Invalid field in source data: " + fieldNumber.ToString());
- }
- else
- {
- wireType = WireType.None;
- fieldNumber = 0;
- }
- if (wireType == ProtoBuf.WireType.EndGroup)
- {
- if (depth > 0) return 0;
- throw new ProtoException("Unexpected end-group in source data; this usually means the source data is corrupt");
- }
- return fieldNumber;
- }
-
-
-
-
- public bool TryReadFieldHeader(int field)
- {
-
- if (blockEnd <= position || wireType == WireType.EndGroup) { return false; }
- uint tag;
- int read = TryReadUInt32VariantWithoutMoving(false, out tag);
- WireType tmpWireType;
- if (read > 0 && ((int)tag >> 3) == field
- && (tmpWireType = (WireType)(tag & 7)) != WireType.EndGroup)
- {
- wireType = tmpWireType;
- fieldNumber = field;
- position += read;
- ioIndex += read;
- available -= read;
- return true;
- }
- return false;
- }
-
-
-
- public TypeModel Model { get { return model; } }
-
-
-
-
- public void Hint(WireType wireType)
- {
- if (this.wireType == wireType) { }
- else if (((int)wireType & 7) == (int)this.wireType)
- {
- this.wireType = wireType;
- }
-
- }
-
-
-
-
- public void Assert(WireType wireType)
- {
- if (this.wireType == wireType) { }
- else if (((int)wireType & 7) == (int)this.wireType)
- {
- this.wireType = wireType;
- }
- else
- {
- throw CreateWireTypeException();
- }
- }
-
-
-
- public void SkipField()
- {
- switch (wireType)
- {
- case WireType.Fixed32:
- if(available < 4) Ensure(4, true);
- available -= 4;
- ioIndex += 4;
- position += 4;
- return;
- case WireType.Fixed64:
- if (available < 8) Ensure(8, true);
- available -= 8;
- ioIndex += 8;
- position += 8;
- return;
- case WireType.String:
- int len = (int)ReadUInt32Variant(false);
- if (len <= available)
- {
- available -= len;
- ioIndex += len;
- position += len;
- return;
- }
-
- position += len;
- len -= available;
- ioIndex = available = 0;
- if (isFixedLength)
- {
- if (len > dataRemaining) throw EoF(this);
-
- dataRemaining -= len;
- }
- ProtoReader.Seek(source, len, ioBuffer);
- return;
- case WireType.Variant:
- case WireType.SignedVariant:
- ReadUInt64Variant();
- return;
- case WireType.StartGroup:
- int originalFieldNumber = this.fieldNumber;
- depth++;
- while (ReadFieldHeader() > 0) { SkipField(); }
- depth--;
- if (wireType == WireType.EndGroup && fieldNumber == originalFieldNumber)
- {
- wireType = ProtoBuf.WireType.None;
- return;
- }
- throw CreateWireTypeException();
- case WireType.None:
- case WireType.EndGroup:
- default:
- throw CreateWireTypeException();
- }
- }
-
-
-
- public ulong ReadUInt64()
- {
- switch (wireType)
- {
- case WireType.Variant:
- return ReadUInt64Variant();
- case WireType.Fixed32:
- return ReadUInt32();
- case WireType.Fixed64:
- if (available < 8) Ensure(8, true);
- position += 8;
- available -= 8;
- return ((ulong)ioBuffer[ioIndex++])
- | (((ulong)ioBuffer[ioIndex++]) << 8)
- | (((ulong)ioBuffer[ioIndex++]) << 16)
- | (((ulong)ioBuffer[ioIndex++]) << 24)
- | (((ulong)ioBuffer[ioIndex++]) << 32)
- | (((ulong)ioBuffer[ioIndex++]) << 40)
- | (((ulong)ioBuffer[ioIndex++]) << 48)
- | (((ulong)ioBuffer[ioIndex++]) << 56);
- default:
- throw CreateWireTypeException();
- }
- }
-
-
-
- public
- #if !FEAT_SAFE
- unsafe
- #endif
- float ReadSingle()
- {
- switch (wireType)
- {
- case WireType.Fixed32:
- {
- int value = ReadInt32();
- #if FEAT_SAFE
- return BitConverter.ToSingle(BitConverter.GetBytes(value), 0);
- #else
- return *(float*)&value;
- #endif
- }
- case WireType.Fixed64:
- {
- double value = ReadDouble();
- float f = (float)value;
- if (Helpers.IsInfinity(f)
- && !Helpers.IsInfinity(value))
- {
- throw AddErrorData(new OverflowException(), this);
- }
- return f;
- }
- default:
- throw CreateWireTypeException();
- }
- }
-
-
-
-
- public bool ReadBoolean()
- {
- switch (ReadUInt32())
- {
- case 0: return false;
- case 1: return true;
- default: throw CreateException("Unexpected boolean value");
- }
- }
- private static readonly byte[] EmptyBlob = new byte[0];
-
-
-
- public static byte[] AppendBytes(byte[] value, ProtoReader reader)
- {
- if (reader == null) throw new ArgumentNullException("reader");
- switch (reader.wireType)
- {
- case WireType.String:
- int len = (int)reader.ReadUInt32Variant(false);
- reader.wireType = WireType.None;
- if (len == 0) return value == null ? EmptyBlob : value;
- int offset;
- if (value == null || value.Length == 0)
- {
- offset = 0;
- value = new byte[len];
- }
- else
- {
- offset = value.Length;
- byte[] tmp = new byte[value.Length + len];
- Helpers.BlockCopy(value, 0, tmp, 0, value.Length);
- value = tmp;
- }
-
-
- reader.position += len;
- while (len > reader.available)
- {
- if (reader.available > 0)
- {
-
- Helpers.BlockCopy(reader.ioBuffer, reader.ioIndex, value, offset, reader.available);
- len -= reader.available;
- offset += reader.available;
- reader.ioIndex = reader.available = 0;
- }
-
- int count = len > reader.ioBuffer.Length ? reader.ioBuffer.Length : len;
- if (count > 0) reader.Ensure(count, true);
- }
-
- if (len > 0)
- {
- Helpers.BlockCopy(reader.ioBuffer, reader.ioIndex, value, offset, len);
- reader.ioIndex += len;
- reader.available -= len;
- }
- return value;
- case WireType.Variant:
- return new byte[0];
- default:
- throw reader.CreateWireTypeException();
- }
- }
-
-
-
-
-
-
-
-
-
-
-
-
-
- private static int ReadByteOrThrow(Stream source)
- {
- int val = source.ReadByte();
- if (val < 0) throw EoF(null);
- return val;
- }
-
-
-
-
- public static int ReadLengthPrefix(Stream source, bool expectHeader, PrefixStyle style, out int fieldNumber)
- {
- int bytesRead;
- return ReadLengthPrefix(source, expectHeader, style, out fieldNumber, out bytesRead);
- }
-
-
-
- public static int DirectReadLittleEndianInt32(Stream source)
- {
- return ReadByteOrThrow(source)
- | (ReadByteOrThrow(source) << 8)
- | (ReadByteOrThrow(source) << 16)
- | (ReadByteOrThrow(source) << 24);
- }
-
-
-
- public static int DirectReadBigEndianInt32(Stream source)
- {
- return (ReadByteOrThrow(source) << 24)
- | (ReadByteOrThrow(source) << 16)
- | (ReadByteOrThrow(source) << 8)
- | ReadByteOrThrow(source);
- }
-
-
-
- public static int DirectReadVarintInt32(Stream source)
- {
- uint val;
- int bytes = TryReadUInt32Variant(source, out val);
- if (bytes <= 0) throw EoF(null);
- return (int) val;
- }
-
-
-
- public static void DirectReadBytes(Stream source, byte[] buffer, int offset, int count)
- {
- int read;
- if (source == null) throw new ArgumentNullException("source");
- while(count > 0 && (read = source.Read(buffer, offset, count)) > 0)
- {
- count -= read;
- offset += read;
- }
- if (count > 0) throw EoF(null);
- }
-
-
-
- public static byte[] DirectReadBytes(Stream source, int count)
- {
- byte[] buffer = new byte[count];
- DirectReadBytes(source, buffer, 0, count);
- return buffer;
- }
-
-
-
- public static string DirectReadString(Stream source, int length)
- {
- byte[] buffer = new byte[length];
- DirectReadBytes(source, buffer, 0, length);
- return Encoding.UTF8.GetString(buffer, 0, length);
- }
-
-
-
-
- public static int ReadLengthPrefix(Stream source, bool expectHeader, PrefixStyle style, out int fieldNumber, out int bytesRead)
- {
- fieldNumber = 0;
- switch (style)
- {
- case PrefixStyle.None:
- bytesRead = 0;
- return int.MaxValue;
- case PrefixStyle.Base128:
- uint val;
- int tmpBytesRead;
- bytesRead = 0;
- if (expectHeader)
- {
- tmpBytesRead = ProtoReader.TryReadUInt32Variant(source, out val);
- bytesRead += tmpBytesRead;
- if (tmpBytesRead > 0)
- {
- if ((val & 7) != (uint)WireType.String)
- {
- throw new InvalidOperationException();
- }
- fieldNumber = (int)(val >> 3);
- tmpBytesRead = ProtoReader.TryReadUInt32Variant(source, out val);
- bytesRead += tmpBytesRead;
- if (bytesRead == 0)
- {
- throw EoF(null);
- }
- return (int)val;
- }
- else
- {
- bytesRead = 0;
- return -1;
- }
- }
-
- tmpBytesRead = ProtoReader.TryReadUInt32Variant(source, out val);
- bytesRead += tmpBytesRead;
- return bytesRead < 0 ? -1 : (int)val;
- case PrefixStyle.Fixed32:
- {
- int b = source.ReadByte();
- if (b < 0)
- {
- bytesRead = 0;
- return -1;
- }
- bytesRead = 4;
- return b
- | (ReadByteOrThrow(source) << 8)
- | (ReadByteOrThrow(source) << 16)
- | (ReadByteOrThrow(source) << 24);
- }
- case PrefixStyle.Fixed32BigEndian:
- {
- int b = source.ReadByte();
- if (b < 0)
- {
- bytesRead = 0;
- return -1;
- }
- bytesRead = 4;
- return (b << 24)
- | (ReadByteOrThrow(source) << 16)
- | (ReadByteOrThrow(source) << 8)
- | ReadByteOrThrow(source);
- }
- default:
- throw new ArgumentOutOfRangeException("style");
- }
- }
-
- private static int TryReadUInt32Variant(Stream source, out uint value)
- {
- value = 0;
- int b = source.ReadByte();
- if (b < 0) { return 0; }
- value = (uint)b;
- if ((value & 0x80) == 0) { return 1; }
- value &= 0x7F;
- b = source.ReadByte();
- if (b < 0) throw EoF(null);
- value |= ((uint)b & 0x7F) << 7;
- if ((b & 0x80) == 0) return 2;
- b = source.ReadByte();
- if (b < 0) throw EoF(null);
- value |= ((uint)b & 0x7F) << 14;
- if ((b & 0x80) == 0) return 3;
- b = source.ReadByte();
- if (b < 0) throw EoF(null);
- value |= ((uint)b & 0x7F) << 21;
- if ((b & 0x80) == 0) return 4;
- b = source.ReadByte();
- if (b < 0) throw EoF(null);
- value |= (uint)b << 28;
- if ((b & 0xF0) == 0) return 5;
- throw new OverflowException();
- }
- internal static void Seek(Stream source, int count, byte[] buffer)
- {
- if (source.CanSeek)
- {
- source.Seek(count, SeekOrigin.Current);
- count = 0;
- }
- else if (buffer != null)
- {
- int bytesRead;
- while (count > buffer.Length && (bytesRead = source.Read(buffer, 0, buffer.Length)) > 0)
- {
- count -= bytesRead;
- }
- while (count > 0 && (bytesRead = source.Read(buffer, 0, count)) > 0)
- {
- count -= bytesRead;
- }
- }
- else
- {
- buffer = BufferPool.GetBuffer();
- try
- {
- int bytesRead;
- while (count > buffer.Length && (bytesRead = source.Read(buffer, 0, buffer.Length)) > 0)
- {
- count -= bytesRead;
- }
- while (count > 0 && (bytesRead = source.Read(buffer, 0, count)) > 0)
- {
- count -= bytesRead;
- }
- }
- finally
- {
- BufferPool.ReleaseBufferToPool(ref buffer);
- }
- }
- if (count > 0) throw EoF(null);
- }
- internal static Exception AddErrorData(Exception exception, ProtoReader source)
- {
- #if !CF && !FX11 && !PORTABLE
- if (exception != null && source != null && !exception.Data.Contains("protoSource"))
- {
- exception.Data.Add("protoSource", string.Format("tag={0}; wire-type={1}; offset={2}; depth={3}",
- source.fieldNumber, source.wireType, source.position, source.depth));
- }
- #endif
- return exception;
- }
- private static Exception EoF(ProtoReader source)
- {
- return AddErrorData(new EndOfStreamException(), source);
- }
-
-
-
- public void AppendExtensionData(IExtensible instance)
- {
- if (instance == null) throw new ArgumentNullException("instance");
- IExtension extn = instance.GetExtensionObject(true);
- bool commit = false;
-
-
- Stream dest = extn.BeginAppend();
- try
- {
-
- using (ProtoWriter writer = new ProtoWriter(dest, model, null))
- {
- AppendExtensionField(writer);
- writer.Close();
- }
- commit = true;
- }
- finally { extn.EndAppend(dest, commit); }
- }
- private void AppendExtensionField(ProtoWriter writer)
- {
-
- ProtoWriter.WriteFieldHeader(fieldNumber, wireType, writer);
- switch (wireType)
- {
- case WireType.Fixed32:
- ProtoWriter.WriteInt32(ReadInt32(), writer);
- return;
- case WireType.Variant:
- case WireType.SignedVariant:
- case WireType.Fixed64:
- ProtoWriter.WriteInt64(ReadInt64(), writer);
- return;
- case WireType.String:
- ProtoWriter.WriteBytes(AppendBytes(null, this), writer);
- return;
- case WireType.StartGroup:
- SubItemToken readerToken = StartSubItem(this),
- writerToken = ProtoWriter.StartSubItem(null, writer);
- while (ReadFieldHeader() > 0) { AppendExtensionField(writer); }
- EndSubItem(readerToken, this);
- ProtoWriter.EndSubItem(writerToken, writer);
- return;
- case WireType.None:
- case WireType.EndGroup:
- default:
- throw CreateWireTypeException();
- }
- }
-
-
-
-
-
- public static bool HasSubValue(ProtoBuf.WireType wireType, ProtoReader source)
- {
- if (source == null) throw new ArgumentNullException("source");
-
- if (source.blockEnd <= source.position || wireType == WireType.EndGroup) { return false; }
- source.wireType = wireType;
- return true;
- }
- internal int GetTypeKey(ref Type type)
- {
- return model.GetKey(ref type);
- }
- internal NetObjectCache NetCache
- {
- get { return netCache; }
- }
- internal System.Type DeserializeType(string value)
- {
- return TypeModel.DeserializeType(model, value);
- }
- internal void SetRootObject(object value)
- {
- netCache.SetKeyedObject(NetObjectCache.Root, value);
- trapCount--;
- }
-
-
-
-
- public static void NoteObject(object value, ProtoReader reader)
- {
- if (reader == null) throw new ArgumentNullException("reader");
- if(reader.trapCount != 0)
- {
- reader.netCache.RegisterTrappedObject(value);
- reader.trapCount--;
- }
- }
-
-
-
- public System.Type ReadType()
- {
- return TypeModel.DeserializeType(model, ReadString());
- }
- internal void TrapNextObject(int newObjectKey)
- {
- trapCount++;
- netCache.SetKeyedObject(newObjectKey, null);
- }
- internal void CheckFullyConsumed()
- {
- if (isFixedLength)
- {
- if (dataRemaining != 0) throw new ProtoException("Incorrect number of bytes consumed");
- }
- else
- {
- if (available != 0) throw new ProtoException("Unconsumed data left in the buffer; this suggests corrupt input");
- }
- }
-
-
-
-
- public static object Merge(ProtoReader parent, object from, object to)
- {
- if (parent == null) throw new ArgumentNullException("parent");
- TypeModel model = parent.Model;
- SerializationContext ctx = parent.Context;
- if(model == null) throw new InvalidOperationException("Types cannot be merged unless a type-model has been specified");
- using (MemoryStream ms = new MemoryStream())
- {
- model.Serialize(ms, from, ctx);
- ms.Position = 0;
- return model.Deserialize(ms, to, null);
- }
- }
- #region RECYCLER
- internal static ProtoReader Create(Stream source, TypeModel model, SerializationContext context, int len)
- {
- ProtoReader reader = GetRecycled();
- if (reader == null)
- {
- return new ProtoReader(source, model, context, len);
- }
- Init(reader, source, model, context, len);
- return reader;
- }
- #if !PLAT_NO_THREADSTATIC
- [ThreadStatic]
- private static ProtoReader lastReader;
- private static ProtoReader GetRecycled()
- {
- ProtoReader tmp = lastReader;
- lastReader = null;
- return tmp;
- }
- internal static void Recycle(ProtoReader reader)
- {
- if(reader != null)
- {
- reader.Dispose();
- lastReader = reader;
- }
- }
- #elif !PLAT_NO_INTERLOCKED
- private static object lastReader;
- private static ProtoReader GetRecycled()
- {
- return (ProtoReader)System.Threading.Interlocked.Exchange(ref lastReader, null);
- }
- internal static void Recycle(ProtoReader reader)
- {
- if(reader != null)
- {
- reader.Dispose();
- System.Threading.Interlocked.Exchange(ref lastReader, reader);
- }
- }
- #else
- private static readonly object recycleLock = new object();
- private static ProtoReader lastReader;
- private static ProtoReader GetRecycled()
- {
- lock(recycleLock)
- {
- ProtoReader tmp = lastReader;
- lastReader = null;
- return tmp;
- }
- }
- internal static void Recycle(ProtoReader reader)
- {
- if(reader != null)
- {
- reader.Dispose();
- lock(recycleLock)
- {
- lastReader = reader;
- }
- }
- }
- #endif
- #endregion
- }
- }
|