Exemplo n.º 1
0
        public static async Task WriteBytesAsync(Stream stream, IntPtr bytes, int length)
        {
            if (length > 130 && ArrayHelper.IsSupportedOneRankValueArrayInfo)
            {
                var ends = ArrayHelper.AsTempOneRankValueArray <byte>(bytes, length, out var starts);

                await stream.WriteAsync(starts, 0, starts.Length);

                await stream.WriteAsync(ends, 0, ends.Length);

                unsafe
                {
                    Unsafe.CopyBlock(
                        ref ((byte *)bytes)[0],
                        ref starts[0],
                        (uint)starts.Length);
                }
            }
            else
            {
                const int bufferLength = 128;

                var buffer = new byte[Math.Min(bufferLength, length)];

                for (int index = 0, count = buffer.Length;
                     index < length;
                     index += count, count = Math.Min(buffer.Length, length - index))
                {
                    unsafe
                    {
                        Unsafe.CopyBlock(
                            ref buffer[0],
                            ref ((byte *)bytes)[index],
                            (uint)count);
                    }

                    await stream.WriteAsync(buffer, 0, count);
                }
            }
        }
Exemplo n.º 2
0
        public static async Task WriteCharsAsync(TextWriter textWriter, IntPtr chars, int length)
        {
            if (length > 130 && ArrayHelper.IsSupportedOneRankValueArrayInfo)
            {
                var ends = ArrayHelper.AsTempOneRankValueArray <char>(chars, length, out var starts);

                await textWriter.WriteAsync(starts);

                await textWriter.WriteAsync(ends);

                unsafe
                {
                    Unsafe.CopyBlock(
                        ref Unsafe.As <char, byte>(ref ((char *)chars)[0]),
                        ref Unsafe.As <char, byte>(ref starts[0]),
                        (uint)(starts.Length * sizeof(char)));
                }
            }
            else
            {
                const int bufferLength = 128;

                var buffer = new char[Math.Min(bufferLength, length)];

                for (int index = 0, count = buffer.Length;
                     index < length;
                     index += count, count = Math.Min(buffer.Length, length - index))
                {
                    unsafe
                    {
                        Unsafe.CopyBlock(
                            ref Unsafe.As <char, byte>(ref buffer[0]),
                            ref Unsafe.As <char, byte>(ref ((char *)chars)[index]),
                            (uint)(count * sizeof(char)));
                    }

                    textWriter.Write(buffer, 0, count);
                }
            }
        }
Exemplo n.º 3
0
        /**
         * Create a buffer on the device
         *
         * @param usageFlags Usage flag bitmask for the buffer (i.e. index, vertex, uniform buffer)
         * @param memoryPropertyFlags Memory properties for this buffer (i.e. device local, host visible, coherent)
         * @param buffer Pointer to a vk::Vulkan buffer object
         * @param size Size of the buffer in byes
         * @param data Pointer to the data that should be copied to the buffer after creation (optional, if not set, no data is copied over)
         *
         * @return VK_SUCCESS if buffer handle and memory have been created and (optionally passed) data has been copied
         */
        public VkResult createBuffer(VkBufferUsageFlags usageFlags, VkMemoryPropertyFlags memoryPropertyFlags, vksBuffer buffer, ulong size, void *data = null)
        {
            buffer.device = _logicalDevice;

            // Create the buffer handle
            VkBufferCreateInfo bufferCreateInfo = VkBufferCreateInfo.New();

            bufferCreateInfo.usage = usageFlags;
            bufferCreateInfo.size  = size;
            Util.CheckResult(vkCreateBuffer(_logicalDevice, &bufferCreateInfo, null, out buffer.buffer));

            // Create the memory backing up the buffer handle
            VkMemoryRequirements memReqs;
            VkMemoryAllocateInfo memAlloc = VkMemoryAllocateInfo.New();

            vkGetBufferMemoryRequirements(_logicalDevice, buffer.buffer, &memReqs);
            memAlloc.allocationSize = memReqs.size;
            // Find a memory type index that fits the properties of the buffer
            memAlloc.memoryTypeIndex = getMemoryType(memReqs.memoryTypeBits, memoryPropertyFlags);
            Util.CheckResult(vkAllocateMemory(_logicalDevice, &memAlloc, null, out buffer.memory));

            buffer.alignment           = memReqs.alignment;
            buffer.size                = memAlloc.allocationSize;
            buffer.usageFlags          = usageFlags;
            buffer.memoryPropertyFlags = memoryPropertyFlags;

            // If a pointer to the buffer data has been passed, map the buffer and copy over the data
            if (data != null)
            {
                Util.CheckResult(buffer.map());
                Unsafe.CopyBlock(buffer.mapped, data, (uint)size);
                buffer.unmap();
            }

            // Initialize a default descriptor that covers the whole buffer size
            buffer.setupDescriptor();

            // Attach the memory to the buffer object
            return(buffer.bind());
        }
