Example #1
0
        public object ValueDecoder(byte[] bytes)
        {
            CodedInputStream input = new CodedInputStream(bytes);
            Int64            hour = 0, min = 0, sec = 0, usec = 0;

            bool negative = input.ReadInt32() > 0;

            if (!input.IsAtEnd)
            {
                hour = input.ReadInt64();
            }
            if (!input.IsAtEnd)
            {
                min = input.ReadInt64();
            }
            if (!input.IsAtEnd)
            {
                sec = input.ReadInt64();
            }
            if (!input.IsAtEnd)
            {
                usec = input.ReadInt64();
            }
            if (negative)
            {
                hour *= -1;
            }
            return(new TimeSpan(0, (int)hour, (int)min, (int)sec, (int)usec * 1000));
        }
Example #2
0
        /// <summary>
        /// Read value from <see cref="System.Protobuf.Object"/>
        /// </summary>
        /// <param name="obj"><see cref="System.Protobuf.Object"/> to read from</param>
        /// <returns>Value in the correct type - null if not capable of converting</returns>
        public static object ToCLR(this System.Protobuf.Object obj)
        {
            var    type  = (Types)obj.Type;
            object value = null;

            using (var stream = new CodedInputStream(obj.Content.ToByteArray()))
            {
                switch (type)
                {
                case Types.String: value = stream.ReadString(); break;

                case Types.Int32: value = stream.ReadInt32(); break;

                case Types.Int64: value = stream.ReadInt64(); break;

                case Types.UInt32: value = stream.ReadUInt32(); break;

                case Types.UInt64: value = stream.ReadUInt64(); break;

                case Types.Float: value = stream.ReadFloat(); break;

                case Types.Double: value = stream.ReadDouble(); break;

                case Types.Boolean: value = stream.ReadBool(); break;

                case Types.DateTime: value = stream.ReadInt64().ToDateTime(); break;

                case Types.DateTimeOffset: value = stream.ReadInt64().ToDateTimeOffset(); break;

                case Types.Guid: value = new Guid(stream.ReadBytes().ToByteArray()); break;
                }
            }
            return(value);
        }
Example #3
0
        public object ValueDecoder(byte[] bytes)
        {
            CodedInputStream input = new CodedInputStream(bytes);
            UInt64           year = 0, month = 0, day = 0;
            Int64            hour = 0, min = 0, sec = 0, usec = 0;

            year  = input.ReadUInt64();
            month = input.ReadUInt64();
            day   = input.ReadUInt64();
            if (!input.IsAtEnd)
            {
                hour = input.ReadInt64();
            }
            if (!input.IsAtEnd)
            {
                min = input.ReadInt64();
            }
            if (!input.IsAtEnd)
            {
                sec = input.ReadInt64();
            }
            if (!input.IsAtEnd)
            {
                usec = input.ReadInt64();
            }
            return(new DateTime((int)year, (int)month, (int)day, (int)hour, (int)min, (int)sec).AddTicks(usec * 10));
        }
Example #4
0
        private static ValueType HandleValueType(CodedInputStream cis)
        {
            var valueType = new ValueType();

            long pos = cis.ReadLength();

            pos += cis.Position;
            while (pos - cis.Position > 0)
            {
                var tag = cis.ReadTag();

                if (tag > 0)
                {
                    var fieldNumber = WireFormat.GetTagFieldNumber(tag);

                    switch (fieldNumber)
                    {
                    case 1:
                        valueType.Type = cis.ReadInt64();
                        break;

                    case 2:
                        valueType.Unit = cis.ReadInt64();
                        break;

                    default:
                        cis.SkipLastField();
                        break;
                    }
                }
            }

            return(valueType);
        }
        object ReadValue(CodedInputStream inputStream, object value, Type type, Type targetType, IValueConverter converter)
        {
            if (type == typeof(Guid))
            {
                _ = inputStream.ReadLength();
                var guidAsBytes = inputStream.ReadBytes();
                value = new Guid(guidAsBytes.ToByteArray());
            }
            else if (type == typeof(string))
            {
                _     = inputStream.ReadLength();
                value = inputStream.ReadString();
            }
            else if (type == typeof(int))
            {
                value = inputStream.ReadInt32();
            }
            else if (type == typeof(long))
            {
                value = inputStream.ReadInt64();
            }
            else if (type == typeof(uint))
            {
                value = inputStream.ReadUInt32();
            }
            else if (type == typeof(ulong))
            {
                value = inputStream.ReadUInt64();
            }
            else if (type == typeof(float))
            {
                value = inputStream.ReadFloat();
            }
            else if (type == typeof(double))
            {
                value = inputStream.ReadDouble();
            }
            else if (type == typeof(bool))
            {
                value = inputStream.ReadBool();
            }
            else if (type == typeof(DateTimeOffset) || type == typeof(DateTime))
            {
                value = DateTimeOffset.FromUnixTimeMilliseconds(inputStream.ReadInt64());
                if (type == typeof(DateTime))
                {
                    value = ((DateTimeOffset)value).UtcDateTime;
                }
            }

            if (converter != null)
            {
                value = converter.ConvertFrom(targetType, value);
            }
            return(value);
        }
