Ejemplo n.º 1
0
        /// <summary>
        /// Converts the span, which encodes binary data as hex characters, to an equivalent 8-bit unsigned integer array.
        /// </summary>
        /// <param name="chars">The span to convert.</param>
        /// <returns>An array of 8-bit unsigned integers that is equivalent to <paramref name="chars"/>.</returns>
        /// <exception cref="FormatException">The length of <paramref name="chars"/>, ignoring white-space characters, is not zero or a multiple of 2.</exception>
        /// <exception cref="FormatException">The format of <paramref name="chars"/> is invalid. <paramref name="chars"/> contains a non-hex character.</exception>
        public static byte[] FromHexString(ReadOnlySpan <char> chars)
        {
            if (chars.Length == 0)
            {
                return(Array.Empty <byte>());
            }

            unsafe
            {
                fixed(char *inPtr = &MemoryMarshal.GetReference(chars))
                {
                    var resultLength = FromHex_ComputeResultLength(inPtr, chars.Length);

#if GC_ALLOC_UNINIT
                    var result = GC.AllocateUninitializedArray <byte>(resultLength);
#else
                    var result = new byte[resultLength];
#endif
                    fixed(byte *outPtr = result)
                    {
                        var res = ConvertFromHexArray(outPtr, result.Length, inPtr, chars.Length);

                        if (res < 0)
                        {
                            throw new FormatException(SR.Format_BadHexChar);
                        }
                        Debug.Assert(res == result.Length);
                    }

                    return(result);
                }
            }
        }
Ejemplo n.º 2
0
 internal SpriteDataSet(bool aligned, ReadOnlyMemory2D <byte> data)
 {
     Data      = data;
     Reference = GC.AllocateUninitializedArray <byte>((int)Data.Length);
     Data.CopyTo(Reference);
     Aligned = aligned;
 }
Ejemplo n.º 3
0
    private static void AddErrorCases(Random random)
    {
        {
            // error case
            Vector2I outerDimensions = (704, 2256);
            uint[]   data            = GC.AllocateUninitializedArray <uint>(outerDimensions.Area);
            random.NextBytes(data.AsSpan().AsBytes());
            Bounds innerBounds = new((703, 1912), (1, 264));

            ReadOnlySpan <byte> dataBytes = data.AsSpan().AsBytes();

            var format      = SurfaceFormat.Color;
            var actualWidth = format.SizeBytes(innerBounds.Extent.X);
            var rawStride   = format.SizeBytes(outerDimensions.Width);
            var rawOffset   = (rawStride * innerBounds.Top) + format.SizeBytes(innerBounds.Left);

            SpriteDataSet set = new(
                false,
                new(
                    array : dataBytes.ToArray(),
                    offset : rawOffset,
                    width : actualWidth,
                    height : innerBounds.Extent.Y,
                    pitch : rawStride - actualWidth
                    )
                );
            DataSets.Add(set);
        }
    }
Ejemplo n.º 4
0
        private static IEnumerable <object> CreateObjectsInDifferentGenerations()
        {
            // This object should go into LOH
            yield return(new DumpSampleClass[50000]);

#if NET5_0_OR_GREATER
            // This object should go into POH
            yield return(GC.AllocateUninitializedArray <byte>(10000, pinned: true));
#endif

            for (var i = 0; i < 5; i++)
            {
                yield return(new DumpSampleClass());
            }
            GC.Collect();

            for (var i = 0; i < 3; i++)
            {
                yield return(new DumpSampleClass());
            }
            GC.Collect();

            for (var i = 0; i < 10; i++)
            {
                yield return(new DumpSampleClass());
            }
        }
Ejemplo n.º 5
0
        public RawB2Sieve(int sieveSize)
        {
            SieveSize = sieveSize;

            data = GC.AllocateUninitializedArray <byte>((SieveSize >> (dataBitsShift + 1)) + 1, pinned: true);
            data.AsSpan().Fill(byte.MaxValue);
        }