Exemplo n.º 4
0
        public void AddNewFiles(VirtualCpk cpk)
        {
            var newFileCount = cpk.Entries.Where(x => x.PacIndex == Native.Header->Index)
                               .Max(x => x.FileIndex + 1);

            if (newFileCount > Entries.Count)
            {
                var oldHeaderSize = sizeof(DwPackHeader) + (Entries.Count * sizeof(DwPackEntry));
                var newHeaderSize = sizeof(DwPackHeader) + (newFileCount * sizeof(DwPackEntry));
                var oldNative     = Native;

                Native = new DwPackPtr((byte *)Marshal.AllocHGlobal(newHeaderSize));
                Unsafe.CopyBlock((void *)Native.Ptr, (void *)oldNative.Ptr, (uint)oldHeaderSize);
                Native.Header->FileCount = newFileCount;
                oldNative.Dispose();

                var dataOffset = Entries.Max(x => x.Native->DataOffset + x.Native->CompressedSize);
                for (int i = oldNative.Header->FileCount; i < Native.Header->FileCount; i++)
                {
                    var entry    = Native.Entries + i;
                    var cpkEntry = cpk.Entries.First(x => x.PacIndex == Native.Header->Index && x.FileIndex == i);

                    entry->Field00   = 0;
                    entry->Index     = (short)i;
                    entry->PackIndex = (short)Native.Header->Index;
                    entry->Path      = cpkEntry.Path;
                    entry->Field104  = 0;
                    entry->Flags     = 0;

                    // These will be filled in later
                    entry->CompressedSize = entry->UncompressedSize = 1;
                    entry->DataOffset     = dataOffset;
                    dataOffset           += entry->CompressedSize;
                }

                mMapper = new MemoryMapper();
                Entries.Clear();
                LoadEntries();
            }
        }
Exemplo n.º 5
0
        /// <summary>
        /// Function to convert an array into a <see cref="GorgonNativeBuffer{T}"/>.
        /// </summary>
        /// <typeparam name="T">The type of data in the array. Must be an unmanaged value type.</typeparam>
        /// <param name="array">The array to turn into a native buffer.</param>
        /// <param name="index">[Optional] The index in the array that represents the beginning of the native buffer.</param>
        /// <param name="count">[Optional] The number of items in the array that will be contained in the buffer.</param>
        /// <returns>A new <see cref="GorgonNativeBuffer{T}"/> containing the <paramref name="array"/> data.</returns>
        /// <exception cref="ArgumentNullException">Thrown when the <paramref name="array"/> parameter is <b>null</b>.</exception>
        /// <exception cref="ArgumentOutOfRangeException">Thrown when the <paramref name="index"/> is less than 0.</exception>
        /// <exception cref="ArgumentException">Thrown when the <paramref name="index"/> + <paramref name="count"/> are equal to or greater than the length of <paramref name="array"/>.</exception>
        /// <remarks>
        /// <para>
        /// This method copies the contents of an array into a <see cref="GorgonNativeBuffer{T}"/> so that the data can be used with native code.
        /// </para>
        /// <para>
        /// If the <paramref name="index"/> is not supplied, then the beginning of the <paramref name="array"/> is used as the start of the buffer, and if the <paramref name="count"/> parameter is not
        /// supplied, then the length of the <paramref name="array"/> (minus the <paramref name="index"/>) is used.
        /// </para>
        /// <para>
        /// <note type="warning">
        /// This method <b>copies</b> the data from the array into the buffer. This may have a negative impact on performance and memory usage.
        /// </note>
        /// </para>
        /// </remarks>
        public static GorgonNativeBuffer <T> ToNativeBuffer <T>(this T[] array, int index = 0, int?count = null)
            where T : unmanaged
        {
            if (count == null)
            {
                count = array.Length - index;
            }

            GorgonNativeBuffer <T> .ValidateArrayParams(array, index, count.Value);

            var result = new GorgonNativeBuffer <T>(count.Value);

            unsafe
            {
                fixed(T *srcPtr = &array[index])
                {
                    Unsafe.CopyBlock((T *)result, srcPtr, (uint)(Unsafe.SizeOf <T>() * count.Value));
                }
            }

            return(result);
        }