Example #6
0
        public static long ReadInt64(this CodedInputStream s)
        {
            long val = 0;

            s.ReadInt64(ref val);
            return(val);
        }
        void Read(CodedInputStream stream)
        {
            while (!stream.IsAtEnd)
            {
                var tag = stream.ReadTag();
                switch (WireFormat.GetTagFieldNumber(tag))
                {
                case 1:
                    using (var ms = new MemoryStream(stream.ReadSomeBytes(stream.ReadLength())))
                    {
                        Hash = new MultiHash(ms).ToBase58();
                    }
                    break;

                case 2:
                    Name = stream.ReadString();
                    break;

                case 3:
                    Size = stream.ReadInt64();
                    break;

                default:
                    throw new InvalidDataException("Unknown field number");
                }
            }
        }
Example #8
0
        private static Label HandleLabel(CodedInputStream cis)
        {
            var label = new Label();

            long pos = cis.ReadLength();

            pos += cis.Position;
            while (pos - cis.Position > 0)
            {
                var tag = cis.ReadTag();
                if (tag > 0)
                {
                    var fieldNumber = WireFormat.GetTagFieldNumber(tag);

                    switch (fieldNumber)
                    {
                    case 1:
                        label.Key = cis.ReadInt64();
                        break;

                    case 2:
                        label.Str = cis.ReadInt64();
                        break;

                    case 3:
                        label.Num = cis.ReadInt64();
                        break;

                    case 4:
                        label.NumUnit = cis.ReadInt64();
                        break;

                    default:
                        cis.SkipLastField();
                        break;
                    }
                }
                else
                {
                    break;
                }
            }

            return(label);
        }
Example #9
0
        public static long[] BytesToProteinIds(byte[] proteinIdBytes)
        {
            var longs            = new List <long>();
            var codedInputStream = new CodedInputStream(proteinIdBytes);

            while (!codedInputStream.IsAtEnd)
            {
                longs.Add(codedInputStream.ReadInt64());
            }
            return(longs.ToArray());
        }
Example #10
0
        public long ParseRawVarint64(int encodedSize)
        {
            CodedInputStream cis = new CodedInputStream(varintInputBuffers[encodedSize]);
            long             sum = 0;

            for (int i = 0; i < BytesToParse / encodedSize; i++)
            {
                sum += cis.ReadInt64();
            }
            return(sum);
        }
Example #11
0
 /// <summary>
 ///   Reads the binary representation of the specified <see cref="CodedInputStream"/>.
 /// </summary>
 /// <param name="stream">
 ///   The <see cref="CodedInputStream"/> to read from.
 /// </param>
 /// <remarks>
 ///   The binary representation is a sequence of <see cref="NetworkProtocol">network protocols</see>.
 /// </remarks>
 void Read(CodedInputStream stream)
 {
     Protocols.Clear();
     do
     {
         uint code = (uint)stream.ReadInt64();
         if (!NetworkProtocol.Codes.TryGetValue(code, out Type protocolType))
             throw new InvalidDataException(string.Format("The IPFS network protocol code '{0}' is unknown.", code));
         var p = (NetworkProtocol)Activator.CreateInstance(protocolType);
         p.ReadValue(stream);
         Protocols.Add(p);
     } while (!stream.IsAtEnd);
 }
