예제 #1
0
        /// <inheritdoc/>
        public override IMemoryOwner <T> Rent(int minBufferSize = -1)
        {
            if (minBufferSize == -1)
            {
                minBufferSize = DefaultMinBufferSize;
            }

            var oldHead = _head;

            var memBlock = Memory <T> .Empty;

            if (minBufferSize > 0)
            {
                ThrowForBadAlloc(minBufferSize);
                memBlock = _isPrePinned
                    ? MemoryMarshal.CreateFromPinnedArray(_pool, oldHead, minBufferSize)
                    : new Memory <T>(_pool, _head, minBufferSize);
            }

            _head += minBufferSize;

            // https://github.com/dotnet/csharplang/issues/3445
            // removes boxing here
            return(new StackMemoryOwner(memBlock, oldHead));
        }
        public static void CreateFromPinnedArrayWithStartAndLengthRangeExtendsToEndOfArray()
        {
            long[]        a            = { 90, 91, 92, 93, 94, 95, 96, 97, 98 };
            Memory <long> pinnedMemory = MemoryMarshal.CreateFromPinnedArray(a, 4, 5);

            pinnedMemory.Validate(94, 95, 96, 97, 98);
        }
예제 #3
0
        public async Task <Result <IRetrievedMessages> > GetMessages(TimeSpan visibilityTimeout, CancellationToken ct)
        {
            var seconds = GetTimeout(visibilityTimeout);

            using (var http = GetClient())
            {
                var url = messageUriWithSas + "&numofmessages=32&visibilitytimeout=" + seconds;

                using (var response = await http.GetAsync(url, ct).ConfigureAwait(false))
                {
                    if (response.StatusCode == HttpStatusCode.OK)
                    {
                        var bytes = GetPinnedBytes();
                        using (var stream = new MemoryStream(bytes))
                        {
                            await response.Content.CopyToAsync(stream).ConfigureAwait(false);

                            var messages = FastXmlAzureParser.ParseGetMessages(MemoryMarshal.CreateFromPinnedArray(bytes, 0, (int)stream.Position));

                            return(new Result <IRetrievedMessages>(response.StatusCode, new RetrievedMessages(messages, bytes, this)));
                        }
                    }

                    return(new Result <IRetrievedMessages>(response));
                }
            }
        }
        public static void CreateFromPinnedArrayIntReadOnlyMemorySliceRemainsPinned()
        {
            int[] a = { 90, 91, 92, 93, 94, 95, 96, 97, 98 };
            ReadOnlyMemory <int> pinnedMemory = MemoryMarshal.CreateFromPinnedArray(a, 3, 5);

            pinnedMemory.Validate(93, 94, 95, 96, 97);

            ReadOnlyMemory <int> slice     = pinnedMemory.Slice(0);
            TestMemory <int>     testSlice = Unsafe.As <ReadOnlyMemory <int>, TestMemory <int> >(ref slice);

            Assert.Equal(3 | (1 << 31), testSlice._index);
            Assert.Equal(5, testSlice._length);

            slice     = pinnedMemory.Slice(0, pinnedMemory.Length);
            testSlice = Unsafe.As <ReadOnlyMemory <int>, TestMemory <int> >(ref slice);
            Assert.Equal(3 | (1 << 31), testSlice._index);
            Assert.Equal(5, testSlice._length);

            slice     = pinnedMemory.Slice(1);
            testSlice = Unsafe.As <ReadOnlyMemory <int>, TestMemory <int> >(ref slice);
            Assert.Equal(4 | (1 << 31), testSlice._index);
            Assert.Equal(4, testSlice._length);

            slice     = pinnedMemory.Slice(1, 2);
            testSlice = Unsafe.As <ReadOnlyMemory <int>, TestMemory <int> >(ref slice);
            Assert.Equal(4 | (1 << 31), testSlice._index);
            Assert.Equal(2, testSlice._length);
        }
        public static void CreateFromPinnedArrayLong()
        {
            long[]        a            = { 90, 91, 92, 93, 94, 95, 96, 97, 98 };
            Memory <long> pinnedMemory = MemoryMarshal.CreateFromPinnedArray(a, 4, 3);

            pinnedMemory.Validate(94, 95, 96);
        }
        public static void CreateFromPinnedArrayString()
        {
            string[]        a            = { "90", "91", "92", "93", "94", "95", "96", "97", "98" };
            Memory <string> pinnedMemory = MemoryMarshal.CreateFromPinnedArray(a, 4, 3);

            pinnedMemory.Validate("94", "95", "96");
        }
