internal static T[] AsArrayInternal <T>(this IEnumerable <T>?source)
 {
     if (source == null)
     {
         return(ArrayEx.Empty <T>());
     }
     if (source is T[] array)
     {
         return(array);
     }
     if (source is ReadOnlyCollectionEx <T> readOnlyCollectionEx)
     {
         return(readOnlyCollectionEx.Wrapped is T[] wrappedArray ? wrappedArray : readOnlyCollectionEx.ToArray());
     }
     if (source is ICollection <T> collection1 && collection1.Count == 0)
     {
         return(ArrayEx.Empty <T>());
     }
     if (source is ICollection <T> collection2)
     {
         var result = new T[collection2.Count];
         collection2.CopyTo(result, 0);
         return(result);
     }
     return(new List <T>(source).ToArray());
 }
Example #2
0
 public InputInitializer(string key, IRelayInput input, ArrayEx <Action <DateTime>[]> queue, Action <InputInitializer> onDispose)
 {
     Key        = key;
     Input      = input;
     _queue     = queue;
     _onDispose = onDispose;
 }
Example #3
0
 // Constructs a new sorted list. The sorted list is initially empty and has
 // a capacity of zero. Upon adding the first element to the sorted list the
 // capacity is increased to 16, and then increased in multiples of two as
 // required. The elements of the sorted list are ordered according to the
 // IComparable interface, which must be implemented by the keys of
 // all entries added to the sorted list.
 public SortedList()
 {
     _keys     = ArrayEx.Empty <object>();
     _values   = ArrayEx.Empty <object>();
     _size     = 0;
     _comparer = new Comparer(CultureInfo.CurrentCulture);
 }
        internal static T[] AsArrayInternal <T>(this IEnumerable <T> source)
        {
            switch (source)
            {
            case null:
                return(ArrayEx.Empty <T>());

            case T[] array:
                return(array);

            case ReadOnlyCollectionEx <T> readOnlyCollectionEx when readOnlyCollectionEx.Wrapped is T[] array:
                return(array);

            case ICollection <T> collection when collection.Count == 0:
                return(ArrayEx.Empty <T>());

            case ICollection <T> collection:
                var result = new T[collection.Count];
                collection.CopyTo(result, 0);
                return(result);

            default:
                return(new List <T>(source).ToArray());
            }
        }
Example #5
0
        public static TResult[] Select <T, TResult>(this T[] array, Func <T, TResult> selector)
        {
            if (array == null)
            {
                throw new ArgumentNullException("array");
            }

            if (array.Length == 0)
            {
                return(ArrayEx.Empty <TResult>());
            }

            if (selector == null)
            {
                throw new ArgumentNullException("selector");
            }

            var result = new TResult[array.Length];

            for (int i = 0; i < array.Length; i++)
            {
                result[i] = selector(array[i]);
            }

            return(result);
        }
 public static GameObject New(this GameObject instance, GameObject parent, Vector3 po, params ActionContainer[] initializers)
 {
     return(instance.New(
                ArrayEx.Concat(
                    _.a((Transform t) => { t.SetParent(parent.transform); t.localPosition = po; })
                    , initializers)));
 }
        public void ReceivePackage(int len, byte[] data)
        {
            byte[] finalData = data.SubArray(0, len);

            packetBuffer = packetBuffer.Concat(finalData);

            //标记是否有完整的包接收到
            bool hasCompletePacket = false;

            do
            {
                int packSize = GetDataLength(packetBuffer);
                if (packSize == 0)
                {
                    break;
                }
                hasCompletePacket = packetBuffer.Length >= packSize;

                if (hasCompletePacket)
                {
                    byte[] packBytes = ArrayEx.CutHeadByLength(ref packetBuffer, packSize);
                    handleQueue.AddAction((act) =>
                    {
                        NetPackageHandler.HandlePackage(server, Package.PrasePackage(packBytes), act);
                    });
                }
            } while (hasCompletePacket);
        }