Example #12
0
    public bool ReadInt64(out string value)
    {
        try
        {
            var number = _stream.ReadInt64();
            value = number.ToString();
        }
        catch (Exception)
        {
            value = default(string);
            return(false);
        }

        return(true);
    }
Example #13
0
    public Dictionary <Type, object> ReadParam()
    {
        Dictionary <Type, object> pairs = new Dictionary <Type, object>();

        foreach (var item in Params)
        {
            object o = null;
            Type   t = Type.GetType(item.Name);

            if (t != null)
            {
                CodedInputStream cis = new CodedInputStream(item.Data.ToByteArray());
                if (t == typeof(int))
                {
                    o = cis.ReadInt32();
                }
                else if (t == typeof(long))
                {
                    o = cis.ReadInt64();
                }
                else if (t == typeof(float))
                {
                    o = cis.ReadFloat();
                }
                else if (t == typeof(double))
                {
                    o = cis.ReadDouble();
                }
                else if (t == typeof(bool))
                {
                    o = cis.ReadBool();
                }
                else if (t == typeof(string))
                {
                    o = cis.ReadString();
                }
                else if (typeof(IMessage).IsAssignableFrom(t))
                {
                    o = Activator.CreateInstance(t);
                    cis.ReadMessage((IMessage)o);
                }

                pairs.Add(t, o);
            }
        }

        return(pairs);
    }
Example #14
0
        /// <summary>
        ///   Reads the binary representation of the specified <see cref="Google.Protobuf.CodedInputStream"/>.
        /// </summary>
        /// <param name="stream">
        ///   The <see cref="Google.Protobuf.CodedInputStream"/> to read from.
        /// </param>
        /// <remarks>
        ///   The binary representation is a sequence of <see cref="NetworkProtocol">network protocols</see>.
        /// </remarks>
        private void Read(CodedInputStream stream)
        {
            Protocols.Clear();
            do
            {
                var code = (uint)stream.ReadInt64();
                if (!NetworkProtocol.Codes.TryGetValue(code, out var protocolType))
                {
                    throw new InvalidDataException($"The IPFS network protocol code '{code}' is unknown.");
                }

                var p = (NetworkProtocol)Activator.CreateInstance(protocolType);
                p.ReadValue(stream);
                Protocols.Add(p);
            } while (!stream.IsAtEnd);
        }
Example #15
0
        /// <summary>
        /// Convert a Protocol Buffer value type, encoded as a byte string, to a C# value.
        /// </summary>
        public static object ReadValue(ByteString value, Type type)
        {
            if (value.Length == 0)
            {
                throw new ArgumentException("Value is empty");
            }
            var stream = new CodedInputStream(value.ToByteArray());

            if (type == typeof(double))
            {
                return(stream.ReadDouble());
            }
            else if (type == typeof(float))
            {
                return(stream.ReadFloat());
            }
            else if (type == typeof(int))
            {
                return(stream.ReadInt32());
            }
            else if (type == typeof(long))
            {
                return(stream.ReadInt64());
            }
            else if (type == typeof(uint))
            {
                return(stream.ReadUInt32());
            }
            else if (type == typeof(ulong))
            {
                return(stream.ReadUInt64());
            }
            else if (type == typeof(bool))
            {
                return(stream.ReadBool());
            }
            else if (type == typeof(string))
            {
                return(stream.ReadString());
            }
            else if (type == typeof(byte[]))
            {
                return(stream.ReadBytes().ToByteArray());
            }
            throw new ArgumentException(type + " is not a Protocol Buffer value type");
        }