Ejemplo n.º 6
0
            public MemoryLender(int segmentSize, int segmentCount)
            {
                if (segmentSize <= 0)
                {
                    throw new ArgumentOutOfRangeException(nameof(segmentSize));
                }
                if (segmentCount <= 0)
                {
                    throw new ArgumentOutOfRangeException(nameof(segmentCount));
                }
                _segmentSize = segmentSize;

                if (RuntimeHelpers.IsReferenceOrContainsReferences <T>())
                {
                    _array = new T[segmentSize * segmentCount];
                }
                else
                {
#if NET5_0_OR_GREATER
                    _array = GC.AllocateUninitializedArray <T>(segmentSize * segmentCount, pinned: true);
#else
                    _array = new T[segmentSize * segmentCount];
#endif
                }
                _segmentState  = new BitArray(segmentCount);
                _availableHead = 0;
                _maxCount      = segmentCount;
                var availableIDStack = new int[segmentCount];
                for (int i = 0; i < availableIDStack.Length; i++)
                {
                    availableIDStack[i] = i;
                }
                _availableIDStack = availableIDStack;
            }
Ejemplo n.º 7
0
    public int GetOrAddId(T value)
    {
        if (!typeof(T).IsValueType)
        {
            ArgumentNullException.ThrowIfNull(value, nameof(value));
        }

        // Get
        int valueId = value !.GetHashCode();

        if (TryGetIdImpl(valueId, out int id))
        {
            return(id);
        }

        // Add
        if (IsFull)
        {
            BitCount++;
            int[] newArray = GC.AllocateUninitializedArray <int>(1 << BitCount);
            Array.Copy(Values, newArray, Values.Length);
            Values = newArray;
        }

        var newId = Count;

        Values[Count++] = valueId;
        return(newId);
    }
        public int[] CollectionCopyTo()
        {
            var result = GC.AllocateUninitializedArray <int>(Count);

            ((ICollection <int>)array !).CopyTo(result, 0);
            return(result);
        }
        public int[] SpanCopyTo()
        {
            var result = GC.AllocateUninitializedArray <int>(Count);

            array.AsSpan().CopyTo(result);
            return(result);
        }
Ejemplo n.º 10
0
        public static void Configure()
        {
            var enabled = ServerConfiguration.GetOrUpdateSetting("connectuo.enabled", true);
            var token   = ServerConfiguration.GetOrUpdateSetting("connectuo.token", "");

            if (enabled)
            {
                try
                {
                    if (!string.IsNullOrWhiteSpace(token))
                    {
                        if (token.Length != _connectUOTokenLength * 2)
                        {
                            throw new Exception("Invalid length for ConnectUO token");
                        }

                        _token = GC.AllocateUninitializedArray <byte>(_connectUOTokenLength);
                        token.ToUpperInvariant().GetBytes(_token);
                    }
                }
                catch
                {
                    logger.Warning("ConnectUO token could not be parsed. Make sure modernuo.json is properly configured");
                    _token = null;
                }

                FreeshardProtocol.Register(0xC0, false, PollInfo);
            }
        }
Ejemplo n.º 11
0
        /// <summary>
        /// Creates a new page-locked 1D array.
        /// </summary>
        /// <param name="accelerator">The parent accelerator.</param>
        /// <param name="extent">The number of elements to allocate.</param>
        /// <param name="uninitialized">True, to allocate an uninitialized array.</param>
        internal unsafe PageLockedArray1D(
            Accelerator accelerator,
            LongIndex1D extent,
            bool uninitialized)
        {
            if (extent < 0L)
            {
                throw new ArgumentOutOfRangeException(nameof(extent));
            }
#if NET5_0_OR_GREATER
            array = uninitialized
                ? GC.AllocateUninitializedArray <T>(extent.ToIntIndex(), pinned: true)
                : GC.AllocateArray <T>(extent.ToIntIndex(), pinned: true);

            fixed(T *ptr = array)
            Initialize(accelerator, new IntPtr(ptr), extent);
#else
            Trace.WriteLineIf(
                uninitialized,
                RuntimeErrorMessages.NotSupportedUninitalizedArrayInitialization);
            array  = new T[extent];
            handle = GCHandle.Alloc(array, GCHandleType.Pinned);
            Initialize(accelerator, handle.AddrOfPinnedObject(), extent);
#endif
        }
