예제 #1
0
 /// <summary>
 /// Initiliazes new instance of <see cref="T:NCoreUtils.Collections.ReadOnlyMappingList{TSource,TTarget}" />
 /// from specified source and mapping.
 /// </summary>
 /// <param name="source">Source read only list.</param>
 /// <param name="mapping">Mapping to apply when retrieving elements.</param>
 public ReadOnlyMappingList(IReadOnlyList <TSource> source, Func <TSource, TTarget> mapping)
 {
     RuntimeAssert.ArgumentNotNull(source, nameof(source));
     RuntimeAssert.ArgumentNotNull(mapping, nameof(mapping));
     _source  = source;
     _mapping = mapping;
 }
예제 #2
0
        /// <summary>
        /// Returns accessor selector for the specified type.
        /// </summary>
        /// <remarks>
        /// Accessor selector retrieved using following scheme:
        /// <list type="number">
        /// <item>
        /// <description>
        /// If <see cref="T:NCoreUtils.Serialization.Meta.AccessorSelectorAttriute" /> is defined for the type, then
        /// accessor selector factory defined by this attribute is used.
        /// </description>
        /// </item>
        /// <item>
        /// <description>
        /// If service provider contains implementation for <see cref="T:NCoreUtils.Serialization.IAccessorSelector{T}" />
        /// specialization for <paramref name="type" />, then this implementation is used.
        /// </description>
        /// </item>
        /// <item>
        /// <description>
        /// If service provider contains implementation for <see cref="T:NCoreUtils.Serialization.IAccessorSelectorFactory{T}" />
        /// specialization for <paramref name="type" />, then this implementation is to create accessor selector.
        /// </description>
        /// </item>
        /// <item>
        /// <description>Default accessor selector is used.</description>
        /// </item>
        /// </list>
        /// </remarks>
        /// <param name="type">Target type.</param>
        /// <param name="serviceProvider">Service provider to use.</param>
        /// <returns>Accessor selector for the specified type.</returns>
        protected virtual IAccessorSelector GetAccessorSelectorFor(Type type, IServiceProvider serviceProvider)
        {
            RuntimeAssert.ArgumentNotNull(type, nameof(type));
            IAccessorSelector accessorSelector;

            if (type.TryGetAttribute <AccessorSelectorAttribute>(out var attr))
            {
                var factory = (IAccessorSelectorFactory)ActivatorUtilities.CreateInstance(serviceProvider, attr.SelectorFactoryType);
                accessorSelector = factory.Create(serviceProvider);
            }
            else if (serviceProvider.TryGetService(typeof(IAccessorSelector <>).MakeGenericType(type), out var boxedSelector))
            {
                accessorSelector = (IAccessorSelector)boxedSelector;
            }
            else if (serviceProvider.TryGetService(typeof(IAccessorSelectorFactory <>).MakeGenericType(type), out var boxedFactory))
            {
                var factory = (IAccessorSelectorFactory)boxedFactory;
                accessorSelector = factory.Create(serviceProvider);
            }
            else
            {
                accessorSelector = _defaultAccessorSelector;
            }
            if (accessorSelector is DerivedAccessorSelector derived)
            {
                derived.BaseAccessorSelector = _defaultAccessorSelector;
                return(derived);
            }
            return(accessorSelector);
        }
예제 #3
0
 /// <summary>
 /// Initializes new instance of type serializer.
 /// </summary>
 /// <param name="factory">Type serializer factory this instance was created by</param>
 /// <param name="targetType">Target type handled by the actual instance.</param>
 protected TypeSerializer(ITypeSerializerFactory factory, Type targetType)
 {
     RuntimeAssert.ArgumentNotNull(factory, nameof(factory));
     RuntimeAssert.ArgumentNotNull(targetType, nameof(targetType));
     Factory    = factory;
     TargetType = targetType;
 }
