/// <summary> /// Reads and decodes a key from the Protobuf stream. /// </summary> /// <param name="stream">The input stream.</param> /// <param name="fieldNumber">Decoded field number.</param> /// <param name="wireType">Decoded wire type.</param> public static void ReadKey(Stream stream, out uint fieldNumber, out WireType wireType) { ulong value = ReadUnsignedVarint(stream); wireType = (WireType)(value & 0x7ul); fieldNumber = (uint)(value >> 3); }
public ArrayDecorator(TypeModel model, IProtoSerializer tail, int fieldNumber, bool writePacked, WireType packedWireType, Type arrayType, bool overwriteList, bool supportNull) : base(tail) { this.itemType = arrayType.GetElementType(); Type arg_3E_0 = (!supportNull) ? (Helpers.GetUnderlyingType(this.itemType) ?? this.itemType) : this.itemType; if ((writePacked || packedWireType != WireType.None) && fieldNumber <= 0) { throw new ArgumentOutOfRangeException("fieldNumber"); } if (!ListDecorator.CanPack(packedWireType)) { if (writePacked) { throw new InvalidOperationException("Only simple data-types can use packed encoding"); } packedWireType = WireType.None; } this.fieldNumber = fieldNumber; this.packedWireType = packedWireType; if (writePacked) { this.options |= 1; } if (overwriteList) { this.options |= 2; } if (supportNull) { this.options |= 4; } this.arrayType = arrayType; }
public ListDecorator(Type declaredType, Type concreteType, IProtoSerializer tail, int packedFieldNumber, WireType packedWireType) : base(tail) { this.packedWireType = WireType.None; if (packedFieldNumber != 0) { if (packedFieldNumber < 0) throw new ArgumentOutOfRangeException("packedFieldNumber"); switch(packedWireType) { case WireType.Fixed32: case WireType.Fixed64: case WireType.SignedVariant: case WireType.Variant: break; default: throw new InvalidOperationException("Only simple data-types can use packed encoding"); } this.packedFieldNumber = packedFieldNumber; this.packedWireType = packedWireType; } if (declaredType == null) throw new ArgumentNullException("declaredType"); if (declaredType.IsArray) throw new ArgumentException("Cannot treat arrays as lists", "declaredType"); this.declaredType = declaredType; this.concreteType = concreteType; // look for a public list.Add(typedObject) method add = TypeModel.ResolveListAdd(declaredType, tail.ExpectedType, out isList); if (add == null) throw new InvalidOperationException(); }
public ListDecorator(Type declaredType, Type concreteType, IProtoSerializer tail, int fieldNumber, bool writePacked, WireType packedWireType, bool returnList, bool overwriteList) : base(tail) { if (returnList) options |= OPTIONS_ReturnList; if (overwriteList) options |= OPTIONS_OverwriteList; if ((writePacked || packedWireType != WireType.None) && fieldNumber <= 0) throw new ArgumentOutOfRangeException("fieldNumber"); if (!CanPack(packedWireType)) { if (writePacked) throw new InvalidOperationException("Only simple data-types can use packed encoding"); packedWireType = WireType.None; } this.fieldNumber = fieldNumber; if (writePacked) options |= OPTIONS_WritePacked; this.packedWireType = packedWireType; if (declaredType == null) throw new ArgumentNullException("declaredType"); if (declaredType.IsArray) throw new ArgumentException("Cannot treat arrays as lists", "declaredType"); this.declaredType = declaredType; this.concreteType = concreteType; // look for a public list.Add(typedObject) method bool isList; add = TypeModel.ResolveListAdd(declaredType, tail.ExpectedType, out isList); if (isList) { options |= OPTIONS_IsList; if (declaredType.FullName.StartsWith("System.Data.Linq.EntitySet`1[[")) { // see http://stackoverflow.com/questions/6194639/entityset-is-there-a-sane-reason-that-ilist-add-doesnt-set-assigned options |= OPTIONS_SuppressIList; } } if (add == null) throw new InvalidOperationException(); }
public TagDecorator(int fieldNumber, WireType wireType, bool strict, IProtoSerializer tail) : base(tail) { this.fieldNumber = fieldNumber; this.wireType = wireType; this.strict = strict; }
public ArrayDecorator(TypeModel model, IProtoSerializer tail, int fieldNumber, bool writePacked, WireType packedWireType, Type arrayType, bool overwriteList, bool supportNull) : base(tail) { Helpers.DebugAssert(arrayType != null, "arrayType should be non-null"); Helpers.DebugAssert(arrayType.IsArray && arrayType.GetArrayRank() == 1, "should be single-dimension array; " + arrayType.FullName); this.itemType = arrayType.GetElementType(); #if NO_GENERICS Type underlyingItemType = itemType; #else Type underlyingItemType = supportNull ? itemType : (Helpers.GetUnderlyingType(itemType) ?? itemType); #endif Helpers.DebugAssert(underlyingItemType == Tail.ExpectedType, "invalid tail"); Helpers.DebugAssert(Tail.ExpectedType != model.MapType(typeof(byte)), "Should have used BlobSerializer"); if ((writePacked || packedWireType != WireType.None) && fieldNumber <= 0) throw new ArgumentOutOfRangeException("fieldNumber"); if (!ListDecorator.CanPack(packedWireType)) { if (writePacked) throw new InvalidOperationException("Only simple data-types can use packed encoding"); packedWireType = WireType.None; } this.fieldNumber = fieldNumber; this.packedWireType = packedWireType; if (writePacked) options |= OPTIONS_WritePacked; if (overwriteList) options |= OPTIONS_OverwriteList; if (supportNull) options |= OPTIONS_SupportNull; this.arrayType = arrayType; }
internal ImmutableCollectionDecorator(TypeModel model, Type declaredType, Type concreteType, IProtoSerializer tail, int fieldNumber, bool writePacked, WireType packedWireType, bool returnList, bool overwriteList, bool supportNull, MethodInfo builderFactory, MethodInfo add, MethodInfo addRange, MethodInfo finish) : base(model, declaredType, concreteType, tail, fieldNumber, writePacked, packedWireType, returnList, overwriteList, supportNull) { this.builderFactory = builderFactory; this.add = add; this.addRange = addRange; this.finish = finish; }
internal static void EmitReadList(ProtoBuf.Compiler.CompilerContext ctx, Compiler.Local list, IProtoSerializer tail, MethodInfo add, WireType packedWireType) { using (Compiler.Local fieldNumber = new Compiler.Local(ctx, typeof(int))) { Compiler.CodeLabel readPacked = packedWireType == WireType.None ? new Compiler.CodeLabel() : ctx.DefineLabel(); if (packedWireType != WireType.None) { ctx.LoadReaderWriter(); ctx.LoadValue(typeof(ProtoReader).GetProperty("WireType")); ctx.LoadValue((int)WireType.String); ctx.BranchIfEqual(readPacked, false); } ctx.LoadReaderWriter(); ctx.LoadValue(typeof(ProtoReader).GetProperty("FieldNumber")); ctx.StoreValue(fieldNumber); Compiler.CodeLabel @continue = ctx.DefineLabel(); ctx.MarkLabel(@continue); EmitReadAndAddItem(ctx, list, tail, add); ctx.LoadReaderWriter(); ctx.LoadValue(fieldNumber); ctx.EmitCall(typeof(ProtoReader).GetMethod("TryReadFieldHeader")); ctx.BranchIfTrue(@continue, false); if (packedWireType != WireType.None) { Compiler.CodeLabel allDone = ctx.DefineLabel(); ctx.Branch(allDone, false); ctx.MarkLabel(readPacked); ctx.LoadReaderWriter(); ctx.EmitCall(typeof(ProtoReader).GetMethod("StartSubItem")); Compiler.CodeLabel testForData = ctx.DefineLabel(), noMoreData = ctx.DefineLabel(); ctx.MarkLabel(testForData); ctx.LoadValue((int)packedWireType); ctx.LoadReaderWriter(); ctx.EmitCall(typeof(ProtoReader).GetMethod("HasSubValue")); ctx.BranchIfFalse(noMoreData, false); EmitReadAndAddItem(ctx, list, tail, add); ctx.Branch(testForData, false); ctx.MarkLabel(noMoreData); ctx.LoadReaderWriter(); ctx.EmitCall(typeof(ProtoReader).GetMethod("EndSubItem")); ctx.MarkLabel(allDone); } } }
/// <summary> /// Skips the field with the specified wire type. /// </summary> public static void Skip(Stream stream, WireType wireType) { Action<Stream> skipAction; if (!Cache.TryGetValue(wireType, out skipAction)) { throw new KeyNotFoundException(String.Format( "The wire type could not be skipped, because there is no appropriate method: {0}", wireType)); } skipAction(stream); }
/// <summary> /// Creates a new writer against a stream /// </summary> /// <param name="dest">The destination stream</param> /// <param name="model">The model to use for serialization; this can be null, but this will impair the ability to serialize sub-objects</param> /// <param name="context">Additional context about this serialization operation</param> public ProtoWriter(Stream dest, TypeModel model, SerializationContext context) { if (dest == null) throw new ArgumentNullException("dest"); if (!dest.CanWrite) throw new ArgumentException("Cannot write to stream", "dest"); //if (model == null) throw new ArgumentNullException("model"); this.dest = dest; this.ioBuffer = BufferPool.GetBuffer(); this.model = model; this.wireType = WireType.None; if (context == null) { context = SerializationContext.Default; } else { context.Freeze(); } this.context = context; }
internal static bool CanPack(WireType wireType) { switch (wireType) { case WireType.Fixed32: case WireType.Fixed64: case WireType.SignedVariant: case WireType.Variant: return true; default: return false; } }
public ProtoReader(Stream source) { #if DEBUG && !PocketPC Protocol.ProtoBuffers.Tools.VisualDebuging(depth, System.Reflection.MethodInfo.GetCurrentMethod()); #endif this.depth = 0; this.position = 0; this.source = source; this.buffer = BufferPool.LockBuffer(); this.wireType = WireType.None; this.fieldNumber = 0; this.subMessageLimit = 0; }
public int BeginSubMessage() { #if DEBUG && !PocketPC Protocol.ProtoBuffers.Tools.VisualDebuging(depth, System.Reflection.MethodInfo.GetCurrentMethod()); #endif if (this.wireType != WireType.Message) throw new InvalidOperationException(); int currentMessageLimit = this.subMessageLimit; this.subMessageLimit = this.position + (int)PrivateReadFixed32(); ++this.depth; this.wireType = ProtoBuffers.WireType.None; return currentMessageLimit; }
/// <summary> /// Writes a field-header, indicating the format of the next data we plan to write. /// </summary> public static void WriteFieldHeader(int fieldNumber, WireType wireType, ProtoWriter writer) { if (writer.wireType != WireType.None) throw new InvalidOperationException("Cannot write a " + wireType + " header until the " + writer.wireType + " data has been written"); if(fieldNumber < 0) throw new ArgumentOutOfRangeException("fieldNumber"); #if DEBUG switch (wireType) { // validate requested header-type case WireType.Fixed32: case WireType.Fixed64: case WireType.String: case WireType.StartGroup: case WireType.SignedVariant: case WireType.Variant: break; // fine case WireType.None: case WireType.EndGroup: default: throw new ArgumentException("Invalid wire-type: " + wireType, "wireType"); } #endif if (writer.packedFieldNumber == 0) { writer.fieldNumber = fieldNumber; writer.wireType = wireType; WriteHeaderCore(fieldNumber, wireType, writer); } else if (writer.packedFieldNumber == fieldNumber) { // we'll set things up, but note we *don't* actually write the header here switch (wireType) { case WireType.Fixed32: case WireType.Fixed64: case WireType.Variant: case WireType.SignedVariant: break; // fine default: throw new InvalidOperationException("Wire-type cannot be encoded as packed: " + wireType); } writer.fieldNumber = fieldNumber; writer.wireType = wireType; } else { throw new InvalidOperationException("Field mismatch during packed encoding; expected " + writer.packedFieldNumber + " but received " + fieldNumber); } }
public ArrayDecorator(IProtoSerializer tail, int fieldNumber, bool writePacked, WireType packedWireType, Type arrayType, bool overwriteList) : base(tail) { Helpers.DebugAssert(arrayType != null, "arrayType should be non-null"); Helpers.DebugAssert(arrayType.IsArray && arrayType.GetArrayRank() == 1, "should be single-dimension array"); Helpers.DebugAssert(arrayType.GetElementType() == Tail.ExpectedType, "invalid tail"); Helpers.DebugAssert(Tail.ExpectedType != typeof(byte), "Should have used BlobSerializer"); if ((writePacked || packedWireType != WireType.None) && fieldNumber <= 0) throw new ArgumentOutOfRangeException("fieldNumber"); if (!ListDecorator.CanPack(packedWireType)) { if (writePacked) throw new InvalidOperationException("Only simple data-types can use packed encoding"); packedWireType = WireType.None; } this.fieldNumber = fieldNumber; this.packedWireType = packedWireType; if (writePacked) options |= OPTIONS_WritePacked; if (overwriteList) options |= OPTIONS_OverwriteList; this.arrayType = arrayType; this.itemType = Tail.ExpectedType; }
public ArrayDecorator(IProtoSerializer tail, int fieldNumber, bool writePacked, WireType packedWireType, Type arrayType, bool overwriteList, bool supportNull, bool asReference, bool nested) : base(tail) { Helpers.DebugAssert(arrayType != null, "arrayType should be non-null"); //Helpers.DebugAssert(arrayType.IsArray && arrayType.GetArrayRank() == 1, "should be single-dimension array; " + arrayType.FullName); if (!arrayType.IsArray /*|| arrayType.GetArrayRank() != 1*/) { throw new Exception("Temporary exception"); } this.itemType = arrayType.GetElementType(); #if NO_GENERICS Type underlyingItemType = itemType; #else Type underlyingItemType = supportNull ? itemType : (Nullable.GetUnderlyingType(itemType) ?? itemType); #endif Helpers.DebugAssert(underlyingItemType == Tail.ExpectedType || (underlyingItemType.IsInterface && Tail.ExpectedType == typeof(object)), "invalid tail"); Helpers.DebugAssert(Tail.ExpectedType != typeof(byte), "Should have used BlobSerializer"); if ((writePacked || packedWireType != WireType.None) && fieldNumber <= 0) throw new ArgumentOutOfRangeException("fieldNumber"); if (!ListDecorator.CanPack(packedWireType)) { if (writePacked) throw new InvalidOperationException("Only simple data-types can use packed encoding"); packedWireType = WireType.None; } this.fieldNumber = fieldNumber; this.packedWireType = packedWireType; if (writePacked) options |= OPTIONS_WritePacked; if (overwriteList) options |= OPTIONS_OverwriteList; if (supportNull) options |= OPTIONS_SupportNull; if (asReference) options |= OPTIONS_AsReference; if (asReference && writePacked) throw new InvalidOperationException("Cannot be packed and AsReference (not supported yet)"); if (asReference && overwriteList) throw new InvalidOperationException("Cannot be overwriteList and AsReference (not supported yet)"); this.arrayType = arrayType; this.nested = nested; }
public ArrayDecorator(IProtoSerializer tail, int packedFieldNumber, WireType packedWireType) : base(tail) { Helpers.DebugAssert(Tail.ExpectedType != typeof(byte), "Should have used BlobSerializer"); this.packedWireType = WireType.None; if (packedFieldNumber != 0) { if (packedFieldNumber < 0) throw new ArgumentOutOfRangeException("packedFieldNumber"); switch (packedWireType) { case WireType.Fixed32: case WireType.Fixed64: case WireType.SignedVariant: case WireType.Variant: break; default: throw new ArgumentException("Packed buffers are not supported for wire-type: " + packedWireType, "packedFieldNumber"); } this.packedFieldNumber = packedFieldNumber; this.packedWireType = packedWireType; } this.itemType = Tail.ExpectedType; this.arrayType = Helpers.MakeArrayType(itemType); }
private IProtoSerializer GetNestedSerializer(BasicList nestedHierarchy, out WireType wireType) { IProtoSerializer ser = null; int listCount = nestedHierarchy.Count; wireType = WireType.None; bool hasAutoDynamicHandling = HasAutoDynamicHandling(nestedHierarchy); for (int i = listCount - 1; i >= 0; i--) { NestedItem item = (NestedItem)nestedHierarchy[i]; if (item.ItemType == null) { bool isDynamic = dynamicType; bool requiresDynamic = item.Type.IsInterface || item.Type == typeof (object); if (!isDynamic && autoDynamicType && requiresDynamic) { isDynamic = true; } else if (hasAutoDynamicHandling && requiresDynamic) { // for now just set isDynamic to true isDynamic = true; } ser = TryGetCoreSerializer(model, dataFormat, item.Type, out wireType, asReference, /*dynamicType*/isDynamic, OverwriteList, false, SupportNull); if (ser == null) throw new InvalidOperationException("No serializer defined for type: " + item.Type.FullName); if (listCount == 1) { ser = new TagDecorator(fieldNumber, wireType, IsStrict, ser); } } else { if (SupportNull) { if (IsPacked) { throw new NotSupportedException("Packed encodings cannot support null values"); } ser = new TagDecorator(NullDecorator.Tag, wireType, IsStrict, ser); ser = new NullDecorator(ser); ser = new TagDecorator(fieldNumber, WireType.StartGroup, false, ser); } else { ser = new TagDecorator(fieldNumber, wireType, IsStrict, ser); } bool nested = listCount > 2 && i >= 1; if (item.Type.IsArray) { ser = new ArrayDecorator(ser, fieldNumber, IsPacked, wireType, item.Type, OverwriteList, SupportNull, AsReference, nested); } else { ser = new ListDecorator(item.Type, item.DefaultType, ser, fieldNumber, IsPacked, wireType, member == null || PropertyDecorator.CanWrite(member), OverwriteList, SupportNull, AsReference, nested, isValueMemberForCollectionBasedTypes); } } } return ser; }
/// <summary> /// Verifies that the stream's current wire-type is as expected, or a specialized sub-type (for example, /// SignedVariant) - in which case the current wire-type is updated. Otherwise an exception is thrown. /// </summary> public void Assert(WireType wireType) { if (this.wireType == wireType) {} // fine; everything as we expect else if (((int)wireType & 7) == (int)this.wireType) { // the underling type is a match; we're customising it with an extension this.wireType = wireType; } else { // nope; that is *not* what we were expecting! throw CreateException(); } }
/// <summary> /// Looks ahead to see whether the next field in the stream is what we expect /// (typically; what we've just finished reading - for example ot read successive list items) /// </summary> public bool TryReadFieldHeader(int field) { // check for virtual end of stream if (blockEnd <= position || wireType == WireType.EndGroup) { return false; } uint tag; int read = TryReadUInt32VariantWithoutMoving(false, out tag); WireType tmpWireType; // need to catch this to exclude (early) any "end group" tokens 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; }
internal static void WriteHeaderCore(int fieldNumber, WireType wireType, ProtoWriter writer) { WriteUInt32Variant((uint)((fieldNumber << 3) | (int)(wireType & (WireType)7)), writer); }
private AnyProto _DoParse(byte[] data, uint start, uint len, bool log = true) { try { AnyProto anyProto = new AnyProto(); uint index = start; while (len - index > 0) { ProtoFiled field = new ProtoFiled(); uint value = 0; uint used = 0; if (!ReadVarint32(out value, out used, data, index, len)) { if (log) { LogError("ReadVarint32 Failed"); } return(null); } index += used; field.Index = value >> 3; uint nWireType = value & 0x7; if (nWireType > (uint)WireType.WIRETYPE_FIXED32) { if (log) { LogError("WireType > WIRETYPE_FIXED32"); } return(null); } WireType type = (WireType)nWireType; switch (type) { case WireType.WIRETYPE_VARINT: { ulong vvalue = 0; if (!ReadVarint64(out vvalue, out used, data, index, len)) { if (log) { LogError("ReadVarint64 Failed"); } return(null); } index += used; long lvalue = (long)vvalue; if (lvalue > int.MaxValue) { field.FieldType = typeof(long); field.FieldValue = lvalue; } else { field.FieldType = typeof(int); field.FieldValue = (int)vvalue; } } break; case WireType.WIRETYPE_FIXED32: { int rvalue = 0; rvalue = (int)data[index]; rvalue |= ((int)data[index + 1]) << 8; rvalue |= ((int)data[index + 2]) << 16; rvalue |= ((int)data[index + 3]) << 24; field.FieldType = typeof(int); field.FieldValue = rvalue; index += 4; } break; case WireType.WIRETYPE_FIXED64: { long rvalue = 0; rvalue = (long)data[index]; rvalue |= ((long)data[index + 1]) << 8; rvalue |= ((long)data[index + 2]) << 16; rvalue |= ((long)data[index + 3]) << 24; rvalue |= ((long)data[index + 4]) << 32; rvalue |= ((long)data[index + 5]) << 40; rvalue |= ((long)data[index + 6]) << 48; rvalue |= ((long)data[index + 7]) << 56; field.FieldType = typeof(long); field.FieldValue = rvalue; index += 8; } break; case WireType.WIRETYPE_LENGTH_DELIMITED: { if (!ReadVarint32(out value, out used, data, index, len)) { if (log) { LogError("ReadVarint32 Failed"); } return(null); } index += used; if (index + value > len) { //Core.Debug.LogError("used data beyond data size"); value = (uint)data.Length - index; return(null); } AnyProto tryProto = _DoParse(data, index, index + value, false); if (tryProto != null) { index += value; field.FieldType = typeof(object); field.IsObject = true; field.FieldValue = tryProto; } else { if (index + value > data.Length) { //Core.Debug.LogError("used data beyond data size"); value = (uint)data.Length - index; return(null); } var getValue = Encoding.UTF8.GetString(data, (int)index, (int)value); index += value; field.FieldType = typeof(string); field.FieldValue = getValue; } } break; case WireType.WIRETYPE_START_GROUP: break; case WireType.WIRETYPE_END_GROUP: break; default: if (log) { LogError("unexcept"); } break; } bool added = false; foreach (var fld in anyProto.Fields) { if (fld.Index == field.Index) { List <ProtoFiled> reptead = null; if (!fld.Repeated) { fld.Repeated = true; reptead = new List <ProtoFiled>(); var nfld = new ProtoFiled(); nfld.FieldType = fld.FieldType; nfld.FieldValue = fld.FieldValue; nfld.Index = fld.Index; nfld.Repeated = false; reptead.Add(nfld); fld.FieldValue = reptead; } else { reptead = (List <ProtoFiled>)fld.FieldValue; } reptead.Add(field); added = true; break; } } if (!added) { anyProto.Fields.Add(field); } } return(anyProto); } catch (System.Exception e) { //Core.Debug.LogError(e); return(null); } }
public static bool TryGetSerializer(Type targetType, ref IProtoSerializer ser, ref WireType wireType) { bool isUnityObjectType = targetType.IsSubclassOf(typeof(UnityEngine.Object)); if (allocaters.ContainsKey(targetType)) { ser = allocaters[targetType]; if (ser != null) { if (isUnityObjectType) { wireType = WireType.Variant; } else { wireType = WireType.String; } } return(ser != null); } if (isUnityObjectType) { ser = Activator.CreateInstance(typeof(UnityRefObjectSerializer <>).MakeGenericType(targetType)) as IProtoTypeSerializer; if (ser != null) { AddCustomSerializer(targetType, ser as IProtoTypeSerializer); wireType = WireType.Variant; return(ser != null); } } return(false); }
/// <summary> /// Writes an *implementation specific* bundled .NET object, including (as options) type-metadata, identity/re-use, etc. /// </summary> public static void WriteNetObject(object value, ProtoWriter dest, int key, NetObjectOptions options) { #if FEAT_IKVM throw new NotSupportedException(); #else if (dest == null) { throw new ArgumentNullException("dest"); } bool dynamicType = (options & NetObjectOptions.DynamicType) != 0, asReference = (options & NetObjectOptions.AsReference) != 0; WireType wireType = dest.WireType; SubItemToken token = ProtoWriter.StartSubItem(null, dest); bool writeObject = true; if (asReference) { bool existing; int objectKey = dest.NetCache.AddObjectKey(value, out existing); ProtoWriter.WriteFieldHeader(existing ? FieldExistingObjectKey : FieldNewObjectKey, WireType.Variant, dest); ProtoWriter.WriteInt32(objectKey, dest); if (existing) { writeObject = false; } } if (writeObject) { if (dynamicType) { bool existing; Type type = value.GetType(); if (!(value is string)) { key = dest.GetTypeKey(ref type); if (key < 0) { throw new InvalidOperationException("Dynamic type is not a contract-type: " + type.Name); } } int typeKey = dest.NetCache.AddObjectKey(type, out existing); ProtoWriter.WriteFieldHeader(existing ? FieldExistingTypeKey : FieldNewTypeKey, WireType.Variant, dest); ProtoWriter.WriteInt32(typeKey, dest); if (!existing) { ProtoWriter.WriteFieldHeader(FieldTypeName, WireType.String, dest); ProtoWriter.WriteString(dest.SerializeType(type), dest); } } ProtoWriter.WriteFieldHeader(FieldObject, wireType, dest); if (value is string) { ProtoWriter.WriteString((string)value, dest); } else { ProtoWriter.WriteObject(value, key, dest); } } ProtoWriter.EndSubItem(token, dest); #endif }
public int WithWireType(WireType wireType) { return(_tag & (int)~WireType.Mask | (int)wireType); }
public static int AsInt(int number, WireType wireType) { return(new MessageTag(number, wireType).Value); }
public MessageTag(int number, WireType wireType) : this(number << 3 | (int)wireType) { }
public object ReadByData(Type _type, WireType _wt) { ProtoTypeCode code = PBHelperCSLE.GetTypeCode(_type); object ret = null; switch (code) { case ProtoTypeCode.Int32: ret = ReadInt32(_wt); break; case ProtoTypeCode.UInt32: ret = ReadUInt32(_wt); break; case ProtoTypeCode.Int64: ret = ReadInt64(_wt); break; case ProtoTypeCode.UInt64: ret = ReadUInt64(_wt); break; case ProtoTypeCode.Single: ret = ReadSingle(_wt); break; case ProtoTypeCode.Double: ret = ReadDouble(_wt); break; case ProtoTypeCode.Boolean: ret = ReadBoolean(_wt); break; case ProtoTypeCode.Char: case ProtoTypeCode.Byte: ret = ReadByte(_wt); break; case ProtoTypeCode.SByte: ret = ReadSByte(_wt); break; case ProtoTypeCode.Int16: ret = ReadInt16(_wt); break; case ProtoTypeCode.UInt16: ret = ReadUInt16(_wt); break; case ProtoTypeCode.Guid: case ProtoTypeCode.Uri: case ProtoTypeCode.ByteArray: case ProtoTypeCode.Type: case ProtoTypeCode.TimeSpan: case ProtoTypeCode.Decimal: case ProtoTypeCode.DateTime: case ProtoTypeCode.String: ret = ReadString(_wt); break; } return(ret); }
public ushort ReadUInt16(WireType _wt) { checked { return((ushort)ReadUInt32(_wt)); } }
internal static void EmitReadList(ProtoBuf.Compiler.CompilerContext ctx, Compiler.Local list, IProtoSerializer tail, MethodInfo add, WireType packedWireType, bool castListForAdd) { using (Compiler.Local fieldNumber = new Compiler.Local(ctx, ctx.MapType(typeof(int)))) { Compiler.CodeLabel readPacked = packedWireType == WireType.None ? new Compiler.CodeLabel() : ctx.DefineLabel(); if (packedWireType != WireType.None) { ctx.LoadReaderWriter(); ctx.LoadValue(typeof(ProtoReader).GetProperty("WireType")); ctx.LoadValue((int)WireType.String); ctx.BranchIfEqual(readPacked, false); } ctx.LoadReaderWriter(); ctx.LoadValue(typeof(ProtoReader).GetProperty("FieldNumber")); ctx.StoreValue(fieldNumber); Compiler.CodeLabel @continue = ctx.DefineLabel(); ctx.MarkLabel(@continue); EmitReadAndAddItem(ctx, list, tail, add, castListForAdd); ctx.LoadReaderWriter(); ctx.LoadValue(fieldNumber); ctx.EmitCall(ctx.MapType(typeof(ProtoReader)).GetMethod("TryReadFieldHeader")); ctx.BranchIfTrue(@continue, false); if (packedWireType != WireType.None) { Compiler.CodeLabel allDone = ctx.DefineLabel(); ctx.Branch(allDone, false); ctx.MarkLabel(readPacked); ctx.LoadReaderWriter(); ctx.EmitCall(ctx.MapType(typeof(ProtoReader)).GetMethod("StartSubItem")); Compiler.CodeLabel testForData = ctx.DefineLabel(), noMoreData = ctx.DefineLabel(); ctx.MarkLabel(testForData); ctx.LoadValue((int)packedWireType); ctx.LoadReaderWriter(); ctx.EmitCall(ctx.MapType(typeof(ProtoReader)).GetMethod("HasSubValue")); ctx.BranchIfFalse(noMoreData, false); EmitReadAndAddItem(ctx, list, tail, add, castListForAdd); ctx.Branch(testForData, false); ctx.MarkLabel(noMoreData); ctx.LoadReaderWriter(); ctx.EmitCall(ctx.MapType(typeof(ProtoReader)).GetMethod("EndSubItem")); ctx.MarkLabel(allDone); } } }
public static void WriteFieldHeader(int fieldNumber, WireType wireType, ProtoWriter writer) { if (writer == null) { throw new ArgumentNullException("writer"); } if (writer.wireType != WireType.None) { throw new InvalidOperationException(string.Concat(new string[] { "Cannot write a ", wireType.ToString(), " header until the ", writer.wireType.ToString(), " data has been written" })); } if (fieldNumber < 0) { throw new ArgumentOutOfRangeException("fieldNumber"); } if (writer.packedFieldNumber == 0) { writer.fieldNumber = fieldNumber; writer.wireType = wireType; ProtoWriter.WriteHeaderCore(fieldNumber, wireType, writer); } else { if (writer.packedFieldNumber != fieldNumber) { throw new InvalidOperationException("Field mismatch during packed encoding; expected " + writer.packedFieldNumber.ToString() + " but received " + fieldNumber.ToString()); } switch (wireType) { case WireType.Variant: case WireType.Fixed64: case WireType.Fixed32: goto IL_D7; case WireType.String: case WireType.StartGroup: case WireType.EndGroup: IL_CB: if (wireType != WireType.SignedVariant) { throw new InvalidOperationException("Wire-type cannot be encoded as packed: " + wireType.ToString()); } goto IL_D7; } goto IL_CB; IL_D7: writer.fieldNumber = fieldNumber; writer.wireType = wireType; } }
public ListDecorator(TypeModel model, Type declaredType, Type concreteType, IProtoSerializer tail, int fieldNumber, bool writePacked, WireType packedWireType, bool returnList, bool overwriteList, bool supportNull) : base(tail) { if (returnList) { options |= OPTIONS_ReturnList; } if (overwriteList) { options |= OPTIONS_OverwriteList; } if (supportNull) { options |= OPTIONS_SupportNull; } if ((writePacked || packedWireType != WireType.None) && fieldNumber <= 0) { throw new ArgumentOutOfRangeException("fieldNumber"); } if (!CanPack(packedWireType)) { if (writePacked) { throw new InvalidOperationException("Only simple data-types can use packed encoding"); } packedWireType = WireType.None; } this.fieldNumber = fieldNumber; if (writePacked) { options |= OPTIONS_WritePacked; } this.packedWireType = packedWireType; if (declaredType == null) { throw new ArgumentNullException("declaredType"); } if (declaredType.IsArray) { throw new ArgumentException("Cannot treat arrays as lists", "declaredType"); } this.declaredType = declaredType; this.concreteType = concreteType; // look for a public list.Add(typedObject) method bool isList; add = TypeModel.ResolveListAdd(model, declaredType, tail.ExpectedType, out isList); if (isList) { options |= OPTIONS_IsList; string fullName = declaredType.FullName; if (fullName != null && fullName.StartsWith("System.Data.Linq.EntitySet`1[[")) { // see http://stackoverflow.com/questions/6194639/entityset-is-there-a-sane-reason-that-ilist-add-doesnt-set-assigned options |= OPTIONS_SuppressIList; } } if (add == null) { throw new InvalidOperationException("Unable to resolve a suitable Add method for " + declaredType.FullName); } }
public sbyte ReadSByte(WireType _wt) { checked { return((sbyte)ReadInt32(_wt)); } }
public ArrayDecorator(IProtoSerializer tail, int fieldNumber, bool writePacked, WireType packedWireType, Type arrayType, bool overwriteList) : base(tail) { Helpers.DebugAssert(arrayType != null, "arrayType should be non-null"); Helpers.DebugAssert(arrayType.IsArray && arrayType.GetArrayRank() == 1, "should be single-dimension array"); Helpers.DebugAssert(arrayType.GetElementType() == Tail.ExpectedType, "invalid tail"); Helpers.DebugAssert(Tail.ExpectedType != typeof(byte), "Should have used BlobSerializer"); if ((writePacked || packedWireType != WireType.None) && fieldNumber <= 0) { throw new ArgumentOutOfRangeException("fieldNumber"); } if (!ListDecorator.CanPack(packedWireType)) { if (writePacked) { throw new InvalidOperationException("Only simple data-types can use packed encoding"); } packedWireType = WireType.None; } this.fieldNumber = fieldNumber; this.packedWireType = packedWireType; if (writePacked) { options |= OPTIONS_WritePacked; } if (overwriteList) { options |= OPTIONS_OverwriteList; } this.arrayType = arrayType; this.itemType = Tail.ExpectedType; }
internal static ListDecorator Create(TypeModel model, Type declaredType, Type concreteType, IProtoSerializer tail, int fieldNumber, bool writePacked, WireType packedWireType, bool returnList, bool overwriteList, bool supportNull) { #if !NO_GENERICS MethodInfo builderFactory, add, addRange, finish; PropertyInfo isEmpty, length; if (returnList && ImmutableCollectionDecorator.IdentifyImmutable(model, declaredType, out builderFactory, out isEmpty, out length, out add, out addRange, out finish)) { return(new ImmutableCollectionDecorator( model, declaredType, concreteType, tail, fieldNumber, writePacked, packedWireType, returnList, overwriteList, supportNull, builderFactory, isEmpty, length, add, addRange, finish)); } #endif return(new ListDecorator(model, declaredType, concreteType, tail, fieldNumber, writePacked, packedWireType, returnList, overwriteList, supportNull)); }
public static void WriteFieldHeader(this Writer writer, SerializerSession session, uint fieldId, Type expectedType, Type actualType, WireType wireType) { var(schemaType, idOrReference) = GetSchemaTypeWithEncoding(session, expectedType, actualType); var field = default(Field); field.FieldIdDelta = fieldId; field.SchemaType = schemaType; field.WireType = wireType; writer.Write(field.Tag); if (field.HasExtendedFieldId) { writer.WriteVarInt(field.FieldIdDelta); } if (field.HasExtendedSchemaType) { writer.WriteType(session, schemaType, idOrReference, actualType); } }
int IMeasuringSerializer <string> .Measure(ISerializationContext context, WireType wireType, string value) => wireType switch {
internal static IProtoSerializer TryGetCoreSerializer(RuntimeTypeModel model, DataFormat dataFormat, Type type, out WireType defaultWireType, bool asReference, bool dynamicType, bool overwriteList, bool allowComplexTypes) { #if !NO_GENERICS type = Helpers.GetUnderlyingType(type) ?? type; #endif if (Helpers.IsEnum(type)) { if (allowComplexTypes && model != null) { // need to do this before checking the typecode; an int enum will report Int32 etc defaultWireType = WireType.Variant; return(new EnumSerializer(type, model.GetEnumMap(type))); } else { // enum is fine for adding as a meta-type defaultWireType = WireType.None; return(null); } } ProtoTypeCode code = Helpers.GetTypeCode(type); switch (code) { case ProtoTypeCode.Int32: defaultWireType = GetIntWireType(dataFormat, 32); return(new Int32Serializer(model)); case ProtoTypeCode.UInt32: defaultWireType = GetIntWireType(dataFormat, 32); return(new UInt32Serializer(model)); case ProtoTypeCode.Int64: defaultWireType = GetIntWireType(dataFormat, 64); return(new Int64Serializer(model)); case ProtoTypeCode.UInt64: defaultWireType = GetIntWireType(dataFormat, 64); return(new UInt64Serializer(model)); case ProtoTypeCode.String: defaultWireType = WireType.String; if (asReference) { return(new NetObjectSerializer(model, model.MapType(typeof(string)), 0, BclHelpers.NetObjectOptions.AsReference)); } return(new StringSerializer(model)); case ProtoTypeCode.Single: defaultWireType = WireType.Fixed32; return(new SingleSerializer(model)); case ProtoTypeCode.Double: defaultWireType = WireType.Fixed64; return(new DoubleSerializer(model)); case ProtoTypeCode.Boolean: defaultWireType = WireType.Variant; return(new BooleanSerializer(model)); case ProtoTypeCode.DateTime: defaultWireType = GetDateTimeWireType(dataFormat); return(new DateTimeSerializer(model)); case ProtoTypeCode.Decimal: defaultWireType = WireType.String; return(new DecimalSerializer(model)); case ProtoTypeCode.Byte: defaultWireType = GetIntWireType(dataFormat, 32); return(new ByteSerializer(model)); case ProtoTypeCode.SByte: defaultWireType = GetIntWireType(dataFormat, 32); return(new SByteSerializer(model)); case ProtoTypeCode.Char: defaultWireType = WireType.Variant; return(new CharSerializer(model)); case ProtoTypeCode.Int16: defaultWireType = GetIntWireType(dataFormat, 32); return(new Int16Serializer(model)); case ProtoTypeCode.UInt16: defaultWireType = GetIntWireType(dataFormat, 32); return(new UInt16Serializer(model)); case ProtoTypeCode.TimeSpan: defaultWireType = GetDateTimeWireType(dataFormat); return(new TimeSpanSerializer(model)); case ProtoTypeCode.Guid: defaultWireType = WireType.String; return(new GuidSerializer(model)); case ProtoTypeCode.Uri: defaultWireType = WireType.String; return(new StringSerializer(model)); // treat as string; wrapped in decorator later case ProtoTypeCode.ByteArray: defaultWireType = WireType.String; return(new BlobSerializer(model, overwriteList)); case ProtoTypeCode.Type: defaultWireType = WireType.String; return(new SystemTypeSerializer(model)); } IProtoSerializer parseable = model.AllowParseableTypes ? ParseableSerializer.TryCreate(type, model) : null; if (parseable != null) { defaultWireType = WireType.String; return(parseable); } if (allowComplexTypes && model != null) { int key = model.GetKey(type, false, true); if (asReference || dynamicType) { defaultWireType = WireType.String; BclHelpers.NetObjectOptions options = BclHelpers.NetObjectOptions.None; if (asReference) { options |= BclHelpers.NetObjectOptions.AsReference; } if (dynamicType) { options |= BclHelpers.NetObjectOptions.DynamicType; } if (key >= 0) { // exists if (asReference && Helpers.IsValueType(type)) { string message = "AsReference cannot be used with value-types"; if (type.Name == "KeyValuePair`2") { message += "; please see http://stackoverflow.com/q/14436606/"; } else { message += ": " + type.FullName; } throw new InvalidOperationException(message); } MetaType meta = model[type]; if (asReference && meta.IsAutoTuple) { options |= BclHelpers.NetObjectOptions.LateSet; } if (meta.UseConstructor) { options |= BclHelpers.NetObjectOptions.UseConstructor; } } return(new NetObjectSerializer(model, type, key, options)); } if (key >= 0) { defaultWireType = dataFormat == DataFormat.Group ? WireType.StartGroup : WireType.String; return(new SubItemSerializer(type, key, model[type], true)); } } defaultWireType = WireType.None; return(null); }
public ArrayDecorator(TypeModel model, IProtoSerializer tail, int fieldNumber, bool writePacked, WireType packedWireType, Type arrayType, bool overwriteList, bool supportNull) : base(tail) { Helpers.DebugAssert(arrayType != null, "arrayType should be non-null"); Helpers.DebugAssert(arrayType.IsArray && arrayType.GetArrayRank() == 1, "should be single-dimension array; " + arrayType.FullName); this.itemType = arrayType.GetElementType(); #if NO_GENERICS Type underlyingItemType = itemType; #else Type underlyingItemType = supportNull ? itemType : (Helpers.GetUnderlyingType(itemType) ?? itemType); #endif Helpers.DebugAssert(underlyingItemType == Tail.ExpectedType || (Tail.ExpectedType == model.MapType(typeof(object)) && !Helpers.IsValueType(underlyingItemType)), "invalid tail"); Helpers.DebugAssert(Tail.ExpectedType != model.MapType(typeof(byte)), "Should have used BlobSerializer"); if ((writePacked || packedWireType != WireType.None) && fieldNumber <= 0) { throw new ArgumentOutOfRangeException("fieldNumber"); } if (!ListDecorator.CanPack(packedWireType)) { if (writePacked) { throw new InvalidOperationException("Only simple data-types can use packed encoding"); } packedWireType = WireType.None; } this.fieldNumber = fieldNumber; this.packedWireType = packedWireType; if (writePacked) { options |= OPTIONS_WritePacked; } if (overwriteList) { options |= OPTIONS_OverwriteList; } if (supportNull) { options |= OPTIONS_SupportNull; } this.arrayType = arrayType; }
/// <summary> /// Makes a tag value given a field number and wire type. /// </summary> public static uint MakeTag(int fieldNumber, WireType wireType) { return (uint) (fieldNumber << TagTypeBits) | (uint) wireType; }
/// <summary> /// Compares the streams current wire-type to the hinted wire-type, updating the reader if necessary; for example, /// a Variant may be updated to SignedVariant. If the hinted wire-type is unrelated then no change is made. /// </summary> public void Hint(WireType wireType) { if (this.wireType == wireType) { } // fine; everything as we expect else if (((int)wireType & 7) == (int)this.wireType) { // the underling type is a match; we're customising it with an extension this.wireType = wireType; } // note no error here; we're OK about using alternative data }
protected ListDecorator(TypeModel model, Type declaredType, Type concreteType, IProtoSerializer tail, int fieldNumber, bool writePacked, WireType packedWireType, bool returnList, bool overwriteList, bool supportNull) : base(tail) { if (returnList) { this.options |= 8; } if (overwriteList) { this.options |= 16; } if (supportNull) { this.options |= 32; } if ((writePacked || packedWireType != WireType.None) && fieldNumber <= 0) { throw new ArgumentOutOfRangeException("fieldNumber"); } if (!ListDecorator.CanPack(packedWireType)) { if (writePacked) { throw new InvalidOperationException("Only simple data-types can use packed encoding"); } packedWireType = WireType.None; } this.fieldNumber = fieldNumber; if (writePacked) { this.options |= 4; } this.packedWireType = packedWireType; if (declaredType == null) { throw new ArgumentNullException("declaredType"); } if (declaredType.get_IsArray()) { throw new ArgumentException("Cannot treat arrays as lists", "declaredType"); } this.declaredType = declaredType; this.concreteType = concreteType; if (this.RequireAdd) { bool flag; this.add = TypeModel.ResolveListAdd(model, declaredType, tail.ExpectedType, out flag); if (flag) { this.options |= 1; string fullName = declaredType.get_FullName(); if (fullName != null && fullName.StartsWith("System.Data.Linq.EntitySet`1[[")) { this.options |= 2; } } if (this.add == null) { throw new InvalidOperationException("Unable to resolve a suitable Add method for " + declaredType.get_FullName()); } } }
private IProtoSerializer GetNestedSerializer(Type type, out WireType wireType) { MetaType metaType = model.FindWithoutAdd(type); BasicList hierarchy = GetNestedListHierarchy(type); if (hierarchy.Count > 1 && metaType != null && metaType.IgnoreListHandling) { hierarchy = new BasicList(); hierarchy.Add(new NestedItem(type, null, null)); } return GetNestedSerializer(hierarchy, out wireType); }
internal SubItemToken(uint depth, uint value, WireType wireType) { this.depth = depth; this.value = value; this.wireType = wireType; }
internal static IProtoSerializer TryGetCoreSerializer( RuntimeTypeModel model, DataFormat dataFormat, Type type, out WireType defaultWireType, bool asReference, bool dynamicType, bool overwriteList, bool overrideSkipConstructor, bool supportNull) { #if !NO_GENERICS type = Nullable.GetUnderlyingType(type) ?? type; #endif if (Helpers.IsEnum(type)) { if (model != null) { // need to do this before checking the typecode; an int enum will report Int32 etc defaultWireType = WireType.Variant; return new EnumSerializer(type, model.GetEnumMap(type)); } else { // enum is fine for adding as a meta-type defaultWireType = WireType.None; return null; } } ProtoTypeCode code = Helpers.GetTypeCode(type); switch (code) { case ProtoTypeCode.Int32: defaultWireType = GetIntWireType(dataFormat, 32); return new Int32Serializer(); case ProtoTypeCode.UInt32: defaultWireType = GetIntWireType(dataFormat, 32); return new UInt32Serializer(); case ProtoTypeCode.Int64: defaultWireType = GetIntWireType(dataFormat, 64); return new Int64Serializer(); case ProtoTypeCode.UInt64: defaultWireType = GetIntWireType(dataFormat, 64); return new UInt64Serializer(); case ProtoTypeCode.String: defaultWireType = WireType.String; if (asReference) { return new NetObjectSerializer(typeof(string), 0, BclHelpers.NetObjectOptions.AsReference); } return new StringSerializer(); case ProtoTypeCode.Single: defaultWireType = WireType.Fixed32; return new SingleSerializer(); case ProtoTypeCode.Double: defaultWireType = WireType.Fixed64; return new DoubleSerializer(); case ProtoTypeCode.Boolean: defaultWireType = WireType.Variant; return new BooleanSerializer(); case ProtoTypeCode.DateTime: defaultWireType = GetDateTimeWireType(dataFormat); return new DateTimeSerializer(); case ProtoTypeCode.Decimal: defaultWireType = WireType.String; return new DecimalSerializer(); case ProtoTypeCode.Byte: defaultWireType = GetIntWireType(dataFormat, 32); return new ByteSerializer(); case ProtoTypeCode.SByte: defaultWireType = GetIntWireType(dataFormat, 32); return new SByteSerializer(); case ProtoTypeCode.Char: defaultWireType = WireType.Variant; return new CharSerializer(); case ProtoTypeCode.Int16: defaultWireType = GetIntWireType(dataFormat, 32); return new Int16Serializer(); case ProtoTypeCode.UInt16: defaultWireType = GetIntWireType(dataFormat, 32); return new UInt16Serializer(); case ProtoTypeCode.TimeSpan: defaultWireType = GetDateTimeWireType(dataFormat); return new TimeSpanSerializer(); case ProtoTypeCode.Guid: defaultWireType = WireType.String; return new GuidSerializer(); case ProtoTypeCode.Uri: defaultWireType = WireType.String; return new StringSerializer(); // treat as string; wrapped in decorator later case ProtoTypeCode.ByteArray: defaultWireType = WireType.String; return new BlobSerializer(overwriteList); case ProtoTypeCode.Type: defaultWireType = WireType.String; return new SystemTypeSerializer(); } IProtoSerializer parseable = ParseableSerializer.TryCreate(type); if (parseable != null) { defaultWireType = WireType.String; return parseable; } if (model != null) { if (asReference && type.FullName.StartsWith("System.Collections.Generic.KeyValuePair`2[[")) { defaultWireType = WireType.Variant; MemberInfo[] mapping; ConstructorInfo ctor = MetaType.ResolveTupleConstructor(type, out mapping); if (ctor == null) throw new InvalidOperationException(); return new TupleSerializer(model, ctor, mapping, true, false, true, true, supportNull); } int key = model.GetKey(type, false, true); if (asReference || dynamicType) { defaultWireType = WireType.String; BclHelpers.NetObjectOptions options = BclHelpers.NetObjectOptions.None; if (asReference) options |= BclHelpers.NetObjectOptions.AsReference; if (dynamicType) options |= BclHelpers.NetObjectOptions.DynamicType; if (key >= 0) { // exists if (!overrideSkipConstructor && model[type].UseConstructor) options |= BclHelpers.NetObjectOptions.UseConstructor; } else if (!type.IsInterface) { options |= BclHelpers.NetObjectOptions.UseConstructor; } return new NetObjectSerializer(type, key, options); } if (key >= 0) { defaultWireType = dataFormat == DataFormat.Group ? WireType.StartGroup : WireType.String; return new SubItemSerializer(type, key, model[type], true, false); } } defaultWireType = WireType.None; return null; }
private void Stream(ArrayList data, WireType wireType) { data.Add(new Snoop.Data.ClassSeparator(typeof(WireType))); data.Add(new Snoop.Data.Object("Actual value", wireType.Conduit)); data.Add(new Snoop.Data.Object("Is in use", wireType.Insulation)); data.Add(new Snoop.Data.Bool("Is in use", wireType.IsInUse)); data.Add(new Snoop.Data.Object("Max size", wireType.MaxSize)); data.Add(new Snoop.Data.Double("Neutral multiplier", wireType.NeutralMultiplier)); data.Add(new Snoop.Data.Bool("Neutral required", wireType.NeutralRequired)); data.Add(new Snoop.Data.String("Neutral size", wireType.NeutralSize.ToString())); data.Add(new Snoop.Data.Object("Temperature rating", wireType.TemperatureRating)); data.Add(new Snoop.Data.Object("Wire material", wireType.WireMaterial)); }
public static byte[] GetTagBytes(int fieldNumber, WireType wireType) { return GetTagBytes(MakeTag(fieldNumber, wireType)); }
internal MapDecorator(TypeModel model, Type concreteType, IProtoSerializer keyTail, IProtoSerializer valueTail, int fieldNumber, WireType wireType, WireType keyWireType, WireType valueWireType, bool overwriteList) : base(DefaultValue == null ? (IProtoSerializer) new TagDecorator(2, valueWireType, false, valueTail) : (IProtoSerializer) new DefaultValueDecorator(model, DefaultValue, new TagDecorator(2, valueWireType, false, valueTail))) { this.wireType = wireType; this.keyTail = new DefaultValueDecorator(model, DefaultKey, new TagDecorator(1, keyWireType, false, keyTail)); this.fieldNumber = fieldNumber; this.concreteType = concreteType ?? typeof(TDictionary); if (keyTail.RequiresOldValue) { throw new InvalidOperationException("Key tail should not require the old value"); } if (!keyTail.ReturnsValue) { throw new InvalidOperationException("Key tail should return a value"); } if (!valueTail.ReturnsValue) { throw new InvalidOperationException("Value tail should return a value"); } AppendToCollection = !overwriteList; }
internal static void WriteHeaderCore(int fieldNumber, WireType wireType, ProtoWriter writer) { uint value = (uint)(fieldNumber << 3 | (int)(wireType & (WireType)7)); ProtoWriter.WriteUInt32Variant(value, writer); }
public void SkipField() { switch (wireType) { case WireType.Variant: ReadUInt64Varint(); break; case WireType.Fixed16: EnsureBuffer(2); index += 2; length -= 2; break; case WireType.Fixed32: EnsureBuffer(4); index += 4; length -= 4; break; case WireType.Fixed64: EnsureBuffer(8); index += 8; length -= 8; break; case WireType.String: int len = checked ((int)ReadUInt32Variant(false)); EnsureBuffer(len); if (length < len) { throw new EndOfStreamException(); } index += len; length -= len; break; case WireType.Binary: int aryLen = checked ((int)ReadUInt32Variant(false)); EnsureBuffer(aryLen); if (length < aryLen) { throw new EndOfStreamException(); } index += aryLen; length -= aryLen; break; case WireType.StartGroup: depth++; uint originalField = field; while (TryReadField(out _)) { SkipField(); } depth--; if (wireType != WireType.EndGroup || originalField != field) { throw new InvalidOperationException(); } break; } wireType = WireType.None; }
// Token: 0x06000039 RID: 57 RVA: 0x0000A274 File Offset: 0x00008474 private static long ReadTimeSpanTicks(ProtoReader source) { WireType wireType = source.WireType; if (wireType == WireType.Fixed64) { return(source.ReadInt64()); } if (wireType - WireType.String > 1) { throw new ProtoException("Unexpected wire-type: " + source.WireType.ToString()); } SubItemToken token = ProtoReader.StartSubItem(source); TimeSpanScale timeSpanScale = TimeSpanScale.Days; long num = 0L; int num2; while ((num2 = source.ReadFieldHeader()) > 0) { if (num2 != 1) { if (num2 == 2) { timeSpanScale = (TimeSpanScale)source.ReadInt32(); } else { source.SkipField(); } } else { source.Assert(WireType.SignedVariant); num = source.ReadInt64(); } } ProtoReader.EndSubItem(token, source); switch (timeSpanScale) { case TimeSpanScale.Days: return(num * 864000000000L); case TimeSpanScale.Hours: return(num * 36000000000L); case TimeSpanScale.Minutes: return(num * 600000000L); case TimeSpanScale.Seconds: return(num * 10000000L); case TimeSpanScale.Milliseconds: return(num * 10000L); case TimeSpanScale.Ticks: return(num); default: if (timeSpanScale != TimeSpanScale.MinMax) { throw new ProtoException("Unknown timescale: " + timeSpanScale.ToString()); } if (num == -1L) { return(long.MinValue); } if (num == 1L) { return(long.MaxValue); } throw new ProtoException("Unknown min/max value: " + num.ToString()); } }
public byte ReadByte(WireType _wt) { checked { return((byte)ReadUInt32(_wt)); } }
/// <summary> /// Encodes and writes the key. /// </summary> public static void WriteKey(Stream stream, uint fieldNumber, WireType wireType) { WriteUnsignedVarint(stream, ((fieldNumber) << 3) | (uint)wireType); }
// Token: 0x06000035 RID: 53 RVA: 0x0000A028 File Offset: 0x00008228 public static void WriteTimeSpan(TimeSpan timeSpan, ProtoWriter dest) { if (dest == null) { throw new ArgumentNullException("dest"); } WireType wireType = dest.WireType; if (wireType == WireType.Fixed64) { ProtoWriter.WriteInt64(timeSpan.Ticks, dest); return; } if (wireType - WireType.String <= 1) { long num = timeSpan.Ticks; TimeSpanScale timeSpanScale; if (timeSpan == TimeSpan.MaxValue) { num = 1L; timeSpanScale = TimeSpanScale.MinMax; } else if (timeSpan == TimeSpan.MinValue) { num = -1L; timeSpanScale = TimeSpanScale.MinMax; } else if (num % 864000000000L == 0L) { timeSpanScale = TimeSpanScale.Days; num /= 864000000000L; } else if (num % 36000000000L == 0L) { timeSpanScale = TimeSpanScale.Hours; num /= 36000000000L; } else if (num % 600000000L == 0L) { timeSpanScale = TimeSpanScale.Minutes; num /= 600000000L; } else if (num % 10000000L == 0L) { timeSpanScale = TimeSpanScale.Seconds; num /= 10000000L; } else if (num % 10000L == 0L) { timeSpanScale = TimeSpanScale.Milliseconds; num /= 10000L; } else { timeSpanScale = TimeSpanScale.Ticks; } SubItemToken token = ProtoWriter.StartSubItem(null, dest); if (num != 0L) { ProtoWriter.WriteFieldHeader(1, WireType.SignedVariant, dest); ProtoWriter.WriteInt64(num, dest); } if (timeSpanScale != TimeSpanScale.Days) { ProtoWriter.WriteFieldHeader(2, WireType.Variant, dest); ProtoWriter.WriteInt32((int)timeSpanScale, dest); } ProtoWriter.EndSubItem(token, dest); return; } throw new ProtoException("Unexpected wire-type: " + dest.WireType.ToString()); }
internal bool TrySerializeAuxiliaryType(ProtoWriter writer, Type type, DataFormat format, int tag, object value, bool isInsideList) { int num; if (type == null) { type = value.GetType(); } ProtoTypeCode typeCode = Helpers.GetTypeCode(type); WireType wireType = this.GetWireType(typeCode, format, ref type, out num); if (num < 0) { if (wireType != WireType.None) { ProtoWriter.WriteFieldHeader(tag, wireType, writer); } switch (typeCode) { case ProtoTypeCode.Boolean: ProtoWriter.WriteBoolean((bool)value, writer); return(true); case ProtoTypeCode.Char: ProtoWriter.WriteUInt16((char)value, writer); return(true); case ProtoTypeCode.SByte: ProtoWriter.WriteSByte((sbyte)value, writer); return(true); case ProtoTypeCode.Byte: ProtoWriter.WriteByte((byte)value, writer); return(true); case ProtoTypeCode.Int16: ProtoWriter.WriteInt16((short)value, writer); return(true); case ProtoTypeCode.UInt16: ProtoWriter.WriteUInt16((ushort)value, writer); return(true); case ProtoTypeCode.Int32: ProtoWriter.WriteInt32((int)value, writer); return(true); case ProtoTypeCode.UInt32: ProtoWriter.WriteUInt32((uint)value, writer); return(true); case ProtoTypeCode.Int64: ProtoWriter.WriteInt64((long)value, writer); return(true); case ProtoTypeCode.UInt64: ProtoWriter.WriteUInt64((ulong)value, writer); return(true); case ProtoTypeCode.Single: ProtoWriter.WriteSingle((float)value, writer); return(true); case ProtoTypeCode.Double: ProtoWriter.WriteDouble((double)value, writer); return(true); case ProtoTypeCode.Decimal: BclHelpers.WriteDecimal((decimal)value, writer); return(true); case ProtoTypeCode.DateTime: BclHelpers.WriteDateTime((DateTime)value, writer); return(true); case ProtoTypeCode.String: ProtoWriter.WriteString((string)value, writer); return(true); case ProtoTypeCode.TimeSpan: BclHelpers.WriteTimeSpan((TimeSpan)value, writer); return(true); case ProtoTypeCode.ByteArray: ProtoWriter.WriteBytes((byte[])value, writer); return(true); case ProtoTypeCode.Guid: BclHelpers.WriteGuid((Guid)value, writer); return(true); case ProtoTypeCode.Uri: ProtoWriter.WriteString(((Uri)value).AbsoluteUri, writer); return(true); } } else { if (Helpers.IsEnum(type)) { this.Serialize(num, value, writer); return(true); } ProtoWriter.WriteFieldHeader(tag, wireType, writer); switch (wireType) { case WireType.None: throw ProtoWriter.CreateException(writer); case WireType.String: case WireType.StartGroup: { SubItemToken token = ProtoWriter.StartSubItem(value, writer); this.Serialize(num, value, writer); ProtoWriter.EndSubItem(token, writer); return(true); } } this.Serialize(num, value, writer); return(true); } IEnumerable enumerable = value as IEnumerable; if (enumerable == null) { return(false); } if (isInsideList) { throw CreateNestedListsNotSupported(); } foreach (object obj2 in enumerable) { if (obj2 == null) { throw new NullReferenceException(); } if (!this.TrySerializeAuxiliaryType(writer, null, format, tag, obj2, true)) { ThrowUnexpectedType(obj2.GetType()); } } return(true); }
internal static ListDecorator Create(TypeModel model, Type declaredType, Type concreteType, IProtoSerializer tail, int fieldNumber, bool writePacked, WireType packedWireType, bool returnList, bool overwriteList, bool supportNull) { MethodInfo builderFactory; MethodInfo methodInfo; MethodInfo addRange; MethodInfo finish; if (returnList && ImmutableCollectionDecorator.IdentifyImmutable(model, declaredType, out builderFactory, out methodInfo, out addRange, out finish)) { return(new ImmutableCollectionDecorator(model, declaredType, concreteType, tail, fieldNumber, writePacked, packedWireType, returnList, overwriteList, supportNull, builderFactory, methodInfo, addRange, finish)); } return(new ListDecorator(model, declaredType, concreteType, tail, fieldNumber, writePacked, packedWireType, returnList, overwriteList, supportNull)); }
internal bool TryDeserializeAuxiliaryType(ProtoReader reader, DataFormat format, int tag, Type type, ref object value, bool skipOtherFields, bool asListItem, bool autoCreate, bool insideList) { int num; if (type == null) { throw new ArgumentNullException("type"); } Type itemType = null; ProtoTypeCode typeCode = Helpers.GetTypeCode(type); WireType wireType = this.GetWireType(typeCode, format, ref type, out num); bool flag = false; if (wireType == WireType.None) { itemType = GetListItemType(this, type); if (((itemType == null) && type.IsArray) && ((type.GetArrayRank() == 1) && (type != typeof(byte[])))) { itemType = type.GetElementType(); } if (itemType != null) { if (insideList) { throw CreateNestedListsNotSupported(); } flag = this.TryDeserializeList(this, reader, format, tag, type, itemType, ref value); if (!flag && autoCreate) { value = CreateListInstance(type, itemType); } return(flag); } ThrowUnexpectedType(type); } Label_00B7: if (!flag || !asListItem) { int num2 = reader.ReadFieldHeader(); if (num2 > 0) { if (num2 != tag) { if (!skipOtherFields) { throw ProtoReader.AddErrorData(new InvalidOperationException("Expected field " + tag.ToString() + ", but found " + num2.ToString()), reader); } reader.SkipField(); } else { flag = true; reader.Hint(wireType); if (num >= 0) { switch (wireType) { case WireType.String: case WireType.StartGroup: { SubItemToken token = ProtoReader.StartSubItem(reader); value = this.Deserialize(num, value, reader); ProtoReader.EndSubItem(token, reader); goto Label_00B7; } } value = this.Deserialize(num, value, reader); } else { switch (typeCode) { case ProtoTypeCode.Boolean: value = reader.ReadBoolean(); break; case ProtoTypeCode.Char: value = (char)reader.ReadUInt16(); break; case ProtoTypeCode.SByte: value = reader.ReadSByte(); break; case ProtoTypeCode.Byte: value = reader.ReadByte(); break; case ProtoTypeCode.Int16: value = reader.ReadInt16(); break; case ProtoTypeCode.UInt16: value = reader.ReadUInt16(); break; case ProtoTypeCode.Int32: value = reader.ReadInt32(); break; case ProtoTypeCode.UInt32: value = reader.ReadUInt32(); break; case ProtoTypeCode.Int64: value = reader.ReadInt64(); break; case ProtoTypeCode.UInt64: value = reader.ReadUInt64(); break; case ProtoTypeCode.Single: value = reader.ReadSingle(); break; case ProtoTypeCode.Double: value = reader.ReadDouble(); break; case ProtoTypeCode.Decimal: value = BclHelpers.ReadDecimal(reader); break; case ProtoTypeCode.DateTime: value = BclHelpers.ReadDateTime(reader); break; case ProtoTypeCode.String: value = reader.ReadString(); break; case ProtoTypeCode.TimeSpan: value = BclHelpers.ReadTimeSpan(reader); break; case ProtoTypeCode.ByteArray: value = ProtoReader.AppendBytes((byte[])value, reader); break; case ProtoTypeCode.Guid: value = BclHelpers.ReadGuid(reader); break; case ProtoTypeCode.Uri: value = new Uri(reader.ReadString()); break; } } } goto Label_00B7; } } if ((!flag && !asListItem) && (autoCreate && (type != typeof(string)))) { value = Activator.CreateInstance(type); } return(flag); }
public static uint MakeTag(int fieldNumber, WireType wireType) { return((uint)(fieldNumber << TagTypeBits) | (uint)wireType); }
internal static void WriteHeaderCore(int fieldNumber, WireType wireType, ProtoWriter writer) { uint header = (((uint)fieldNumber) << 3) | (((uint)wireType) & 7); WriteUInt32Variant(header, writer); }