Ejemplo n.º 12
0
        protected override unsafe byte[] UncheckedTransformFinalBlock(byte[] inputBuffer, int inputOffset, int inputCount)
        {
            if (SymmetricPadding.DepaddingRequired(PaddingMode))
            {
                byte[] rented  = CryptoPool.Rent(inputCount + InputBlockSize);
                int    written = 0;

                fixed(byte *pRented = rented)
                {
                    try
                    {
                        written = UncheckedTransformFinalBlock(inputBuffer.AsSpan(inputOffset, inputCount), rented);
                        return(rented.AsSpan(0, written).ToArray());
                    }
                    finally
                    {
                        CryptoPool.Return(rented, clearSize: written);
                    }
                }
            }
            else
            {
                byte[] buffer  = GC.AllocateUninitializedArray <byte>(inputCount);
                int    written = UncheckedTransformFinalBlock(inputBuffer.AsSpan(inputOffset, inputCount), buffer);
                Debug.Assert(written == buffer.Length);
                return(buffer);
            }
        }
        private static void RunRemoteHost(string ip, int port)
        {
            byte[] buffer = GC.AllocateUninitializedArray <byte>(64 * 1024, pinned: true);

            using var listenSocket = new Socket(SocketType.Stream, ProtocolType.Tcp);

            listenSocket.Bind(new IPEndPoint(IPAddress.Parse(ip), port));
            Console.WriteLine($"Remote host bound on {listenSocket.LocalEndPoint}");

            listenSocket.Listen();

            while (true)
            {
                try
                {
                    while (true)
                    {
                        using Socket socket = listenSocket.Accept();
                        while (socket.Receive(buffer, SocketFlags.None) != 0)
                        {
                            ;
                        }
                    }
                }
                catch (SocketException ex) when(ex.SocketErrorCode == SocketError.ConnectionReset)
                {
                    // do nothing.
                }
            }
        }
Ejemplo n.º 14
0
 private static void AllocateArrayNegativeSize(int negValue)
 {
     Assert.Throws <OverflowException>(() => GC.AllocateUninitializedArray <byte>(-1));
     Assert.Throws <OverflowException>(() => GC.AllocateUninitializedArray <byte>(negValue));
     Assert.Throws <OverflowException>(() => GC.AllocateUninitializedArray <byte>(-1, pinned: true));
     Assert.Throws <OverflowException>(() => GC.AllocateUninitializedArray <byte>(negValue, pinned: true));
 }
Ejemplo n.º 15
0
        public static void Deserialize(string path, Action <IGenericReader> deserializer, bool ensure = true)
        {
            AssemblyHandler.EnsureDirectory(Path.GetDirectoryName(path));

            if (!File.Exists(path))
            {
                if (ensure)
                {
                    new FileInfo(path).Create().Close();
                }

                return;
            }

            using FileStream fs = new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.Read);
            // TODO: Support files larger than 2GB
            var buffer = GC.AllocateUninitializedArray <byte>((int)fs.Length);

            try
            {
                deserializer(new BufferReader(buffer));
            }
            catch (Exception e)
            {
                Console.WriteLine("[Persistence]: Failed to deserialize");
                Console.WriteLine(e);
            }
        }
Ejemplo n.º 16
0
        private unsafe static void AllocateArrayCheckPinning()
        {
            var list = new List <long[]>();

            var r = new Random(1234);

            for (int i = 0; i < 10000; i++)
            {
                int size = r.Next(2, 100);
                var arr  = i % 2 == 1 ?
                           GC.AllocateArray <long>(size, pinned: true) :
                           GC.AllocateUninitializedArray <long>(size, pinned: true);

                fixed(long *pElem = &arr[0])
                {
                    *pElem = (long)pElem;
                }

                if (r.Next(100) % 2 == 0)
                {
                    list.Add(arr);
                }
            }

            GC.Collect();

            foreach (var arr in list)
            {
                fixed(long *pElem = &arr[0])
                {
                    Assert.Equal(*pElem, (long)pElem);
                }
            }
        }