Example #8
0
        /// <summary>
        /// Formats a duration in minutes to a string
        /// </summary>
        /// <param name="hours"></param>
        /// <param name="minutes"></param>
        /// <returns></returns>
        public static string FormatDuration(int?totalMinutes)
        {
            if (totalMinutes != null)
            {
                int?toatalSeconds = totalMinutes * 60;

                int?          days         = Math.Floor(toatalSeconds / 86400);
                int?          hours        = Math.Floor((toatalSeconds % 86400) / 3600);
                int?          minutes      = Math.Floor(((toatalSeconds % 86400) % 3600) / 60);
                int?          seconds      = ((toatalSeconds % 86400) % 3600) % 60;
                List <string> formatString = new List <string>();
                if (days > 0)
                {
                    ArrayEx.Add(formatString, "{0}d");
                }

                if (hours > 0)
                {
                    ArrayEx.Add(formatString, "{1}h");
                }

                if (minutes > 0)
                {
                    ArrayEx.Add(formatString, "{2}m");
                }


                return(String.Format(ArrayEx.Join((Array)formatString, " "), days, hours, minutes));
            }
            else
            {
                return("");
            }
        }
        public static IReadOnlyList <T> WrapAsIReadOnlyList <T>(this IEnumerable <T> source)
        {
            if (source == null)
            {
                throw new ArgumentNullException(nameof(source));
            }
            if (source is T[] array)
            {
#if LESSTHAN_NET45
                return(new ReadOnlyCollectionEx <T>(array));
#else
                return(ArrayEx.AsReadOnly(array));
#endif
            }
            if (source is ListEx <T> listEx)
            {
                return(listEx.AsReadOnly());
            }
#if GREATERTHAN_NET45 || TARGETS_NETCORE || TARGETS_NETSTANDARD
            if (source is List <T> list)
            {
                return(list.AsReadOnly());
            }
#endif
            if (source is IReadOnlyList <T> result)
            {
                return(result);
            }
            return(EnumerationList <T> .Create(source));
        }
Example #10
0
 public InventoryItem()
 {
     Id      = EmptyID;
     Color01 = DefaultColor;
     Color02 = DefaultColor;
     Sockets = ArrayEx.Empty <int>();
 }
Example #11
0
            protected internal override Expression VisitLambda <T>(Expression <T> node)
            {
                IEnumerable <ParameterExpression> parameters = ArrayEx.Empty <ParameterExpression>();

                var count = node.ParameterCount;

                if (count > 0)
                {
                    var parameterList = new List <ParameterExpression>(count);

                    for (var i = 0; i < count; i++)
                    {
                        parameterList.Add(node.GetParameter(i));
                    }

                    parameters = parameterList;
                }

                PushParameters(parameters);

                base.VisitLambda(node);

                PopParameters(parameters);

                return(node);
            }
        public static IReadOnlyCollection <T> AsIReadOnlyCollection <T>(this IEnumerable <T>?source)
        {
            if (source == null)
            {
                return(EmptyCollection <T> .Instance);
            }
            if (source is T[] array)
            {
#if LESSTHAN_NET45
                return(new ReadOnlyCollectionEx <T>(array));
#else
                return(ArrayEx.AsReadOnly(array));
#endif
            }
            if (source is ListEx <T> listEx)
            {
                return(listEx.AsReadOnly());
            }
#if GREATERTHAN_NET45 || TARGETS_NETCORE || TARGETS_NETSTANDARD
            if (source is List <T> list)
            {
                return(list.AsReadOnly());
            }
#endif
            if (source is IReadOnlyCollection <T> result)
            {
                return(result);
            }
            return(EnumerationList <T> .Create(source));
        }
Example #13
0
        /// <summary>
        ///     Creates an <see cref="IndexExpression" /> to access an array.
        /// </summary>
        /// <param name="array">An expression representing the array to index.</param>
        /// <param name="indexes">An <see cref="IEnumerable{T}" /> containing expressions used to index the array.</param>
        /// <remarks>
        ///     The expression representing the array can be obtained by using the <see cref="MakeMemberAccess" /> method,
        ///     or through <see cref="NewArrayBounds(System.Type,System.Linq.Expressions.Expression[])" /> or
        ///     <see cref="NewArrayInit(System.Type,System.Linq.Expressions.Expression[])" />.
        /// </remarks>
        /// <returns>The created <see cref="IndexExpression" />.</returns>
        public static IndexExpression ArrayAccess(Expression array, IEnumerable <Expression>?indexes)
        {
            if (array == null)
            {
                throw new ArgumentNullException(nameof(array));
            }

            ExpressionUtils.RequiresCanRead(array, nameof(array));

            var arrayType = array.Type;

            if (!arrayType.IsArray)
            {
                throw new ArgumentException("Argument must be array", nameof(array));
            }

            if (indexes != null)
            {
                return(ArrayAccessExtracted(array, indexes, arrayType));
            }

            if (arrayType.GetArrayRank() != 0)
            {
                throw new ArgumentException("Incorrect number of indexes");
            }

            return(new IndexExpression(array, null, ArrayEx.Empty <Expression>()));
        }