예제 #4
0
 void Resize(int newSize, bool forceNewHashCodes)
 {
     RuntimeAssert.GreaterOrEquals(newSize, _entries.Length, nameof(newSize));
     int[] newBuckets = new int[newSize];
     for (int i = 0; i < newBuckets.Length; i++)
     {
         newBuckets[i] = -1;
     }
     Entry[] newEntries = new Entry[newSize];
     Array.Copy(_entries, 0, newEntries, 0, _count);
     if (forceNewHashCodes)
     {
         for (int i = 0; i < _count; i++)
         {
             if (newEntries[i].HashCode != -1)
             {
                 newEntries[i].HashCode = GetKeyHasCode(newEntries[i].Key);
             }
         }
     }
     for (int i = 0; i < _count; i++)
     {
         if (newEntries[i].HashCode >= 0)
         {
             int bucket = newEntries[i].HashCode % newSize;
             newEntries[i].Next = newBuckets[bucket];
             newBuckets[bucket] = i;
         }
     }
     _buckets = newBuckets;
     _entries = newEntries;
 }
 /// <summary>
 /// Initializes composite metadata using "empty" service provider.
 /// </summary>
 /// <typeparam name="TBuilder">Builder type.</typeparam>
 /// <typeparam name="TMetadata">Composed metadata type.</typeparam>
 /// <param name="builder">Target builder.</param>
 /// <returns>Initialized composite metadata.</returns>
 public static TMetadata Initialize <TMetadata, TBuilder>(this TBuilder builder)
     where TMetadata : ICompositeMetadata
     where TBuilder : ICompositeMetdataBuilder <TMetadata>
 {
     RuntimeAssert.ArgumentNotNull(builder, nameof(builder));
     return(builder.Initialize(EmptyServiceProvider.SharedInstance));
 }
 public Matcher(Func <TMetadata, TResult> onValue, Func <Func <IServiceProvider, ICompositeMetadata, TMetadata>, TResult> onFactory)
 {
     RuntimeAssert.ArgumentNotNull(onValue, nameof(onValue));
     RuntimeAssert.ArgumentNotNull(onFactory, nameof(onFactory));
     _onValue   = onValue;
     _onFactory = onFactory;
 }
예제 #7
0
            /// <summary>
            /// Initializes new instance of <see cref="T:NCoreUtils.Reflection.MemberAccessor+PropertyAccessor" /> during
            /// deserialization.
            /// </summary>
            /// <param name="info">
            /// The <c>SerializationInfo</c> that holds the serialized object data about the exception being thrown.
            /// </param>
            /// <param name="context">
            /// The <c>StreamingContext</c> that contains contextual information about the source or destination.
            /// </param>
            protected PropertyAccessor(SerializationInfo info, StreamingContext context)
            {
                var type = Type.GetType(info.GetString(KeyType), true);
                var prop = type.GetProperty(info.GetString(KeyMember));

                RuntimeAssert.ArgumentNotNull(prop, "propertyInfo");
                PropertyInfo = prop;
            }
예제 #8
0
 /// <summary>
 /// Substitutes parameter node in the source expression with respect to the specified arguments.
 /// </summary>
 /// <param name="source">Source expression.</param>
 /// <param name="parameter">Parameter node to substitute.</param>
 /// <param name="substitution">Expression to perform substitution with.</param>
 /// <returns>Resulting expression.</returns>
 public static Expression SubstituteParameter(this Expression source, ParameterExpression parameter, Expression substitution)
 {
     RuntimeAssert.ArgumentNotNull(parameter, nameof(parameter));
     RuntimeAssert.ArgumentNotNull(substitution, nameof(substitution));
     return(source.SubstituteParameters(ImmutableDictionary.CreateRange(new KeyValuePair <ParameterExpression, Expression>[] {
         new KeyValuePair <ParameterExpression, Expression>(parameter, substitution)
     })));
 }
예제 #9
0
 public static void Fill <T>(this T[] array, T value = default(T))
 {
     RuntimeAssert.ArgumentNotNull(array, nameof(array));
     for (int i = 0; i < array.Length; ++i)
     {
         array[i] = value;
     }
 }