Ejemplo n.º 17
0
        private void Resize(int amount)
        {
            var newBuffer = GC.AllocateUninitializedArray <byte>(amount);

            _buffer.AsSpan(0, Math.Min(amount, _buffer.Length)).CopyTo(newBuffer);
            _buffer = newBuffer;
        }
        protected override unsafe byte[] UncheckedTransformFinalBlock(byte[] inputBuffer, int inputOffset, int inputCount)
        {
            if (DepaddingRequired)
            {
                byte[] rented  = CryptoPool.Rent(inputCount + InputBlockSize);
                int    written = 0;

                fixed(byte *pRented = rented)
                {
                    try
                    {
                        written = UncheckedTransformFinalBlock(inputBuffer.AsSpan(inputOffset, inputCount), rented);
                        return(rented.AsSpan(0, written).ToArray());
                    }
                    finally
                    {
                        CryptoPool.Return(rented, clearSize: written);
                    }
                }
            }
            else
            {
#if NETSTANDARD || NETFRAMEWORK || NETCOREAPP3_0
                byte[] buffer = new byte[inputCount];
#else
                byte[] buffer = GC.AllocateUninitializedArray <byte>(inputCount);
#endif
                int written = UncheckedTransformFinalBlock(inputBuffer.AsSpan(inputOffset, inputCount), buffer);
                Debug.Assert(written == buffer.Length);
                return(buffer);
            }
        }
Ejemplo n.º 19
0
        public static void DoWork()
        {
            // Allocate POH objects
            var arr0 = GC.AllocateUninitializedArray <int>(100000, true);
            var arr1 = GC.AllocateArray <int>(200000, true);

            int k = 0;

            while (k < 3)
            {
                Console.WriteLine("{0}: Restarting run {1}", Thread.CurrentThread.Name, k);
                int[] largeArray = new int[1000000];
                for (int i = 0; i <= 100; i++)
                {
                    int[] saveArray = largeArray;
                    largeArray = new int[largeArray.Length + 100000];
                    saveArray  = null;
                    //Console.WriteLine("{0} at size {1}",Thread.CurrentThread.Name,largeArray.Length.ToString());
                }

                k++;
            }

            GC.KeepAlive(arr0);
            GC.KeepAlive(arr1);
        }
        public override T[] Rent(int minimumLength)
        {
            // Arrays can't be smaller than zero.  We allow requesting zero-length arrays (even though
            // pooling such an array isn't valuable) as it's a valid length array, and we want the pool
            // to be usable in general instead of using `new`, even for computed lengths.
            if (minimumLength < 0)
            {
                throw new ArgumentOutOfRangeException(nameof(minimumLength));
            }
            else if (minimumLength == 0)
            {
                // No need to log the empty array.  Our pool is effectively infinite
                // and we'll never allocate for rents and never store for returns.
                return(Array.Empty <T>());
            }

            T[]? buffer;

            // Get the bucket number for the array length
            int bucketIndex = Utilities.SelectBucketIndex(minimumLength);

            // If the array could come from a bucket...
            if (bucketIndex < _buckets.Length)
            {
                // First try to get it from TLS if possible.
                T[]?[]? tlsBuckets = t_tlsBuckets;
                if (tlsBuckets != null)
                {
                    buffer = tlsBuckets[bucketIndex];
                    if (buffer != null)
                    {
                        tlsBuckets[bucketIndex] = null;
                        return(buffer);
                    }
                }

                // We couldn't get a buffer from TLS, so try the global stack.
                PerCoreLockedStacks?b = _buckets[bucketIndex];
                if (b != null)
                {
                    buffer = b.TryPop();
                    if (buffer != null)
                    {
                        return(buffer);
                    }
                }

                // No buffer available.  Allocate a new buffer with a size corresponding to the appropriate bucket.
                buffer = GC.AllocateUninitializedArray <T>(_bucketArraySizes[bucketIndex]);
            }
            else
            {
                // The request was for a size too large for the pool.  Allocate an array of exactly the requested length.
                // When it's returned to the pool, we'll simply throw it away.
                buffer = GC.AllocateUninitializedArray <T>(minimumLength);
            }

            return(buffer);
        }