Example #16
0
        void HandlePacket(CodedInputStream reader)
        {
            var service_id = reader.ReadRawByte();
            var method_id  = reader.ReadInt32() - 1;
            var request_id = reader.ReadFixedUInt16();

            Debug.WriteLine("Received packet [service_id: 0x{0:X2}, method_id: {1}, request_id: {2}]", service_id, method_id, request_id);
            // Handle RPC responses
            if (service_id == RESPONSE_SERVICE_ID)
            {
                Debug.WriteLine("  received response");
                HandleResponse(request_id, reader);
            }
            else
            {
                var listener_id = reader.ReadInt64();
                Debug.WriteLine("  listener_id: {0}", listener_id);

                IService service;
                if (!exportedServices.TryGetValue(service_id, out service))
                {
                    throw new ArgumentException("No service bound on index " + service_id);
                }

                // Load correct descriptor for the requested method
                var method_descriptor = service.DescriptorForType.Methods[method_id];
                // Create a prototype of the request message
                var message_prototype = service.GetRequestPrototype(method_descriptor);
                // And create a builder for that message
                var builder = message_prototype.WeakCreateBuilderForType();
                // Read the message into the correct builder
                var message = ReadMessage(reader, builder);

                Debug.WriteLine("  passing RPC to {0}::{1}", method_descriptor.Service.Name, method_descriptor.Name);
                Debug.WriteLine(message.ToString());

                // Response callback sends the repsponse
                service.CallMethod(method_descriptor, null, message, m => SendResponse(request_id, m));
            }
        }
Example #17
0
        private static Line HandleLine(CodedInputStream cis)
        {
            var line = new Line();

            long pos = cis.ReadLength();

            pos += cis.Position;
            while (pos - cis.Position > 0)
            {
                var tag = cis.ReadTag();
                if (tag > 0)
                {
                    var fieldNumber = WireFormat.GetTagFieldNumber(tag);

                    switch (fieldNumber)
                    {
                    case 1:
                        line.FunctionId = cis.ReadUInt64();
                        break;

                    case 2:
                        line.LineNumber = cis.ReadInt64();
                        break;

                    default:
                        cis.SkipLastField();
                        break;
                    }
                }
                else
                {
                    break;
                }
            }

            return(line);
        }
        void Read(CodedInputStream stream)
        {
            while (!stream.IsAtEnd)
            {
                var tag = stream.ReadTag();
                switch (WireFormat.GetTagFieldNumber(tag))
                {
                case 1:
                    Id = Cid.Read(stream);
                    break;

                case 2:
                    Name = stream.ReadString();
                    break;

                case 3:
                    Size = stream.ReadInt64();
                    break;

                default:
                    throw new InvalidDataException("Unknown field number");
                }
            }
        }
Example #19
0
        private static Mapping HandleMapping(CodedInputStream cis)
        {
            var mapping = new Mapping();

            long pos = cis.ReadLength();

            pos += cis.Position;
            while (pos - cis.Position > 0)
            {
                var tag = cis.ReadTag();
                if (tag > 0)
                {
                    var fieldNumber = WireFormat.GetTagFieldNumber(tag);

                    switch (fieldNumber)
                    {
                    case 1:
                        mapping.Id = cis.ReadUInt64();
                        break;

                    case 2:
                        mapping.MemoryStart = cis.ReadUInt64();
                        break;

                    case 3:
                        mapping.MemoryLimit = cis.ReadUInt64();
                        break;

                    case 4:
                        mapping.FileOffset = cis.ReadUInt64();
                        break;

                    case 5:
                        mapping.FileNameIndex = cis.ReadInt64();
                        break;

                    case 6:
                        mapping.BuildIdIndex = cis.ReadInt64();
                        break;

                    case 7:
                        mapping.HasFunctions = cis.ReadInt32() != 0;
                        break;

                    case 8:
                        mapping.HasFilenames = cis.ReadInt32() != 0;
                        break;

                    case 9:
                        mapping.HasLineNumbers = cis.ReadInt32() != 0;
                        break;

                    case 10:
                        mapping.HasInlineFrames = cis.ReadInt32() != 0;
                        break;

                    default:
                        cis.SkipLastField();
                        break;
                    }
                }
                else
                {
                    break;
                }
            }

            return(mapping);
        }