Example #14
0
        public static object Get(Type type, IEnumerable <Type> preferredTypes)
        {
            if (!_dataGenerators.TryGetValue(type, out var dictionary))
            {
                return(type.GetTypeInfo().IsValueType ? Activator.CreateInstance(type) : null);
            }

            Delegate @delegate = null;

            foreach (var preferredType in preferredTypes)
            {
                if (!dictionary.TryGetValue(preferredType, out var found))
                {
                    continue;
                }

                @delegate = found;
                break;
            }

            if (@delegate == null)
            {
                @delegate = dictionary.First().Value;
            }

            return(@delegate.DynamicInvoke(ArrayEx.Empty <object>()));
        }
Example #15
0
        public void GenericClearTest1()
        {
            // ReSharper disable once AssignNullToNotNullAttribute
            Action test = () => ArrayEx.Clear <String>(null, 0, 2);

            Assert.Throws <ArgumentNullException>(test);
        }
Example #16
0
        internal PathInfo(
            PathType pathType,
            string path,
            bool isValidHelperLiteral,
            int contextChangeCount,
            IReadOnlyList <PathSegment> segments)
        {
            IsValidHelperLiteral = isValidHelperLiteral;
            HasValue             = pathType != PathType.Empty;
            _path = path;

            _hashCode = (_path.GetHashCode() * 397) ^ HasValue.GetHashCode();

            if (!HasValue)
            {
                return;
            }

            IsVariable    = pathType == PathType.Variable;
            IsInversion   = pathType == PathType.Inversion;
            IsBlockHelper = pathType == PathType.BlockHelper;
            IsBlockClose  = pathType == PathType.BlockClose;

            ContextChangeDepth = contextChangeCount;
            HasContextChange   = ContextChangeDepth > 0;

            var plainSegments = segments.Where(o => !o.IsContextChange && o.IsNotEmpty).ToArray();

            IsThis     = string.Equals(path, "this", StringComparison.OrdinalIgnoreCase) || path == "." || plainSegments.Any(o => o.IsThis);
            IsPureThis = string.Equals(path, "this", StringComparison.OrdinalIgnoreCase) || path == ".";

            var segment = plainSegments.SingleOrDefault(o => !o.IsThis);

            if (!segment.IsNotEmpty)
            {
                IsPureThis  = true;
                TrimmedPath = ".";
                PathChain   = ArrayEx.Empty <ChainSegment>();
                return;
            }

            PathChain = segment.PathChain;
            var lastIndex = segment.PathChain.Length - 1;

            using (var container = StringBuilderPool.Shared.Use())
            {
                for (int index = 0; index < PathChain.Length; index++)
                {
                    container.Value.Append(PathChain[index].TrimmedValue);
                    if (index != lastIndex)
                    {
                        container.Value.Append('.');
                    }
                }

                TrimmedPath = container.Value.ToString();
            }

            _trimmedHashCode = TrimmedPath.GetHashCode();
        }
Example #17
0
        protected override Expression VisitIteratorExpression(IteratorExpression iex)
        {
            var context = Arg <BindingContext>(CompilationContext.BindingContext);

            var template = FunctionBuilder.CompileCore(new[] { iex.Template }, CompilationContext.Configuration);
            var ifEmpty  = FunctionBuilder.CompileCore(new[] { iex.IfEmpty }, CompilationContext.Configuration);

            if (iex.Sequence is PathExpression pathExpression)
            {
                pathExpression.Context = PathExpression.ResolutionContext.Parameter;
            }

            var compiledSequence  = Arg <object>(FunctionBuilder.Reduce(iex.Sequence, CompilationContext));
            var blockParamsValues = CreateBlockParams();

            return(Call(() =>
                        Iterator.Iterate(context, blockParamsValues, compiledSequence, template, ifEmpty)
                        ));

            ExpressionContainer <ChainSegment[]> CreateBlockParams()
            {
                var parameters = iex.BlockParams?.BlockParam?.Parameters;

                if (parameters == null)
                {
                    parameters = ArrayEx.Empty <ChainSegment>();
                }

                return(Arg(parameters));
            }
        }