Exemplo n.º 6
0
        /// <summary>
        /// Function to copy the contents of an array into a <see cref="GorgonNativeBuffer{T}"/>.
        /// </summary>
        /// <typeparam name="T">The type of data in the array and buffer. Must be an unmanaged value type.</typeparam>
        /// <param name="array">The array to copy from.</param>
        /// <param name="buffer">The buffer that will receive the data.</param>
        /// <param name="arrayIndex">[Optional] The index in the array to start copying from.</param>
        /// <param name="count">[Optional] The number of items to copy.</param>
        /// <param name="bufferIndex">[Optional] The index in the buffer to start writing into.</param>
        /// <exception cref="ArgumentNullException">Thrown when the <paramref name="array"/>, or <paramref name="buffer"/> parameter is <b>null</b>.</exception>
        /// <exception cref="ArgumentOutOfRangeException">Thrown when the <paramref name="arrayIndex"/>, or the <paramref name="bufferIndex"/> parameter is less than 0.</exception>
        /// <exception cref="ArgumentException">
        /// <para>Thrown when the <paramref name="arrayIndex"/> + <paramref name="count"/> is too big for the <paramref name="array"/>.</para>
        /// <para>-or-</para>
        /// <para>Thrown when the <paramref name="bufferIndex"/> + <paramref name="count"/> is too big for the <paramref name="buffer"/>.</para>
        /// </exception>
        /// <remarks>
        /// <para>
        /// If the <paramref name="count"/> parameter is ommitted, then the full length of the source buffer, minus the <paramref name="arrayIndex"/> is used. Ensure that there is enough space in the
        /// <paramref name="buffer"/> to accomodate the amount of data required.
        /// </para>
        /// </remarks>
        public static void CopyTo <T>(this T[] array, GorgonNativeBuffer <T> buffer, int arrayIndex = 0, int?count = null, int bufferIndex = 0)
            where T : unmanaged
        {
            if (array == null)
            {
                throw new ArgumentNullException(nameof(array));
            }

            if (buffer == null)
            {
                throw new ArgumentNullException(nameof(buffer));
            }

            if (count == null)
            {
                count = array.Length - arrayIndex;
            }

            GorgonNativeBuffer <T> .ValidateArrayParams(array, arrayIndex, count.Value);

            if (bufferIndex < 0)
            {
                throw new ArgumentOutOfRangeException(nameof(bufferIndex), Resources.GOR_ERR_DATABUFF_OFFSET_TOO_SMALL);
            }

            if (bufferIndex + count.Value > buffer.Length)
            {
                throw new ArgumentException(string.Format(Resources.GOR_ERR_DATABUFF_SIZE_OFFSET_TOO_LARGE, bufferIndex, count));
            }

            unsafe
            {
                fixed(T *srcPtr = &array[arrayIndex])
                fixed(T * destPtr = &buffer[bufferIndex])
                {
                    Unsafe.CopyBlock(destPtr, srcPtr, (uint)count.Value);
                }
            }
        }
Exemplo n.º 7
0
        /// <summary>
        /// Function to copy the contents of this buffer into other.
        /// </summary>
        /// <param name="destination">The destination buffer that will receive the data.</param>
        /// <param name="sourceIndex">[Optional] The first index to start copying from.</param>
        /// <param name="count">[Optional] The number of items to copy.</param>
        /// <param name="destIndex">[Optional] The destination index in the destination buffer to start copying into.</param>
        /// <exception cref="ArgumentNullException">Thrown when the <paramref name="destination"/> parameter is <b>null</b>.</exception>
        /// <exception cref="ArgumentOutOfRangeException">Thrown when the <paramref name="sourceIndex"/>, or the <paramref name="destIndex"/> parameter is less than 0.</exception>
        /// <exception cref="ArgumentException">
        /// <para>Thrown when the <paramref name="sourceIndex"/> + <paramref name="count"/> is too big for this buffer.</para>
        /// <para>-or-</para>
        /// <para>Thrown when the <paramref name="destIndex"/> + <paramref name="count"/> is too big for the <paramref name="destination"/> buffer.</para>
        /// </exception>
        /// <remarks>
        /// <para>
        /// If the <paramref name="count"/> parameter is ommitted, then the full length of the source buffer, minus the <paramref name="sourceIndex"/> is used. Ensure that there is enough space in the
        /// <paramref name="destination"/> buffer to accomodate the amount of data required.
        /// </para>
        /// </remarks>
        public void CopyTo(GorgonNativeBuffer <T> destination, int sourceIndex = 0, int?count = null, int destIndex = 0)
        {
            if (destination == null)
            {
                throw new ArgumentNullException(nameof(destination));
            }

            if (sourceIndex < 0)
            {
                throw new ArgumentOutOfRangeException(nameof(sourceIndex), Resources.GOR_ERR_DATABUFF_OFFSET_TOO_SMALL);
            }

            if (destIndex < 0)
            {
                throw new ArgumentOutOfRangeException(nameof(destIndex), Resources.GOR_ERR_DATABUFF_OFFSET_TOO_SMALL);
            }

            if (count == null)
            {
                count = Length - sourceIndex;
            }

            if (count < 0)
            {
                throw new ArgumentOutOfRangeException(nameof(count), Resources.GOR_ERR_DATABUFF_SIZE_TOO_SMALL);
            }

            if (sourceIndex + count.Value > Length)
            {
                throw new ArgumentException(string.Format(Resources.GOR_ERR_DATABUFF_SIZE_OFFSET_TOO_LARGE, sourceIndex, count.Value));
            }

            if (destIndex + count.Value > destination.Length)
            {
                throw new ArgumentException(string.Format(Resources.GOR_ERR_DATABUFF_SIZE_OFFSET_TOO_LARGE, destIndex, count.Value));
            }

            Unsafe.CopyBlock(destination._memoryBlock + (destIndex * _typeSize), _memoryBlock + (sourceIndex * _typeSize), (uint)(count * _typeSize));
        }