예제 #10
0
        /// <summary>
        /// Assignes the specified value to the specified key.
        /// </summary>
        /// <param name="key">Key.</param>
        /// <param name="value">Value.</param>
        public void Add(TKey key, TValue value)
        {
            RuntimeAssert.ArgumentNotNull(key, nameof(key));
            EnsureInitialized();
            var hashCode     = GetKeyHasCode(key);
            var targetBucket = hashCode % _buckets.Length;

            Insert(key, value, hashCode, targetBucket);
        }
예제 #11
0
 public Task <BlackjackSession> LoadSessionAsync(
     ulong userId,
     ulong channelId)
 {
     return(repository.GetAsync(channelId, userId)
            .AndThen(session => RuntimeAssert.NotNull(
                         session, new BlackjackSessionNullException()))
            .Map(session => new BlackjackSession(session)));
 }
예제 #12
0
 /// <summary>
 /// Initializes a new instance of the <see cref="T:NFS.Collections.MultiDictionary`2"/> class.
 /// </summary>
 /// <param name="capacity">Capacity.</param>
 /// <param name="keyEqualityComparer">Key equality comparer.</param>
 /// <param name="valueEqualityComparer">Value equality comparer.</param>
 public MultiDictionary(int capacity = 0, IEqualityComparer <TKey> keyEqualityComparer = null, IEqualityComparer <TValue> valueEqualityComparer = null)
 {
     RuntimeAssert.ArgumentInRange(capacity, 0, int.MaxValue, nameof(capacity));
     if (capacity > 0)
     {
         Initialize(capacity);
     }
     _keyComparer   = keyEqualityComparer ?? EqualityComparer <TKey> .Default;
     _valueComparer = valueEqualityComparer ?? EqualityComparer <TValue> .Default;
 }
 /// <summary>
 /// Implements null-safe way to retrieve default value from the accessor, if any.
 /// </summary>
 /// <param name="accessor">The accessor to use.</param>
 /// <param name="value">Variable to store default value if present.</param>
 /// <returns>
 /// <c>true</c> if the accessor has default value and it has been stored in the specified variable, <c>false</c>
 /// otherwise.
 /// </returns>
 public static bool TryGetDefaultValue(this IAccessor accessor, out object value)
 {
     RuntimeAssert.ArgumentNotNull(accessor, nameof(accessor));
     if (accessor.HasDefaultValue)
     {
         value = accessor.DefaultValue;
         return(true);
     }
     value = default(object);
     return(false);
 }
예제 #14
0
 /// <summary>
 /// Returns typed partial data if present.
 /// </summary>
 /// <param name="dataSource">Composite metadata source.</param>
 /// <param name="data">Variable to return metadata.</param>
 /// <returns>
 /// <c>true</c> if metadata of the specified type was present, <c>false</c> otherwise.
 /// </returns>
 public static bool TryGetMetadata <TMetadata>(this ICompositeMetadata dataSource, out TMetadata data) where TMetadata : IMetadata
 {
     RuntimeAssert.ArgumentNotNull(dataSource, nameof(dataSource));
     if (dataSource.TryGetMetadata(typeof(TMetadata), out var obj))
     {
         data = (TMetadata)obj;
         return(true);
     }
     data = default(TMetadata);
     return(false);
 }
예제 #15
0
        public static T[] InitArray <T>(int size, Func <int, T> generator)
        {
            RuntimeAssert.ArgumentNotNull(generator, nameof(generator));
            var result = new T[size];

            for (var i = 0; i < result.Length; ++i)
            {
                result[i] = generator(i);
            }
            return(result);
        }
예제 #16
0
        public static T[] Slice <T>(this T[] array, int offset, int count = -1)
        {
            RuntimeAssert.ArgumentNotNull(array, nameof(array));
            if (-1 == count)
            {
                count = array.Length - offset;
            }
            var result = new T[count];

            Array.Copy(array, offset, result, 0, count);
            return(result);
        }