Example #18
0
 override public void VisitArrayEx(ArrayEx x)
 {
     _serializer.StartSerialize(typeof(ArrayEx).Name, SerializeSpan(x.Span));
     foreach (var item in x.Items)
     {
         if (item != null)
         {
             if (item is ValueItem vi)
             {
                 SerializeItem(vi);
             }
             else if (item is RefItem ri)
             {
                 SerializeItem(ri);
             }
             else if (item is SpreadItem si)
             {
                 SerializeItem(si);
             }
             else
             {
                 throw new ArgumentException();
             }
         }
     }
     _serializer.EndSerialize();
 }
        public static Vector3 GetVector3(string key)
        {
            string v = PlayerPrefs.GetString(key);

            float[] tokens = ArrayEx.Parse <float>(v);
            return(new Vector3(tokens[0], tokens[1], tokens[2]));
        }
Example #20
0
 public bool Add(T item)
 {
     if (Bound.Contains(item.Position))
     {
         if (m_childs.Length == 0)
         {
             if (Depth < MaxDepth)
             {
                 Subdivide();
             }
             else
             {
                 item.Node = this;
                 ArrayEx.Add(ref m_items, ref m_items_size, item);
                 return(true);
             }
         }
         for (int index = 0; index < m_childs.Length; index++)
         {
             if (m_childs[index].Add(item))
             {
                 return(true);
             }
         }
     }
     return(Parent?.Add(item) ?? false);
 }
Example #21
0
        public override void VisitArrayEx(ArrayEx x)
        {
            // Force traversing

            foreach (Item item in x.Items)
            {
                // It may not be listed and can be null
                VisitElement(item.Index);

                var valueItem = item as ValueItem;
                if (valueItem != null)
                {
                    VisitElement(valueItem.ValueExpr);
                }
                else
                {
                    var refItem = item as RefItem;
                    if (refItem != null)
                    {
                        VisitElement(refItem.RefToGet);
                    }
                    else
                    {
                        throw new NotSupportedException("There is no other array item type");
                    }
                }
            }
        }
Example #22
0
        public void ReceivePackage(int len, byte[] data)
        {
            byte[] finalData = data.SubArray(0, len);

            packetBuffer = packetBuffer.Concat(finalData);

            //标记是否有完整的包接收到
            bool hasCompletePacket = false;

            do
            {
                int packSize = GetDataLength(packetBuffer);
                if (packSize == 0)
                {
                    break;
                }

                hasCompletePacket = packetBuffer.Length >= packSize;

                if (hasCompletePacket)
                {
                    byte[] packBytes = ArrayEx.CutHeadByLength(ref packetBuffer, packSize);
                    packageList.Add(Package.PrasePackage(packBytes));
                }
            } while (hasCompletePacket);
        }
 public ConditionalExtendedList(IEnumerable <T> target, IEnumerable <T> append, Func <bool>?enumerateTarget, Func <bool>?enumerateAppend)
 {
     _target          = target?.WrapAsIList() ?? ArrayEx.Empty <T>();
     _append          = append?.WrapAsIList() ?? ArrayEx.Empty <T>();
     _enumerateTarget = enumerateTarget ?? (target == null ? FuncHelper.GetFallacyFunc() : FuncHelper.GetTautologyFunc());
     _enumerateAppend = enumerateAppend ?? (append == null ? FuncHelper.GetFallacyFunc() : FuncHelper.GetTautologyFunc());
 }
Example #24
0
        public static Column AddColumn(List <Column> cols, string displayName, int width, string field)
        {
            Column col = NewColumn(field, displayName, width);

            ArrayEx.Add(cols, col);
            return(col);
        }