Example #20
0
        private static Sample HandleSample(CodedInputStream cis)
        {
            var sample = new Sample();
            var lables = new List <Label>();

            sample.Labels = lables;

            var locationIds = new List <ulong>();

            sample.LocationIds = locationIds;

            var values = new List <long>();

            sample.Values = values;

            long pos = cis.ReadLength();

            pos += cis.Position;
            while (pos - cis.Position > 0)
            {
                var tag = cis.ReadTag();
                if (tag > 0)
                {
                    var fieldNumber = WireFormat.GetTagFieldNumber(tag);

                    switch (fieldNumber)
                    {
                    case 1:
                    {
                        long posLocations = cis.ReadLength();
                        posLocations += cis.Position;
                        while (posLocations - cis.Position > 0)
                        {
                            locationIds.Add(cis.ReadUInt64());
                        }

                        break;
                    }

                    case 2:
                    {
                        long posValues = cis.ReadLength();
                        posValues += cis.Position;
                        while (posValues - cis.Position > 0)
                        {
                            values.Add(cis.ReadInt64());
                        }

                        break;
                    }

                    case 3:
                        lables.Add(HandleLabel(cis));
                        break;

                    default:
                        cis.SkipLastField();
                        break;
                    }
                }
                else
                {
                    break;
                }
            }

            return(sample);
        }
Example #21
0
        /// <summary>
        /// Decode a value of the given type.
        /// Should not be called directly. This interface is used by service client stubs.
        /// </summary>
        public static object Decode(ByteString value, Type type, Connection client)
        {
            var stream = new CodedInputStream(value.ToByteArray());

            if (type == typeof(double))
            {
                return(stream.ReadDouble());
            }
            else if (type == typeof(float))
            {
                return(stream.ReadFloat());
            }
            else if (type == typeof(int))
            {
                return(stream.ReadInt32());
            }
            else if (type == typeof(long))
            {
                return(stream.ReadInt64());
            }
            else if (type == typeof(uint))
            {
                return(stream.ReadUInt32());
            }
            else if (type == typeof(ulong))
            {
                return(stream.ReadUInt64());
            }
            else if (type == typeof(bool))
            {
                return(stream.ReadBool());
            }
            else if (type == typeof(string))
            {
                return(stream.ReadString());
            }
            else if (type == typeof(byte[]))
            {
                return(stream.ReadBytes().ToByteArray());
            }
            else if (type.IsEnum)
            {
                return(stream.ReadInt32());
            }
            else if (typeof(RemoteObject).IsAssignableFrom(type))
            {
                if (client == null)
                {
                    throw new ArgumentException("Client not passed when decoding remote object");
                }
                var id = stream.ReadUInt64();
                if (id == 0)
                {
                    return(null);
                }
                return((RemoteObject)Activator.CreateInstance(type, client, id));
            }
            else if (typeof(IMessage).IsAssignableFrom(type))
            {
                IMessage message = (IMessage)Activator.CreateInstance(type);
                message.MergeFrom(stream);
                return(message);
            }
            else if (type.IsGenericType && type.GetGenericTypeDefinition() == typeof(IList <>))
            {
                return(DecodeList(value, type, client));
            }
            else if (type.IsGenericType && type.GetGenericTypeDefinition() == typeof(IDictionary <,>))
            {
                return(DecodeDictionary(value, type, client));
            }
            else if (type.IsGenericType && type.GetGenericTypeDefinition() == typeof(ISet <>))
            {
                return(DecodeSet(value, type, client));
            }
            else if (type.IsGenericType &&
                     (type.GetGenericTypeDefinition() == typeof(Tuple <>) ||
                      type.GetGenericTypeDefinition() == typeof(Tuple <,>) ||
                      type.GetGenericTypeDefinition() == typeof(Tuple <, ,>) ||
                      type.GetGenericTypeDefinition() == typeof(Tuple <, , ,>) ||
                      type.GetGenericTypeDefinition() == typeof(Tuple <, , , ,>) ||
                      type.GetGenericTypeDefinition() == typeof(Tuple <, , , , ,>)))
            {
                return(DecodeTuple(value, type, client)); // TODO: ugly handing of tuple types
            }
            throw new ArgumentException(type + " is not a serializable type");
        }
Example #22
0
 internal BlockHandle(CodedInputStream pb)
     : this(pb.ReadInt64(), pb.ReadInt64())
 {
 }
Example #23
0
 public override long Read(CodedInputStream stream)
 {
     return(stream.ReadInt64());
 }