예제 #7
0
        public static unsafe void CreateFromPinnedArrayIntReadOnlyMemorySliceRemainsPinned()
        {
            int[] a = { 90, 91, 92, 93, 94, 95, 96, 97, 98 };
            ReadOnlyMemory <int> pinnedMemory = MemoryMarshal.CreateFromPinnedArray(a, 3, 5);

            pinnedMemory.Validate(93, 94, 95, 96, 97);

            TestMemory <int> testPinnedMemory = Unsafe.As <ReadOnlyMemory <int>, TestMemory <int> >(ref pinnedMemory);

            ReadOnlyMemory <int> slice     = pinnedMemory.Slice(0);
            TestMemory <int>     testSlice = Unsafe.As <ReadOnlyMemory <int>, TestMemory <int> >(ref slice);

            Assert.Equal(testPinnedMemory._index, testSlice._index);
            Assert.Equal(testPinnedMemory._length, testSlice._length);

            slice     = pinnedMemory.Slice(0, pinnedMemory.Length);
            testSlice = Unsafe.As <ReadOnlyMemory <int>, TestMemory <int> >(ref slice);
            Assert.Equal(testPinnedMemory._index, testSlice._index);
            Assert.Equal(testPinnedMemory._length, testSlice._length);

            int expectedLength = testPinnedMemory._length - 1;

            slice     = pinnedMemory.Slice(1);
            testSlice = Unsafe.As <ReadOnlyMemory <int>, TestMemory <int> >(ref slice);
            Assert.Equal(testPinnedMemory._index + 1, testSlice._index);
            Assert.Equal(expectedLength, testSlice._length);

            expectedLength = 2 | (1 << 31);
            slice          = pinnedMemory.Slice(1, 2);
            testSlice      = Unsafe.As <ReadOnlyMemory <int>, TestMemory <int> >(ref slice);
            Assert.Equal(testPinnedMemory._index + 1, testSlice._index);
            Assert.Equal(expectedLength, testSlice._length);
        }
        public static void CreateFromPinnedArrayInt()
        {
            int[]        a            = { 90, 91, 92, 93, 94, 95, 96, 97, 98 };
            Memory <int> pinnedMemory = MemoryMarshal.CreateFromPinnedArray(a, 3, 2);

            pinnedMemory.Validate(93, 94);
        }
        public static void CreateFromPinnedArrayZeroLength()
        {
            int[]        empty  = Array.Empty <int>();
            Memory <int> memory = MemoryMarshal.CreateFromPinnedArray(empty, 0, empty.Length);

            memory.Validate();
        }
예제 #10
0
        internal MemoryPoolBlock(SlabMemoryPool pool, int length)
        {
            Pool = pool;

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

            Memory = MemoryMarshal.CreateFromPinnedArray(pinnedArray, 0, pinnedArray.Length);
        }
예제 #11
0
        /// <summary>
        /// This object cannot be instantiated outside of the static Create method
        /// </summary>
        internal MemoryPoolBlock(SlabMemoryPool pool, MemoryPoolSlab slab, int offset, int length)
        {
            _offset = offset;
            _length = length;

            Pool = pool;
            Slab = slab;

            Memory = MemoryMarshal.CreateFromPinnedArray(slab.Array, _offset, _length);
        }
예제 #12
0
        public Visiting()
        {
            var payload = new byte[]
            {
                1, 13,
                /*->*/ 3, 0, 4, 1, 1
            };

            gcHandle = GCHandle.Alloc(payload, GCHandleType.Pinned);
            memory   = MemoryMarshal.CreateFromPinnedArray(payload, 0, payload.Length);
        }
