static BEncodedDictionary Serialize(object builder)
        {
            var dict  = new BEncodedDictionary();
            var props = builder.GetType().GetProperties();

            foreach (var property in props)
            {
                BEncodedValue?convertedValue = property.GetValue(builder) switch {
                    bool value => convertedValue = new BEncodedString(value.ToString()),
                    IList <EncryptionType> value => convertedValue = new BEncodedList(value.Select(v => (BEncodedString)v.ToString())),
                    string value => new BEncodedString(value),
                    TimeSpan value => new BEncodedNumber(value.Ticks),
                    IPAddress value => new BEncodedString(value.ToString()),
                    IPEndPoint value => new BEncodedList {
                        (BEncodedString)value.Address.ToString(), (BEncodedNumber)value.Port
                    },
                    int value => new BEncodedNumber(value),
                    FastResumeMode value => new BEncodedString(value.ToString()),
                    null => null,
                    _ => throw new NotSupportedException($"{property.Name} => type: ${property.PropertyType}"),
                };
                // Ensure default values aren't accidentally propagated.
                if (property.PropertyType == typeof(IPEndPoint) && convertedValue == null)
                {
                    convertedValue = new BEncodedList();
                }
                if (convertedValue != null)
                {
                    dict[property.Name] = convertedValue;
                }
            }

            return(dict);
        }
Esempio n. 2
0
        static byte[] Serialize(object builder)
        {
            var dict  = new BEncodedDictionary();
            var props = builder.GetType().GetProperties();

            foreach (var property in props)
            {
                BEncodedValue convertedValue = property.GetValue(builder) switch {
                    bool value => convertedValue = new BEncodedString(value.ToString()),
                    IList <EncryptionType> value => convertedValue = new BEncodedList(value.Select(v => (BEncodedString)v.ToString())),
                    string value => new BEncodedString(value),
                    TimeSpan value => new BEncodedNumber(value.Ticks),
                    IPAddress value => new BEncodedString(value.ToString()),
                    int value => new BEncodedNumber(value),
                    FastResumeMode value => new BEncodedString(value.ToString()),
                    null => null,
                    { } => throw new NotSupportedException($"{property.Name} => type: ${property.PropertyType}"),