Exemplo n.º 8
0
        public unsafe void SetData <T>(ref T data, int dataSizeInBytes, int destinationOffsetInBytes) where T : struct
        {
            if (destinationOffsetInBytes != 0)
            {
                throw new NotImplementedException();
            }

            if (_resourceUsage == ResourceUsage.Dynamic)
            {
                DataBox db = Device.ImmediateContext.MapSubresource(Buffer, 0, MapMode.WriteNoOverwrite, MapFlags.None);
                Unsafe.CopyBlock(
                    (byte *)db.DataPointer.ToPointer() + destinationOffsetInBytes,
                    Unsafe.AsPointer(ref data),
                    (uint)dataSizeInBytes);
                Device.ImmediateContext.UnmapSubresource(Buffer, 0);
            }
            else
            {
                EnsureBufferSize(dataSizeInBytes + destinationOffsetInBytes);
                Device.ImmediateContext.UpdateSubresource(ref data, Buffer);
            }
        }
Exemplo n.º 9
0
        /// <summary>
        /// 将一块内存转换为临时数组对象(非托管)。
        /// </summary>
        /// <typeparam name="T">元素类型</typeparam>
        /// <param name="address">内存地址</param>
        /// <param name="length">内存元素数量</param>
        /// <param name="starts">返回一个起始位置的内容备份,此实例长度加临时数组长度刚好等于元素数量</param>
        /// <returns>返回一个临时数组</returns>
        public static T[] AsTempOneRankValueArray <T>(void *address, int length, out T[] starts) where T : struct
        {
            if (!(IsSupportedOneRankValueArrayInfo && OneRankValueArrayInfo <T> .Available))
            {
                throw new PlatformNotSupportedException("This operation is not supported by the current platform.");
            }

            var startsLength = (OneRankValueArrayInfo <T> .ElementOffset + Unsafe.SizeOf <T>() - 1) / Unsafe.SizeOf <T>();

            if (length < startsLength)
            {
                throw new ArgumentException("Not enough length to store array information.", nameof(length));
            }

            starts = new T[startsLength];

            Unsafe.CopyBlock(
                ref Unsafe.As <T, byte>(ref starts[0]),
                ref Unsafe.AsRef <byte>(address),
                (uint)(startsLength * Unsafe.SizeOf <T>()));

            ref var pArray = ref Unsafe.AddByteOffset(
Exemplo n.º 10
0
    public static unsafe int Main()
    {
        byte *source = stackalloc byte[SIZE];
        byte *dest   = stackalloc byte[SIZE];

        for (int i = 0; i < SIZE; i++)
        {
            source[i] = (byte)(i % 255);
            dest[i]   = 0;
        }

        Unsafe.CopyBlock(dest, source, (uint)SIZE);

        bool result = true;

        for (int i = 0; i < SIZE; i++)
        {
            result &= (source[i] == dest[i]);
        }

        return(result ? 100 : -1);
    }
Exemplo n.º 11
0
            public unsafe void FillWithColor(GraphicsDevice d, System.Drawing.Color c, string name)
            {
                TextureDescription desc = new TextureDescription();

                desc.Width       = 1;
                desc.Height      = 1;
                desc.MipLevels   = 1;
                desc.SampleCount = TextureSampleCount.Count1;
                desc.ArrayLayers = 1;
                desc.Depth       = 1;
                desc.Type        = TextureType.Texture2D;
                desc.Usage       = TextureUsage.Staging;
                desc.Format      = PixelFormat.R8_G8_B8_A8_UNorm;
                _staging         = d.ResourceFactory.CreateTexture(desc);

                byte[] col = new byte[4];
                col[0] = c.R;
                col[1] = c.G;
                col[2] = c.B;
                col[3] = c.A;
                MappedResource map = d.Map(_staging, MapMode.Write, 0);

                fixed(void *data = col)
                {
                    Unsafe.CopyBlock(map.Data.ToPointer(), data, 4);
                }

                _pool.DescriptorTableDirty = true;

                Renderer.AddBackgroundUploadTask((gd, cl) =>
                {
                    desc.Usage    = TextureUsage.Sampled;
                    _texture      = d.ResourceFactory.CreateTexture(desc);
                    _texture.Name = name;
                    cl.CopyTexture(_staging, _texture);
                    Resident = true;
                    _pool.DescriptorTableDirty = true;
                });
            }
Exemplo n.º 12
0
            public static unsafe byte[]? GetGrayScaleValues(Bitmap original, double darkProcent = 80)
            {
                // Lock the bitmap's bits.
                Rectangle  rect    = new Rectangle(0, 0, original.Width, original.Height);
                BitmapData bmpData = original.LockBits(rect, ImageLockMode.ReadOnly, original.PixelFormat);

                // Get the address of the first line.
                IntPtr ptr = bmpData.Scan0;

                // Declare an array to hold the bytes of the bitmap.
                int bytes = bmpData.Stride * original.Height;

                byte[] rgbValues = new byte[bytes];
                byte[] buffer    = new byte[256];

                // Copy the RGB values into the array.
                fixed(byte *byteArrayPtr = rgbValues)
                {
                    Unsafe.CopyBlock(byteArrayPtr, (void *)ptr, (uint)rgbValues.Length);
                }

                original.UnlockBits(bmpData);

                int count = 0, all = bmpData.Width * bmpData.Height;
                int buffercounter = 0;

                for (int i = 0; i < rgbValues.Length; i += 4)
                {
                    byte r = rgbValues[i + 2], g = rgbValues[i + 1], b = rgbValues[i];
                    buffer[buffercounter] = r;
                    buffercounter++;
                    byte brightness = (byte)Math.Round(0.299 * r + 0.5876 * g + 0.114 * b);
                    if (brightness <= 0x20)
                    {
                        count++;
                    }
                }
                return(100d / all * count >= darkProcent ? null : buffer);
            }
Exemplo n.º 13
0
        public unsafe static Bitmap ToBitmap(ImageGrid grid)
        {
            grid.EnsureNotDisposed();

            var bitmap = new Bitmap(grid.Width, grid.Height, PixelFormat.Format32bppArgb);
            var bounds = new Rectangle(0, 0, grid.Width, grid.Height);
            var data   = bitmap.LockBits(bounds, ImageLockMode.WriteOnly, PixelFormat.Format32bppRgb);

            try
            {
                fixed(byte *inputPtr = &Unsafe.As <RgbColor, byte>(ref grid._data[0]))
                {
                    Unsafe.CopyBlock(data.Scan0.ToPointer(), inputPtr, (uint)(data.Stride * data.Height));
                }
            }
            finally
            {
                bitmap.UnlockBits(data);
            }

            return(bitmap);
        }
Exemplo n.º 14
0
        /// <summary>
        /// Calculates the transaction id of a signed transaction. Will throw an exception when the transaction
        /// is not signed. The id is not needed to submit a transaction but can be useful when transactions
        /// depend on each other.
        /// </summary>
        /// <param name="rawTransaction">The RawTransaction for which the id needs to be calculated.</param>
        /// <param name="signer">The address of the signer.</param>
        /// <returns>The RawTransaction with the calculated id.</returns>
        public static RawTransaction CalculateTxId(this RawTransaction rawTransaction, Address signer)
        {
            if (rawTransaction.signature == null)
            {
                throw new ArgumentException("transaction is not singed");
            }

            // Hash the RLP encoded transaction
            var signingHash    = Hash.HashBlake2B(rawTransaction.Encode());
            var signingAddress = signer.HexString.HexStringToByteArray();

            byte[] concatenatedBytes = new byte[52];
            Unsafe.CopyBlock(ref concatenatedBytes[0], ref signingHash[0], (uint)signingHash.Length);
            //Array.Copy(signingHash,    0, concatenatedBytes, 0, signingHash.Length);
            Unsafe.CopyBlock(ref concatenatedBytes[signingHash.Length], ref signingAddress[0], (uint)signingAddress.Length);
            //Array.Copy(signingAddress, 0, concatenatedBytes, signingHash.Length, signingAddress.Length);

            // Hash the bytes from the signed transaction and the signer address
            byte[] txIdBytes = Hash.HashBlake2B(concatenatedBytes);
            rawTransaction.id = txIdBytes.ByteArrayToString(StringType.Hex | StringType.ZeroLowerX);
            return(rawTransaction);
        }
Exemplo n.º 15
0
        private void WriteStringSlow(string input, uint byteCount, uint allowed)
        {
            if (input.Length >= 2048)
            {
                Flush();
                fixed(void *s = input)
                {
                    _target.Write(new ReadOnlySpan <byte>(s, (int)byteCount));
                    return;
                }
            }

            uint sourcePosition = 0;

            fixed(void *text = input)
            {
                do
                {
                    if (byteCount > allowed)
                    {
                        Unsafe.CopyBlock(Unsafe.Add <byte>(_bufferPtr, (int)_bufferPosition), Unsafe.Add <byte>(text, (int)sourcePosition), allowed);
                        byteCount       -= allowed;
                        _bufferPosition += allowed;
                        sourcePosition  += allowed;
                        if (!Flush())
                        {
                            ThrowFailedStream();
                        }
                    }
                    else
                    {
                        Unsafe.CopyBlock(Unsafe.Add <byte>(_bufferPtr, (int)_bufferPosition), Unsafe.Add <byte>(text, (int)sourcePosition), byteCount);
                        _bufferPosition += byteCount;
                        byteCount        = 0;
                    }
                    allowed = (uint)(_size - _bufferPosition);
                } while (byteCount > 0);
            }
        }
Exemplo n.º 16
0
        /// <summary>
        /// Gets matrix after tensor product of two vectors
        /// </summary>
        /// <param name="va">the left vector</param>
        /// <param name="vb">the right vector(transpose)</param>
        /// <typeparam name="T">unmanaged type</typeparam>
        /// <returns><see cref="Matrix{T}"/></returns>
        /// <exception cref="MatrixDotNetException">left vector is not equal right</exception>
        public static unsafe Matrix <T> TensorProduct <T>(Vector <T> va, Vector <T> vb)
            where T : unmanaged
        {
            int n = va.Length;

            if (n != vb.Length)
            {
                throw new MatrixDotNetException("vector length is not equal");
            }

            int size           = System.Numerics.Vector <T> .Count;
            var mr             = new Matrix <T>(n, n);
            int lastIndexBlock = n - n % size;
            int j = 0;

            fixed(T *ptr = mr._Matrix)
            {
                for (int i = 0; i < mr.Rows; i++)
                {
                    for (j = 0; j < lastIndexBlock; j += size)
                    {
                        var vd  = new System.Numerics.Vector <T>(vb.Array, j);
                        var vc  = Vector.Multiply(va[i], vd);
                        var res = (T *)Unsafe.AsPointer(ref vc);
                        Unsafe.CopyBlock(ptr + i * mr.Columns + j, res, (uint)(sizeof(T) * size));
                    }
                }

                for (int i = 0; i < mr.Rows; i++)
                {
                    for (int k = j; k < n; k++)
                    {
                        mr[i, k] = MathUnsafe <T> .Mul(va[i], vb[k]);
                    }
                }
            }

            return(mr);
        }
Exemplo n.º 17
0
        /// <summary>
        /// Initializes a new instance of the <see cref="NativeStack{T}"/> struct.
        /// </summary>
        /// <param name="elements">The initial elements.</param>
        /// <param name="allocator">The allocator.</param>
        public NativeStack(Span <int> elements, Allocator allocator)
        {
            if (Allocator.IsCached(allocator) is false)
            {
                throw new ArgumentException("Allocator is not in cache.", nameof(allocator));
            }

            if (elements.IsEmpty)
            {
                this = default;
            }
            else
            {
                _buffer      = allocator.Allocate <T>(elements.Length);
                _capacity    = elements.Length;
                _count       = _capacity;
                _allocatorID = allocator.ID;

                void *source = Unsafe.AsPointer(ref MemoryMarshal.GetReference(elements));
                Unsafe.CopyBlock(_buffer, source, (uint)(sizeof(T) * _capacity));
            }
        }
Exemplo n.º 18
0
        public int SyncrhonizeInputs(ref byte[] values)
        {
            int disconnect_flags = 0;

            Debug.Assert(values.Length >= config.numPlayers * config.inputSize);

            Unsafe.InitBlock(ref values[0], 0, (uint)values.Length);
            for (int i = 0; i < config.numPlayers; i++)
            {
                var input = new GameInput(GameInput.NullFrame, null, (uint)config.inputSize);
                if (localConnectStatus[i].Disconnected && FrameCount > localConnectStatus[i].LastFrame)
                {
                    disconnect_flags |= (1 << i);
                }
                else
                {
                    inputQueues[i].GetInput(FrameCount, ref input);
                }
                Unsafe.CopyBlock(ref values[i * config.inputSize], ref input.bits[0], (uint)config.inputSize);
            }
            return(disconnect_flags);
        }
Exemplo n.º 19
0
        /// <summary>
        /// Loads all the captured variables from a given closure class and returns them as a <see cref="ClosureData"/> instance
        /// </summary>
        /// <param name="instance">The input <see cref="Delegate"/> instance to load data from</param>
        /// <returns>A <see cref="ClosureData"/> instance with the captured data</returns>
        public unsafe ClosureData GetData(Delegate instance)
        {
            object[] references = ArrayPool <object> .Shared.Rent(ReferenceCount);

            byte[] bytes = ArrayPool <byte> .Shared.Rent(ByteSize);

            int
                referenceOffset = 0, // Offset into the references array
                byteOffset      = 0; // Offset into the bytes array

            for (int i = 0; i < Fields.Count; i++)
            {
                ClosureFieldWithGetter field = Fields[i];

                // Traverse the parents hierarchy
                object target = instance.Target;
                for (int j = 0; j < field.Parents.Count; j++)
                {
                    target = field.Parents[j].Getter(target);
                }
                object value = field.Getter(target);

                // We need to handle value types and objects differently
                if (field.Info.FieldType.IsValueType)
                {
                    // Pin the boxed value and get the source and destination references
                    GCHandle handle      = GCHandle.Alloc(value, GCHandleType.Pinned);
                    void *   p           = handle.AddrOfPinnedObject().ToPointer();
                    ref byte source      = ref Unsafe.AsRef <byte>(p);
                    ref byte destination = ref Unsafe.Add(ref bytes[0], byteOffset);
                    int      size        = Marshal.SizeOf(field.Info.FieldType);

                    // Copy the raw data of the value type into our bytes buffer
                    Unsafe.CopyBlock(ref destination, ref source, (uint)size);
                    byteOffset += size;

                    handle.Free(); // Do NOT forget to do this
                }
Exemplo n.º 20
0
        public static unsafe void WriteChars(TextWriter textWriter, char *chars, int length)
        {
#if NETCOREAPP && !NETCOREAPP2_0
            textWriter.Write(new ReadOnlySpan <char>(chars, length));
#else
            if (length > 130 && ArrayHelper.IsSupportedOneRankValueArrayInfo)
            {
                var ends = ArrayHelper.AsTempOneRankValueArray <char>(chars, length, out var starts);

                textWriter.Write(starts);

                textWriter.Write(ends);

                Unsafe.CopyBlock(
                    ref Unsafe.As <char, byte>(ref chars[0]),
                    ref Unsafe.As <char, byte>(ref starts[0]),
                    (uint)(starts.Length * sizeof(char)));
            }
            else
            {
                const int bufferLength = 128;

                var buffer = new char[Math.Min(bufferLength, length)];

                for (int index = 0, count = buffer.Length;
                     index < length;
                     index += count, count = Math.Min(buffer.Length, length - index))
                {
                    Unsafe.CopyBlock(
                        ref Unsafe.As <char, byte>(ref buffer[0]),
                        ref Unsafe.As <char, byte>(ref chars[index]),
                        (uint)(count * sizeof(char)));

                    textWriter.Write(buffer, 0, count);
                }
            }
#endif
        }
Exemplo n.º 21
0
        public static unsafe void WriteBytes(Stream stream, byte *bytes, int length)
        {
#if NETCOREAPP && !NETCOREAPP2_0
            stream.Write(new ReadOnlySpan <byte>(bytes, length));
#else
            if (length > 130 && ArrayHelper.IsSupportedOneRankValueArrayInfo)
            {
                var ends = ArrayHelper.AsTempOneRankValueArray <byte>(bytes, length, out var starts);

                stream.Write(starts, 0, starts.Length);

                stream.Write(ends, 0, ends.Length);

                Unsafe.CopyBlock(
                    ref bytes[0],
                    ref starts[0],
                    (uint)starts.Length);
            }
            else
            {
                const int bufferLength = 128;

                var buffer = new byte[Math.Min(bufferLength, length)];

                for (int index = 0, count = buffer.Length;
                     index < length;
                     index += count, count = Math.Min(buffer.Length, length - index))
                {
                    Unsafe.CopyBlock(
                        ref buffer[0],
                        ref bytes[index],
                        (uint)count);

                    stream.Write(buffer, 0, count);
                }
            }
#endif
        }
Exemplo n.º 22
0
        public int Write(byte *p, int count)
        {
            var wrote = 0;

            do
            {
                var length = Math.Min(_dataCapacity - _position, count);
                Unsafe.CopyBlock(_dataBuffer.Ptr, p, (uint)length);

                _position += length;
                p         += length;
                count     -= length;
                wrote     += length;

                if (_dataCapacity - _position == 0)
                {
                    WriteToUnderlying();
                }
            } while (count > 0);

            _length = _position;
            return(wrote);
        }
Exemplo n.º 23
0
        public unsafe byte[] ToStructure()
        {
            var result = new byte[dwSizeHid * dwCount + sizeof(int) * 2];

            fixed(byte *resultPtr = result)
            {
                var intPtr = (int *)resultPtr;

                intPtr[0] = dwSizeHid;
                intPtr[1] = dwCount;

                fixed(byte *rawDataPtr = rawData)
                {
#if NET45
                    Unsafe.CopyBlock(rawDataPtr, &intPtr[2], (uint)rawData.Length);
#else
                    Buffer.MemoryCopy(rawDataPtr, &intPtr[2], rawData.Length, rawData.Length);
#endif
                }
            }

            return(result);
        }
Exemplo n.º 24
0
        private unsafe void ImplSubmit()
        {
            var vertex_buffer = new TransientVertexBuffer(vertex_index, Vertex2DLayout);

            fixed(void *v = vertices)
            {
                Unsafe.CopyBlock((void *)vertex_buffer.Data, v, (uint)(vertex_index * Vertex2D.Stride));
            }

            Bgfx.SetTexture(0, current_shader_program.Samplers[0], current_texture.Texture, current_texture.TexFlags);

            Bgfx.SetRenderState(render_state);

            Bgfx.SetIndexBuffer(index_buffer, 0, vertex_index / 4 * 6);

            Bgfx.SetVertexBuffer(0, vertex_buffer, 0, vertex_index);

            current_shader_program.SubmitValues();

            Bgfx.SetViewMode(current_render_pass, ViewMode.Sequential);

            Bgfx.Submit(current_render_pass, current_shader_program.Program);
        }
Exemplo n.º 25
0
        public static byte[] FirstBytes(this byte[] buffer, uint length)
        {
            if (buffer.Length < length)
            {
                throw new ArgumentOutOfRangeException(nameof(length), "Length must be greater than length of buffer.");
            }

            if (buffer.Length == 0)
            {
                return(Array.Empty <byte>());
            }

            if (buffer.Length == length)
            {
                return(buffer);
            }

            var bytes = new byte[length];

            Unsafe.CopyBlock(ref bytes[0], ref buffer[0], length);

            return(bytes);
        }
Exemplo n.º 26
0
        public void WriteBytes(byte[] buffer, int start, int length)
        {
            if (buffer == null)
            {
                throw new ArgumentNullException();
            }

            if (start < 0 || length <= 0)
            {
                throw new ArgumentOutOfRangeException();
            }

            if (buffer.Length < start || start + length > buffer.Length)
            {
                throw new ArgumentOutOfRangeException();
            }

            var idx = Advance(length);

            fixed(byte *src = buffer)
            fixed(byte *dst = m_buffer)
            Unsafe.CopyBlock(dst + idx, src + start, (uint)length);
        }
Exemplo n.º 27
0
        /// <summary>
        /// Copies initial Blowfish state (P and S boxes) to the current instance.
        /// </summary>
        private void InitializeState()
        {
            const uint PSizeInBytes = PSize * sizeof(uint);
            const uint SSizeInBytes = SSize * sizeof(uint);

            unsafe
            {
                fixed(BlowfishState *pState = &m_state)
                fixed(uint *pPInit  = PInit)
                fixed(uint *pS0Init = S0Init)
                fixed(uint *pS1Init = S1Init)
                fixed(uint *pS2Init = S2Init)
                fixed(uint *pS3Init = S3Init)
                {
                    // assume compiler can take care of alignment required
                    Unsafe.CopyBlock(pState->P, pPInit, PSizeInBytes);
                    Unsafe.CopyBlock(pState->S0, pS0Init, SSizeInBytes);
                    Unsafe.CopyBlock(pState->S1, pS1Init, SSizeInBytes);
                    Unsafe.CopyBlock(pState->S2, pS2Init, SSizeInBytes);
                    Unsafe.CopyBlock(pState->S3, pS3Init, SSizeInBytes);
                }
            }
        }
Exemplo n.º 28
0
        public unsafe void Double()
        {
            var srcPtr = stackalloc double[SourceSize];
            var dstPtr = stackalloc double[DestinationSize];

            for (int i = 0; i < SourceSize - 2; i++)
            {
                srcPtr[i] = 42;
            }

            var dstPtrOffset = dstPtr + Offset;

            Unsafe.CopyBlock(dstPtrOffset, srcPtr, SourceFilledSize * sizeof(double));

            for (int i = 0; i < Offset; i++)
            {
                Assert.Equal(0, dstPtr[i]);
            }
            for (int i = Offset; i < DestinationSize; i++)
            {
                Assert.Equal(42, dstPtr[i]);
            }
        }
Exemplo n.º 29
0
        unsafe void Write(ReadOnlySpan <byte> buffer)
        {
            ValidateDisposed();
            ValidateSpan(buffer, nameof(buffer));
            var count = buffer.Length;

            if (count == 0)
            {
                return;
            }

            var maxCount = _capacity - _offset;

            if (count > maxCount)
                throw new IOException("Not enough capacity to consume write.");

            fixed(byte *pBuf = buffer)
            Unsafe.CopyBlock(_pointer + _offset, pBuf, (uint)count);

            _offset += count;

            _length = Math.Max(_length, _offset);
        }
Exemplo n.º 30
0
        internal void Init(int digestLength, ProtectedMemory key)
        {
            uint keyLength = key == null ? 0u : (uint)(key?.ContentLength);

            hHash = Marshal.AllocHGlobal(HashSize);
            hash  = (ulong *)hHash;

            hBlock = Marshal.AllocHGlobal(BlockSize);
            block  = (byte *)hBlock;

            if (digestLength == 0 || (uint)digestLength > HashSize)
            {
                throw new ArgumentOutOfRangeException(nameof(digestLength), "Value must be between 1 and " + HashSize);
            }
            if (keyLength > MaxKeyBytes)
            {
                throw new ArgumentException("Key must be between 0 and " + MaxKeyBytes + " bytes in length", nameof(key));
            }

            outlen = (uint)digestLength;
            fixed(byte *pIv = iv)
            {
                Unsafe.CopyBlock(hash, pIv, HashSize);
            }

            hash[0] ^= 0x01010000u ^ (keyLength << 8) ^ outlen;

            if (keyLength != 0)
            {
                MarshalExtensions.ZeroMemory(hBlock, BlockSize);
                using (ProtectedMemoryAccess access = new ProtectedMemoryAccess(key))
                {
                    Unsafe.CopyBlockUnaligned(block, (byte *)access.Handle, keyLength);
                }
                c = BlockSize;
            }
        }