예제 #13
0
            public MemoryHolder(Sally7MemoryPool pool, int bufferSize)
            {
                _pool = pool;

#if NET5_0_OR_GREATER
                // Allocate a pinned buffer in the special pinned object heap (POH).
                // This avoids the need to pin this buffer in the socket implementation.
                byte[] arr = GC.AllocateUninitializedArray <byte>(bufferSize, pinned: true);
                Memory = MemoryMarshal.CreateFromPinnedArray(arr, 0, arr.Length);
#else
                Memory = new byte[bufferSize];
#endif
            }
        public static void CreateFromPinnedArrayNullArray()
        {
            Memory <int> memory = MemoryMarshal.CreateFromPinnedArray((int[])null, 0, 0);

            memory.Validate();
            Assert.Equal(default, memory);
예제 #15
0
    public Skeleton(ReadOnlyMemory <byte> memory)
    {
        using (var stream = CreateStream(memory))
        {
            var reader = new BinaryReader(stream);

            var boneCount     = reader.ReadInt32();
            var boneDataStart = reader.ReadInt32();
            reader.ReadInt32(); // Formerly variationCount
            reader.ReadInt32(); // Formerly variationDataStart
            var animationCount     = reader.ReadInt32();
            var animationDataStart = reader.ReadInt32();

            stream.Seek(boneDataStart, SeekOrigin.Begin);
            var bones = new List <SkeletonBone>(boneCount);
            for (var i = 0; i < boneCount; i++)
            {
                var flags       = reader.ReadInt16();
                var parentId    = reader.ReadInt16();
                var name        = reader.ReadFixedString(48);
                var scale       = reader.ReadVector4();
                var rotation    = reader.ReadVector4();
                var translation = reader.ReadVector4();

                var bone = new SkeletonBone
                {
                    Flags        = flags,
                    ParentId     = parentId,
                    Name         = name,
                    InitialState = new SkelBoneState
                    {
                        Scale       = new Vector3(scale.X, scale.Y, scale.Z),
                        Rotation    = new Quaternion(rotation.X, rotation.Y, rotation.Z, rotation.W),
                        Translation = new Vector3(translation.X, translation.Y, translation.Z)
                    }
                };
                // Flip axes for root bones
                //if (bone.ParentId == -1)
                //{
                //    bone.InitialState = bone.InitialState.WithSwappedAxes();
                //}

                bones.Add(bone);
            }

            Bones = bones;

            stream.Seek(animationDataStart, SeekOrigin.Begin);

            Span <int> animDataStarts = stackalloc int[animationCount];
            Animations = new List <SkeletonAnimation>(animationCount);
            var streamStartOffsets = new HashSet <int>();
            for (var i = 0; i < animationCount; i++)
            {
                animDataStarts[i] = (int)stream.Position;

                var animation = new SkeletonAnimation
                {
                    Name      = reader.ReadFixedString(64),
                    DriveType = (SkelAnimDriver)reader.ReadByte(),
                    Loopable  = reader.ReadBoolean()
                };

                var eventCount  = reader.ReadUInt16();
                var eventOffset = reader.ReadUInt32();

                // Read the events (but we need to seek for this)
                if (eventCount > 0)
                {
                    var posAfterEvents = stream.Position;
                    stream.Position = animDataStarts[i] + eventOffset;

                    var events = new SkelAnimEvent[eventCount];
                    for (var j = 0; j < events.Length; j++)
                    {
                        events[j] = new SkelAnimEvent
                        {
                            Frame  = reader.ReadUInt16(),
                            Type   = reader.ReadFixedString(48),
                            Action = reader.ReadFixedString(128)
                        };
                    }

                    stream.Position  = posAfterEvents;
                    animation.Events = events;
                }
                else
                {
                    animation.Events = Array.Empty <SkelAnimEvent>();
                }

                var streamCount = reader.ReadUInt16();
                reader.ReadUInt16(); // Unknown value (padding most likely)

                var streams = new SkelAnimStream[10];
                var mem     = MemoryMarshal.CreateFromPinnedArray(streams, 0, streams.Length);

                var byteSpan = MemoryMarshal.Cast <SkelAnimStream, byte>(mem.Span);
                reader.Read(byteSpan);
                if (streamCount == 0)
                {
                    streams = new SkelAnimStream[0];
                }
                else
                {
                    Array.Resize(ref streams, streamCount);
                }

                foreach (var animStream in streams)
                {
                    streamStartOffsets.Add(animDataStarts[i] + animStream.DataOffset);
                }

                animation.Streams = streams;


                Animations.Add(animation);
            }

            // Key frame data is contiguous in the file until the end of the file
            var sortedKeyFrameDataStart  = streamStartOffsets.ToImmutableSortedSet().ToArray();
            var sortedKeyFrameDataLength = sortedKeyFrameDataStart.Select((start, idx) =>
            {
                if (idx + 1 < sortedKeyFrameDataStart.Length)
                {
                    return(sortedKeyFrameDataStart[idx + 1] - start);
                }

                return(memory.Length - start);
            }).ToArray();

            _animationsByName = new Dictionary <string, SkeletonAnimation>(Animations.Count);
            for (var i = 0; i < animationCount; i++)
            {
                var anim = Animations[i];
                anim.StreamData    = new ReadOnlyMemory <byte> [anim.Streams.Length];
                anim.StreamDataIds = new int[anim.Streams.Length];
                for (var j = 0; j < anim.Streams.Length; j++)
                {
                    var dataStart    = animDataStarts[i] + anim.Streams[j].DataOffset;
                    var dataStartIdx = Array.BinarySearch(sortedKeyFrameDataStart, dataStart);
                    var dataLength   = sortedKeyFrameDataLength[dataStartIdx];
                    anim.StreamDataIds[j] = dataStart;
                    anim.StreamData[j]    = memory.Slice(dataStart, dataLength);
                }

                _animationsByName[anim.Name.ToLowerInvariant()] = anim;
            }
        }
    }
 protected internal sealed override Memory <byte> _GetMemory(int index, int count)
 {
     return(MemoryMarshal.CreateFromPinnedArray(Memory, Idx(index), count));
 }
 protected internal sealed override ReadOnlySequence <byte> _GetSequence(int index, int count)
 {
     return(new ReadOnlySequence <byte>(MemoryMarshal.CreateFromPinnedArray(Memory, Idx(index), count)));
 }