Ejemplo n.º 21
0
        public static void FixArgs(ref string[] args)
        {
            var old = args;

            args = GC.AllocateUninitializedArray <string>(args.Length - 1);

            Array.Copy(old, 1, args, 0, args.Length);
        }
Ejemplo n.º 22
0
        public static void FixSetString(ref string[] args, int index)
        {
            var old = args;

            args = GC.AllocateUninitializedArray <string>(index);

            Array.Copy(old, 0, args, 0, index);
        }
Ejemplo n.º 23
0
        public static byte[] AllocArray(int size)
        {
#if NET5_0
            return(GC.AllocateUninitializedArray <byte>(size, false));
#else
            return(new byte[size]);
#endif
        }
Ejemplo n.º 24
0
 /// <summary>
 /// Create a buffer with the specified data.
 /// </summary>
 /// <param name="data">The data to be contained in this buffer.</param>
 public Buffer(ReadOnlySpan <byte> data)
 {
     InnerBuffer = GC.AllocateUninitializedArray <byte>(data.Length);
     if (!data.IsEmpty)
     {
         data.CopyTo(InnerBuffer);
     }
 }
Ejemplo n.º 25
0
        protected override byte[] UncheckedTransformFinalBlock(byte[] inputBuffer, int inputOffset, int inputCount)
        {
            byte[] buffer  = GC.AllocateUninitializedArray <byte>(GetCiphertextLength(inputCount));
            int    written = UncheckedTransformFinalBlock(inputBuffer.AsSpan(inputOffset, inputCount), buffer);

            Debug.Assert(written == buffer.Length);
            return(buffer);
        }
Ejemplo n.º 26
0
        private static BufferedStreamReader Decompress_Internal_Init(Stream stream, ArchiveCompressorOptions options, out byte[] decompressedBuffer)
        {
            var endianByteStream = GetStreamFromEndian(stream, options.BigEndian, options.BufferSize, out var bufferedStreamReader);

            endianByteStream.Seek(_decompSizeOffset, SeekOrigin.Current);
            decompressedBuffer = GC.AllocateUninitializedArray <byte>(endianByteStream.Read <int>());
            return(bufferedStreamReader);
        }
Ejemplo n.º 27
0
        public static MemoryPoolSlab Create(int length)
        {
            // allocate requested memory length from the pinned memory heap
            var pinnedArray = GC.AllocateUninitializedArray <byte>(length, pinned: true);

            // allocate and return slab tracking object
            return(new MemoryPoolSlab(pinnedArray));
        }
Ejemplo n.º 28
0
        internal static T[] AllocatePinnedUninitializedArray <T>(int count) where T : unmanaged
        {
#if NET5_0_OR_GREATER || NET5_0
            return(GC.AllocateUninitializedArray <T>(count, true));
#else
            return(new T[count]);
#endif
        }
Ejemplo n.º 29
0
        internal MemoryPoolBlock(SlabMemoryPool pool, int length)
        {
            Pool = pool;

            var pinnedArray = GC.AllocateUninitializedArray <byte>(length, pinned: true);

            Memory = MemoryMarshal.CreateFromPinnedArray(pinnedArray, 0, pinnedArray.Length);
        }
Ejemplo n.º 30
0
        internal void DoEnlargeArray(int needArraySize)
        {
            const int EXTRA_ALLOC_MOVES = 8; // allocate more than bare minimum to reduce number of times we have to expand

            MGMove[] newMoveArray = GC.AllocateUninitializedArray <MGMove>(needArraySize + EXTRA_ALLOC_MOVES);
            Array.Copy(MovesArray, newMoveArray, NumMovesUsed);
            MovesArray = newMoveArray;
        }