Example #25
0
        public static PathInfo Parse(string path)
        {
            if (path == "null")
            {
                return(new PathInfo(PathType.Empty, path, false, 0, null));
            }

            var originalPath  = path;
            var pathSubstring = new Substring(path);

            var isValidHelperLiteral = true;
            var pathType             = GetPathType(pathSubstring);
            var isVariable           = pathType == PathType.Variable;
            var isInversion          = pathType == PathType.Inversion;
            var isBlockHelper        = pathType == PathType.BlockHelper;

            if (isVariable || isBlockHelper || isInversion)
            {
                isValidHelperLiteral = isBlockHelper || isInversion;
                pathSubstring        = new Substring(pathSubstring, 1);
            }

            var contextChangeCount = 0;
            var segments           = new List <PathSegment>();
            var pathParts          = Substring.Split(pathSubstring, '/');

            if (pathParts.Count > 1)
            {
                isValidHelperLiteral = false;
            }
            for (var index = 0; index < pathParts.Count; index++)
            {
                var segment = pathParts[index];
                if (segment.Length == 2 && segment[0] == '.' && segment[1] == '.')
                {
                    contextChangeCount++;
                    isValidHelperLiteral = false;
                    segments.Add(new PathSegment(segment, ArrayEx.Empty <ChainSegment>()));
                    continue;
                }

                if (segment.Length == 1 && segment[0] == '.')
                {
                    isValidHelperLiteral = false;
                    segments.Add(new PathSegment(segment, ArrayEx.Empty <ChainSegment>()));
                    continue;
                }

                var chainSegments = GetPathChain(segment).ToArray();
                if (chainSegments.Length > 1)
                {
                    isValidHelperLiteral = false;
                }

                segments.Add(new PathSegment(segment, chainSegments));
            }

            return(new PathInfo(pathType, originalPath, isValidHelperLiteral, contextChangeCount, segments));
        }
Example #26
0
        public static PathInfo Parse(string path)
        {
            if (path == "null")
            {
                return(Empty);
            }

            var originalPath  = path;
            var pathType      = GetPathType(path);
            var pathSubstring = new Substring(path);

            var isValidHelperLiteral = true;
            var isVariable           = pathType == PathType.Variable;
            var isInversion          = pathType == PathType.Inversion;
            var isBlockHelper        = pathType == PathType.BlockHelper;

            if (isVariable || isBlockHelper || isInversion)
            {
                isValidHelperLiteral = isBlockHelper || isInversion;
                pathSubstring        = new Substring(pathSubstring, 1);
            }

            var segments           = new List <PathSegment>();
            var pathParts          = Substring.Split(pathSubstring, '/');
            var extendedEnumerator = ExtendedEnumerator <Substring> .Create(pathParts);

            while (extendedEnumerator.MoveNext())
            {
                var segment = extendedEnumerator.Current.Value;
                if (segment.Length == 2 && segment[0] == '.' && segment[1] == '.')
                {
                    isValidHelperLiteral = false;
                    segments.Add(new PathSegment(segment, ArrayEx.Empty <ChainSegment>()));
                    continue;
                }

                if (segment.Length == 1 && segment[0] == '.')
                {
                    isValidHelperLiteral = false;
                    segments.Add(new PathSegment(segment, ArrayEx.Empty <ChainSegment>()));
                    continue;
                }

                var chainSegments = GetPathChain(segment);
                if (chainSegments.Length > 1)
                {
                    isValidHelperLiteral = false;
                }

                segments.Add(new PathSegment(segment, chainSegments));
            }

            if (isValidHelperLiteral && segments.Count > 1)
            {
                isValidHelperLiteral = false;
            }

            return(new PathInfo(pathType, originalPath, isValidHelperLiteral, segments.ToArray()));
        }
Example #27
0
        public void SelectWithEmptyArrayAndNullLambdaDoesNotThrow()
        {
            var array = ArrayEx.Empty <int>();

            Assert.That(new TestDelegate(() =>
                                         array.Select <int, byte>(null)),
                        Throws.Nothing);
        }
Example #28
0
        public void ResizeWithLengthLessThanZeroThrows()
        {
            var array = ArrayEx.Empty <int>();

            Assert.That(() =>
                        array.Resize(-1),
                        Throws.InstanceOf <ArgumentOutOfRangeException>());
        }