예제 #17
0
        /// <summary>
        /// Assignes the specified values to the specified key.
        /// </summary>
        /// <param name="key">Key.</param>
        /// <param name="values">Values to assign.</param>
        public void Add(TKey key, IEnumerable <TValue> values)
        {
            RuntimeAssert.ArgumentNotNull(key, nameof(key));
            EnsureInitialized();
            var hashCode     = GetKeyHasCode(key);
            var targetBucket = hashCode % _buckets.Length;

            foreach (var value in values)
            {
                targetBucket = Insert(key, value, hashCode, targetBucket);
            }
        }
 /// <summary>
 /// Return an instance to the pool.
 /// </summary>
 /// <param name="item">Item to return.</param>
 public override void Return(T item)
 {
     if (Pool.Count >= MaxItemsPreserved)
     {
         RuntimeAssert.ArgumentNotNull(item, nameof(item));
         Dispose(item);
     }
     else
     {
         base.ReturnNoCheck(item);
     }
 }
예제 #19
0
        public static T Pop <T>(this List <T> list)
        {
            RuntimeAssert.ArgumentNotNull(list, nameof(list));
            if (0 == list.Count)
            {
                throw new InvalidOperationException("List is empty.");
            }
            var index  = list.Count - 1;
            var result = list[index];

            list.RemoveAt(index);
            return(result);
        }
        /// <summary>
        /// Initializes new instance of <see cref="T:NCoreUtils.Linq.ParameterSubstitution" /> with the specified
        /// substitution rules.
        /// </summary>
        /// <param name="substitutions"></param>
        public ParameterSubstitution(IEnumerable <KeyValuePair <ParameterExpression, Expression> > substitutions)
        {
            RuntimeAssert.ArgumentNotNull(substitutions, nameof(substitutions));
            switch (substitutions)
            {
            case ImmutableDictionary <ParameterExpression, Expression> dict:
                Substitutions = dict;
                break;

            default:
                Substitutions = substitutions.ToImmutableDictionary();
                break;
            }
        }
예제 #21
0
        bool Contains(TKey key, Func <int, bool> predicate)
        {
            RuntimeAssert.ArgumentNotNull(key, nameof(key));
            var found = false;

            if (null != _buckets)
            {
                var hashCode = GetKeyHasCode(key);
                for (int i = _buckets[hashCode % _buckets.Length]; !found && i >= 0; i = _entries[i].Next)
                {
                    found = _entries[i].HashCode == hashCode && predicate(i);
                }
            }
            return(found);
        }
예제 #22
0
 int FindEntry(TKey key)
 {
     RuntimeAssert.ArgumentNotNull(key, nameof(key));
     if (null != _buckets)
     {
         var hashCode = GetKeyHasCode(key);
         for (int i = _buckets[hashCode % _buckets.Length]; i >= 0; i = _entries[i].Next)
         {
             if (_entries[i].HashCode == hashCode && _keyComparer.Equals(_entries[i].Key, key))
             {
                 return(i);
             }
         }
     }
     return(-1);
 }
예제 #23
0
 /// <summary>
 /// Copies all assignments to the specified array at the specified index.
 /// </summary>
 /// <param name="array">Array.</param>
 /// <param name="arrayIndex">Array index.</param>
 public void CopyTo(KeyValuePair <TKey, TValue>[] array, int arrayIndex)
 {
     RuntimeAssert.ArgumentNotNull(array, nameof(array));
     RuntimeAssert.IndexInRange(arrayIndex, 0, array.Length - 1, nameof(arrayIndex));
     RuntimeAssert.GreaterOrEquals(array.Length - arrayIndex, _count, nameof(array));
     if (null != _entries)
     {
         for (var i = 0; i < _count; ++i)
         {
             if (_entries[i].HashCode >= 0)
             {
                 array[i + arrayIndex] = new KeyValuePair <TKey, TValue>(_entries[i].Key, _entries[i].Value);
             }
         }
     }
 }
예제 #24
0
 int Remove(TKey key, Func <int, bool> predicate)
 {
     RuntimeAssert.ArgumentNotNull(key, nameof(key));
     if (null != _buckets)
     {
         var hashCode = GetKeyHasCode(key);
         var bucket   = hashCode % _buckets.Length;
         var last     = -1;
         var i        = _buckets[bucket];
         var removed  = 0;
         while (i >= 0)
         {
             if (_entries[i].HashCode == hashCode && predicate(i))
             {
                 int j = _entries[i].Next;
                 if (0 > last)
                 {
                     // first item
                     _buckets[bucket] = j;
                 }
                 else
                 {
                     _entries[last].Next = j;
                 }
                 _entries[i].HashCode = -1;
                 _entries[i].Next     = _freeIndex;
                 _entries[i].Key      = default(TKey);
                 _entries[i].Value    = default(TValue);
                 _freeIndex           = i;
                 ++_freeCount;
                 ++_version;
                 ++removed;
                 i = j;
             }
             else
             {
                 last = i;
                 i    = _entries[i].Next;
             }
         }
         return(removed);
     }
     return(0);
 }
예제 #25
0
        bool FindEntries(TKey key, ICollection <int> entries)
        {
            RuntimeAssert.ArgumentNotNull(key, nameof(key));
            var found = false;

            if (null != _buckets)
            {
                var hashCode = GetKeyHasCode(key);
                for (int i = _buckets[hashCode % _buckets.Length]; i >= 0; i = _entries[i].Next)
                {
                    if (_entries[i].HashCode == hashCode && _keyComparer.Equals(_entries[i].Key, key))
                    {
                        found = true;
                        entries.Add(i);
                    }
                }
            }
            return(found);
        }
예제 #26
0
 /// <summary>
 /// Initializes new composite metadata object from initialized metadata objects appending any property marked
 /// as metadata to the raw representation.
 /// </summary>
 /// <param name="explicitMetadata"></param>
 protected internal MetadataObject(ImmutableDictionary <Type, IMetadata> explicitMetadata)
 {
     RuntimeAssert.ArgumentNotNull(explicitMetadata, nameof(explicitMetadata));
     _explicitMetadata = explicitMetadata;
     _rawMetadata      = L(() => {
         var builder = ImmutableDictionary.CreateBuilder <CaseInsensitive, object>();
         // compose explicit metadata
         _explicitMetadata.Values
         .ForEach(data => data.ForEach(raw => builder[raw.Key] = raw.Value));
         // compose implicit metadata
         this.GetType()
         .GetAccessors(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.FlattenHierarchy)
         .ForEach(accessor => {
             if (accessor.TryGetAttribute <MetadataKeyAttribute>(out var keyAttr))
             {
                 builder[keyAttr.Key] = accessor.GetValue(this);
             }
         });
         return(builder.ToImmutable());
     });
 }
 public MetadataFactory(Func <IServiceProvider, ICompositeMetadata, T> factory)
 {
     RuntimeAssert.ArgumentNotNull(factory, nameof(factory));
     Factory = factory;
 }
예제 #28
0
 public TypedSerializer(TypeSerializer nonTypedSerializer)
     : base(nonTypedSerializer.Factory)
 {
     RuntimeAssert.ArgumentNotNull(nonTypedSerializer, nameof(nonTypedSerializer));
     _nonTypedSerializer = nonTypedSerializer;
 }
예제 #29
0
 /// <summary>
 /// Substitutes parameter nodes in the source expression with respect to the specified substitutions.
 /// </summary>
 /// <param name="source">Source expression.</param>
 /// <param name="substitutions">Substitutions.</param>
 /// <returns>Resulting expression.</returns>
 public static Expression SubstituteParameters(this Expression source, IEnumerable <KeyValuePair <ParameterExpression, Expression> > substitutions)
 {
     RuntimeAssert.ArgumentNotNull(source, nameof(source));
     return(new ParameterSubstitution(substitutions).Visit(source));
 }
 /// <summary>
 /// Initializes new instance of <see cref="T:NCoreUtils.Serialization.ExplicitBinaryDataReader" /> from the
 /// specified byte array.
 /// </summary>
 /// <param name="data">Explicit byte array.</param>
 public ExplicitBinaryDataReader(byte[] data)
 {
     RuntimeAssert.ArgumentNotNull(data, nameof(data));
     _data = data;
 }