Example #29
0
        public void SelectWithNullLambdaThrows()
        {
            var array = ArrayEx.Create(10, i => i + 1);

            Assert.That(() =>
                        array.Select <int, byte>(null),
                        Throws.InstanceOf <ArgumentNullException>());
        }
        public T AddManager <T>()
            where T : BaseManager
        {
            var manager = New <T> .Create();

            ArrayEx.Add(ref m_managers, ref m_managers_size, manager);
            return(manager);
        }
        private static void InitDirectionsIfNeeded()
        {
            if (_directions == null)
            {
                _directions = new ArrayEx<GridDirection>(new int[] { 3, 3, 3 });

                _directions[1, 1, 1] = GridDirection.NA;

                _directions[1, 0, 1] = GridDirection.North;  // North[0, -1,  0]
                _directions[2, 0, 1] = GridDirection.NorthEast;  // North-East[1, -1,  0]
                _directions[2, 1, 1] = GridDirection.East;  // East[1,  0,  0]
                _directions[2, 2, 1] = GridDirection.SouthEast;  // South-East[1,  1,  0]
                _directions[1, 2, 1] = GridDirection.South;  // South[0,  1,  0]
                _directions[0, 2, 1] = GridDirection.SouthWest;  // South-West[-1, 1,  0]
                _directions[0, 1, 1] = GridDirection.West;  // West[-1, 0,  0]
                _directions[0, 0, 1] = GridDirection.NorthWest;  // North-West[-1,-1,  0]

                _directions[1, 0, 0] = GridDirection.NorthLower;  // North-Lower[0, -1, -1]
                _directions[2, 0, 0] = GridDirection.NorthEastLower;  // North-East-Lower[1, -1, -1]
                _directions[2, 1, 0] = GridDirection.EastLower; // East-Lower[1,  0, -1]
                _directions[2, 2, 0] = GridDirection.SouthEastLower;  // South-East-Lower[ 1,  1, -1]
                _directions[1, 2, 0] = GridDirection.SouthLower;  // South-Lower[0,  1, -1]
                _directions[0, 2, 0] = GridDirection.SouthWestLower;  // South-West-Lower[-1, 1, -1]
                _directions[0, 1, 0] = GridDirection.WestLower; // West-Lower[-1, 0, -1]
                _directions[0, 0, 0] = GridDirection.NorthWestLower; // North-West-Lower[-1,-1, -1]
                _directions[1, 1, 0] = GridDirection.Lower;  // Lower[0,  0, -1]

                _directions[1, 0, 2] = GridDirection.NorthRaise;  // North-Raise[0, -1,  1]
                _directions[2, 0, 2] = GridDirection.NorthEastRaise;  // North-East-Raise[1, -1,  1]
                _directions[2, 1, 2] = GridDirection.EastRaise;  // East-Raise[1,  0,  1]
                _directions[2, 2, 2] = GridDirection.SouthEastRaise;  // South-East-Raise[1,  1,  1]
                _directions[1, 2, 2] = GridDirection.SouthRaise;  // South-Raise[0,  1,  1]
                _directions[0, 2, 2] = GridDirection.SouthWestRaise; // South-West-Raise[-1, 1,  1]
                _directions[0, 1, 2] = GridDirection.WestRaise;  // West-Raise[-1,  0,  1]
                _directions[0, 0, 2] = GridDirection.NorthWestRaise;  // North-West-Raise[-1, -1,  1]
                _directions[1, 1, 2] = GridDirection.Raise;  // Raise[ 0,  0,  1]
            }
        }
Example #32
0
        /// <summary>
        /// Creates new grid of specefic size
        /// </summary>
        /// <param name="sizeX">X size parameter</param>
        /// <param name="sizeY">Y size parameter</param>
        /// <param name="sizeZ">Z size parameter</param>
        public void Create(int sizeX, int sizeY, int sizeZ, Cell3D polygon, INodeInfo fill = null)
        {
            SizeX = sizeX;
            SizeY = sizeY;
            SizeZ = sizeZ;
            Nodes = new ArrayEx<Cell>(new int[] { SizeX, SizeY, SizeZ });

            for (int k = 0; k < SizeZ; k++)
            {
                for (int j = 0; j < SizeY; j++)
                {
                    for (int i = 0; i < SizeX; i++)
                    {
                        //_nodes[i, j, k] = new Node3D<T>(i * Polygon.Bounds.SizeX, j * Polygon.Bounds.SizeY, k * Polygon.Bounds.SizeZ, Polygon);
                        Nodes[i, j, k] = new Cell(i, j, k, Polygon, this, fill);
                    }
                }
            }
        }