Beispiel #1
0
        void OnReadUnix(UVBuffer.Unix buffer, IntPtr bytesAvaliable)
        {
            long bytesRead = bytesAvaliable.ToInt64();

            if (bytesRead == 0)
            {
                return;
            }
            else if (bytesRead < 0)
            {
                var error = UVException.ErrorCodeToError((int)bytesRead);
                if (error == UVError.EOF)
                {
                    OnEndOfStream();
                    Dispose();
                }
                else
                {
                    Dispose();
                    throw new UVException((int)bytesRead);
                }
            }
            else
            {
                // This can be a Span<byte> but the samples pass it directly to TryWrite which
                // needs to unpack the data and turn it back into either an array or native memory
                var readSlice = new UnsafeMemory <byte>((byte *)buffer.Buffer, (int)bytesRead);
                OnReadCompleted(readSlice);
                buffer.Dispose();
            }
        }
Beispiel #2
0
        protected override unsafe void Execute(Action <IntPtr, IntPtr, UIntPtr> fn, out string result, out string expected)
        {
            const int cnt = 17;

            var d = new uint[] { 0x00000000, 0x10101010, 0x20100804, 0x30200003, 0x40204040, 0x5000004D, 0x60302E2C, 0x706F6E6D, 0x807F4F2F, 0x90349001, 0xA0010203, 0xB03204AB, 0xC023AFBD, 0xD0D0D0C0, 0xE0AABBCC, 0xFFFFFFFF, 0xF8F4F2F1 };
            var s = new uint[] { 0xE0E0E0E0, 0xA0008080, 0x341F1E1A, 0xFEFEFEFE, 0x80302010, 0x49490A0B, 0x998F7798, 0x00000000, 0x01010101, 0xA0264733, 0xBAB0B1B9, 0xFF000000, 0xDAB0A0C1, 0xE0BACFDA, 0x99887766, 0xFFFFFF80, 0xEE0A5FEC };

            var rawptr = Marshal.AllocHGlobal((cnt + 3) * sizeof(uint) + 8);
            var pdst   = new IntPtr(16 * (((long)rawptr + 15) / 16));

            rawptr = Marshal.AllocHGlobal((cnt + 3) * sizeof(uint) + 8);
            var psrc = new IntPtr(16 * (((long)rawptr + 15) / 16));

            UnsafeMemory.Copy(pdst, Marshal.UnsafeAddrOfPinnedArrayElement(d, 0), cnt * sizeof(uint));
            UnsafeMemory.Copy(psrc, Marshal.UnsafeAddrOfPinnedArrayElement(s, 0), cnt * sizeof(uint));

            var e = new uint[cnt];

            for (var z = 0; z < cnt; z++)
            {
                e[z] = BlendSrcOver(d[z], s[z]);
            }

            fn(pdst, psrc, (UIntPtr)cnt);

            UnsafeMemory.Copy(Marshal.UnsafeAddrOfPinnedArrayElement(d, 0), pdst, cnt * sizeof(uint));

            result   = string.Join(",", d);
            expected = string.Join(",", e);
        }
Beispiel #3
0
 public void Dispose()
 {
     foreach (var pointer in _dataAllocations)
     {
         UnsafeMemory.Free(pointer);
     }
 }
Beispiel #4
0
 void OnReadCompleted(UnsafeMemory <byte> bytesRead)
 {
     if (ReadCompleted != null)
     {
         ReadCompleted(bytesRead);
     }
 }
Beispiel #5
0
        public unsafe void TryWrite(UnsafeMemory <byte> data)
        {
            // This can work with Span<byte> because it's synchronous but we need pinning support
            EnsureNotDisposed();

            void *pointer;

            if (!data.TryGetPointer(out pointer))
            {
                throw new InvalidOperationException("Pointer not available");
            }

            IntPtr ptrData = (IntPtr)pointer;
            var    length  = data.Length;

            if (IsUnix)
            {
                var buffer = new UVBuffer.Unix(ptrData, (uint)length);
                UVException.ThrowIfError(UVInterop.uv_try_write(Handle, &buffer, 1));
            }
            else
            {
                var buffer = new UVBuffer.Windows(ptrData, (uint)length);
                UVException.ThrowIfError(UVInterop.uv_try_write(Handle, &buffer, 1));
            }
        }
 public BinaryVarValue(UnsafeMemory <BitState> bits, List <VarDef> variables, bool isValidBinary)
 {
     Debug.Assert(isValidBinary == bits.Span.IsAllBinary());
     this.BitSlice      = bits;
     this.Vars          = variables;
     this.IsValidBinary = isValidBinary;
 }
Beispiel #7
0
        public void SlicePointerBackedMemory()
        {
            unsafe
            {
                var data = new byte[10];
                for (int i = 0; i < 10; i++)
                {
                    data[i] = (byte)i;
                }

                fixed(byte *ptr = data)
                {
                    var memory = new UnsafeMemory <byte>(ptr, data.Length);
                    var slice  = memory.Slice(0, 5);
                    var span   = slice.Span;

                    for (int i = 0; i < 5; i++)
                    {
                        Assert.Equal(i, span[i]);
                    }

                    var subSlice = slice.Slice(2, 1);

                    Assert.Equal(2, subSlice.Span[0]);
                }
            }
        }
Beispiel #8
0
 public void Destroy()
 {
     if (data != null)
     {
         UnsafeMemory.Free(data);
         data = null;
     }
     if (ffpipe != null)
     {
         ffpipe.Close();
         ffpipe = null;
     }
     if (keyColors != null)
     {
         UnsafeMemory.Free(keyColors);
     }
     if (frame != null)
     {
         UnsafeMemory.Free(frame);
         frame = null;
     }
     if (emptyFrame != null)
     {
         UnsafeMemory.Free(emptyFrame);
         emptyFrame = null;
     }
     //if (renderPush != null)
     //{
     //    renderPush.Wait();
     //}
     keyColors = null;
 }
Beispiel #9
0
        public unsafe void TryWrite(UnsafeMemory<byte> data)
        {
            // This can work with Span<byte> because it's synchronous but we need pinning support
            EnsureNotDisposed();

            void* pointer;
            if (!data.TryGetPointer(out pointer))
            {
                throw new InvalidOperationException("Pointer not available");
            }

            IntPtr ptrData = (IntPtr)pointer;
            var length = data.Length;

            if (IsUnix)
            {
                var buffer = new UVBuffer.Unix(ptrData, (uint)length);
                UVException.ThrowIfError(UVInterop.uv_try_write(Handle, &buffer, 1));
            }
            else
            {
                var buffer = new UVBuffer.Windows(ptrData, (uint)length);
                UVException.ThrowIfError(UVInterop.uv_try_write(Handle, &buffer, 1));
            }
        }
Beispiel #10
0
 public void Visit(Node node)
 {
     if (!node.Shared)
     {
         UnsafeMemory.Copy(Dst + node.Offset, node.Data, DataSize);
     }
 }
Beispiel #11
0
            internal void Put(Node newNode)
            {
                var dataSize = DataSize;

                Length++;
                if (Root == null)
                {
                    Root = newNode;
                    return;
                }

                var node  = Root;
                var stack = new Node[HeightLimit];

                var top = 0;
                int dir;

                // Find a spot and save the stack.
                for (; ;)
                {
                    stack[top++] = node;
                    dir          = UnsafeMemory.Compare(node.Data, newNode.Data, dataSize) < 0 ? 1 : 0;

                    var link = node.Link[dir];
                    if (link == null)
                    {
                        break;
                    }

                    node = link;
                }

                // Link and rebalance.
                node.Link[dir] = newNode;

                while (top > 0)
                {
                    // Which child?
                    node = stack[--top];

                    if (top != 0)
                    {
                        dir = stack[top - 1].Link[1] == node ? 1 : 0;
                    }

                    node = SkewNode(node);
                    node = SplitNode(node);

                    // Fix the parent.
                    if (top != 0)
                    {
                        stack[top - 1].Link[dir] = node;
                    }
                    else
                    {
                        Root = node;
                    }
                }
            }
Beispiel #12
0
        public void GetArrayOrPointer()
        {
            var original = new int[] { 1, 2, 3 };
            ArraySegment <int> array;
            UnsafeMemory <int> slice;

            slice = new UnsafeMemory <int>(original, 1, 2);
            Assert.True(slice.TryGetArray(out array));
            Assert.Equal(2, array.Array[array.Offset + 0]);
            Assert.Equal(3, array.Array[array.Offset + 1]);

            slice = new UnsafeMemory <int>(original, 0, 3);
            Assert.True(slice.TryGetArray(out array));
            Assert.Equal(1, array.Array[array.Offset + 0]);
            Assert.Equal(2, array.Array[array.Offset + 1]);
            Assert.Equal(3, array.Array[array.Offset + 2]);

            slice = new UnsafeMemory <int>(original, 0, 0);
            Assert.True(slice.TryGetArray(out array));
            Assert.Equal(0, array.Offset);
            Assert.Equal(original, array.Array);
            Assert.Equal(0, array.Count);

            unsafe
            {
                fixed(int *pBytes = original)
                {
                    slice = new UnsafeMemory <int>(pBytes, 1);
                    Assert.False(slice.TryGetArray(out array));
                    void *p;

                    Assert.True(slice.TryGetPointer(out p));
                    Assert.True(null != p);
                    Assert.Equal(null, array.Array);
                    Assert.Equal(0, array.Offset);
                    Assert.Equal(0, array.Count);
                }
            }

            unsafe
            {
                fixed(int *pBytes = original)
                {
                    var roSlice = new ReadOnlySpan <int>(pBytes, 1);

                    Assert.False(slice.TryGetArray(out array));
                    void *p;

                    Assert.True(slice.TryGetPointer(out p));
                    Assert.True(null != p);
                    Assert.Equal(null, array.Array);
                    Assert.Equal(0, array.Offset);
                    Assert.Equal(0, array.Count);
                }
            }
        }
 public void Serialize(ref MessagePackWriter writer, ref int idx, CultureInfo value, IFormatterResolver formatterResolver)
 {
     if (value != null)
     {
         var encodedBytes = MessagePackBinary.GetEncodedStringBytes(value.Name);
         UnsafeMemory.WriteRaw(ref writer, encodedBytes, ref idx);
         return;
     }
     writer.WriteNil(ref idx);
 }
Beispiel #14
0
        public void WriteRaw(byte[] rawValue)
        {
#if NETSTANDARD
            UnsafeMemory.WriteRaw(ref this, rawValue);
#else
            BinaryUtil.EnsureCapacity(ref buffer, offset, rawValue.Length);
            Buffer.BlockCopy(rawValue, 0, buffer, offset, rawValue.Length);
            offset += rawValue.Length;
#endif
        }
Beispiel #15
0
        public void TryGetPointerReturnsFalseIfNotPinned()
        {
            var data   = new byte[10];
            var memory = new UnsafeMemory <byte>(data, 0, data.Length);

            unsafe
            {
                void *pointer;
                Assert.False(memory.TryGetPointer(out pointer));
            }
        }
Beispiel #16
0
        static void RunLoop(bool log)
        {
            var loop = new UVLoop();

            var listener  = new TcpListener(s_ipAddress, s_port, loop);
            var formatter = new ArrayFormatter(512, EncodingData.InvariantUtf8);

            listener.ConnectionAccepted += (Tcp connection) =>
            {
                if (log)
                {
                    Console.WriteLine("connection accepted");
                }

                connection.ReadCompleted += (data) =>
                {
                    if (log)
                    {
                        unsafe
                        {
                            var requestString = new Utf8String(data);
                            Console.WriteLine("*REQUEST:\n {0}", requestString.ToString());
                        }
                    }

                    formatter.Clear();
                    formatter.Append("HTTP/1.1 200 OK");
                    formatter.Append("\r\n\r\n");
                    formatter.Append("Hello World!");
                    if (log)
                    {
                        formatter.Format(" @ {0:O}", DateTime.UtcNow);
                    }

                    var segment = formatter.Formatted;
                    unsafe
                    {
                        fixed(byte *p = segment.Array)
                        {
                            var response = new UnsafeMemory <byte>(segment.Array, segment.Offset, segment.Count, pointer: p);

                            connection.TryWrite(response);
                        }
                    }

                    connection.Dispose();
                };

                connection.ReadStart();
            };

            listener.Listen();
            loop.Run();
        }
Beispiel #17
0
        public void Serialize(ref MessagePackWriter writer, ref int idx, T value, IFormatterResolver formatterResolver)
        {
            if (!valueNameMapping.TryGetValue(value, out string name))
            {
                name = value.ToString(); // fallback for flags etc, But Enum.ToString is too slow.
            }

            var encodedName = MessagePackBinary.GetEncodedStringBytes(name);

            UnsafeMemory.WriteRaw(ref writer, encodedName, ref idx);
        }
Beispiel #18
0
        internal void Fill(Pointer dst)
        {
            UnsafeMemory.Fill(dst, 0, Size);
            var filler = new ConstPoolFill(dst, 1);

            foreach (var t in _tree)
            {
                t.Iterate(filler);
                filler.DataSize <<= 1;
            }
        }
Beispiel #19
0
 public void TryGetPointerReturnsTrueIfPointerUsed()
 {
     unsafe
     {
         IntPtr raw    = Marshal.AllocHGlobal(10);
         var    memory = new UnsafeMemory <byte>((void *)raw, 10);
         void * pointer;
         Assert.True(memory.TryGetPointer(out pointer));
         Assert.True(raw.ToPointer() == pointer);
         Marshal.FreeHGlobal(raw);
     }
 }
Beispiel #20
0
            internal static Node NewNode(Pointer data, int size, int offset, bool shared)
            {
                var node = new Node();

                node.Link[0] = null;
                node.Link[1] = null;
                node.Level   = 1;
                node.Shared  = shared;
                node.Offset  = offset;
                node.Data    = UnsafeMemory.Allocate(size);
                UnsafeMemory.Copy(node.Data, data, size);
                return(node);
            }
Beispiel #21
0
        public void MemoryCtorThrowsIfPtrDoesNotMatchArrayArgs()
        {
            Assert.Throws <ArgumentException>(() =>
            {
                unsafe
                {
                    var data = new byte[10];

                    fixed(byte *ptr = data)
                    {
                        var memory = new UnsafeMemory <byte>(data, 0, data.Length, ptr + 1);
                    }
                }
            });
        }
Beispiel #22
0
        public void TryGetPointerReturnsTrueIfArrayAndPrePinned()
        {
            unsafe
            {
                var data = new byte[10];
                fixed(byte *ptr = data)
                {
                    var   memory = new UnsafeMemory <byte>(data, 0, data.Length, ptr);
                    void *pointer;

                    Assert.True(memory.TryGetPointer(out pointer));
                    Assert.True(ptr == pointer);
                }
            }
        }
Beispiel #23
0
        private DataNode CreateDataNode(Pointer data, int size)
        {
            var clonedData = UnsafeMemory.Allocate(size);

            if (clonedData == Pointer.Invalid)
            {
                return(null);
            }
            _dataAllocations.Add(clonedData);
            if (data != Pointer.Invalid)
            {
                UnsafeMemory.Copy(clonedData, data, size);
            }

            return(new DataNode(clonedData, size));
        }
Beispiel #24
0
        private static void RunTest()
        {
            const int cnt = 17;

            var d = new uint[] { 0x00000000, 0x10101010, 0x20100804, 0x30200003, 0x40204040, 0x5000004D, 0x60302E2C, 0x706F6E6D, 0x807F4F2F, 0x90349001, 0xA0010203, 0xB03204AB, 0xC023AFBD, 0xD0D0D0C0, 0xE0AABBCC, 0xFFFFFFFF, 0xF8F4F2F1 };
            var s = new uint[] { 0xE0E0E0E0, 0xA0008080, 0x341F1E1A, 0xFEFEFEFE, 0x80302010, 0x49490A0B, 0x998F7798, 0x00000000, 0x01010101, 0xA0264733, 0xBAB0B1B9, 0xFF000000, 0xDAB0A0C1, 0xE0BACFDA, 0x99887766, 0xFFFFFF80, 0xEE0A5FEC };

            var rawptr = Marshal.AllocHGlobal((cnt + 3) * sizeof(uint) + 8);
            var pdst   = new IntPtr(16 * (((long)rawptr + 15) / 16));

            rawptr = Marshal.AllocHGlobal((cnt + 3) * sizeof(uint) + 8);
            var psrc = new IntPtr(16 * (((long)rawptr + 15) / 16));

            UnsafeMemory.Copy(pdst, Marshal.UnsafeAddrOfPinnedArrayElement(d, 0), cnt * sizeof(uint));
            UnsafeMemory.Copy(psrc, Marshal.UnsafeAddrOfPinnedArrayElement(s, 0), cnt * sizeof(uint));

            var t1 = new ExecutionTimer();
            var t2 = new ExecutionTimer();

            t1.Start();
            for (int i = 0; i < 1000000; i++)
            {
                var e = new uint[cnt];
                for (var z = 0; z < cnt; z++)
                {
                    e[z] = BlendSrcOver(d[z], s[z]);
                }
            }
            t1.Stop();
            var tt1 = t1.Milliseconds;

            var fn = Make();

            t2.Start();
            for (int i = 0; i < 1000000; i++)
            {
                fn(pdst, psrc, (UIntPtr)cnt);
            }
            t2.Stop();
            var tt2 = t2.Milliseconds;

            Console.WriteLine("NET: " + tt1);
            Console.WriteLine("Asm: " + tt2);
            Console.ReadKey();

            UnsafeMemory.Copy(Marshal.UnsafeAddrOfPinnedArrayElement(d, 0), pdst, cnt * sizeof(uint));
        }
Beispiel #25
0
        internal static void VisitScalarValueChange(ReadOnlyMemory <byte> text, IDToVarDef idToVariable, SimPass pass, BitAllocator bitAlloc)
        {
            UnsafeMemory <BitState> bits = bitAlloc.GetBits(1);
            BitState bit = ToBitState(text.Span[0]);
            var      id  = text.Slice(1);

            bits.Span[0] = bit;

            if (idToVariable.TryGetValue(id, out List <VarDef>?variable))
            {
                pass.BinValue = new BinaryVarValue(bits, variable, ((int)bit & 0b10) == 0);
            }
            else
            {
                throw new Exception($"Unknown variable identifier: {id}");
            }
        }
Beispiel #26
0
        internal static unsafe (UnsafeMemory <BitState> bits, bool isValidBinary) ToBitStates(ReadOnlySpan <byte> valueText, BitAllocator bitAlloc)
        {
            UnsafeMemory <BitState> bitsMem = bitAlloc.GetBits(valueText.Length);
            Span <BitState>         bits    = bitsMem.Span;

            ulong isValidBinary = 0;
            int   index         = 0;

            if (Ssse3.IsSupported && bits.Length >= Vector128 <byte> .Count)
            {
                int vecBitCount = bits.Length / Vector128 <byte> .Count;
                fixed(BitState *bitsPtr = bits)
                {
                    fixed(byte *textPtr = valueText)
                    {
                        Vector128 <ulong> isValidBin = Vector128 <ulong> .Zero;

                        for (; index < vecBitCount; index++)
                        {
                            var charText = Avx.LoadVector128(textPtr + index * Vector128 <byte> .Count);
                            var byteText = Avx.Shuffle(charText, shuffleIdxs);

                            var firstBit         = Avx.And(onlyFirstBit, Avx.Or(byteText, Avx.ShiftRightLogical(byteText.AsInt32(), 1).AsByte()));
                            var secondBit        = Avx.And(onlySecondBit, Avx.ShiftRightLogical(byteText.AsInt32(), 5).AsByte());
                            var bytesAsBitStates = Avx.Or(firstBit, secondBit);

                            Avx.Store((byte *)bitsPtr + bits.Length - (index + 1) * Vector128 <byte> .Count, bytesAsBitStates);
                            isValidBin = Avx.Or(isValidBin, secondBit.AsUInt64());
                        }

                        isValidBinary = isValidBin.GetElement(0) | isValidBin.GetElement(1);
                    }
                }

                index *= Vector128 <byte> .Count;
            }

            for (; index < bits.Length; index++)
            {
                BitState bit = ToBitState(valueText[index]);
                bits[bits.Length - index - 1] = bit;
                isValidBinary |= (uint)bit & 0b10;
            }

            return(bitsMem, isValidBinary == 0);
        }
Beispiel #27
0
 public int Send(UnsafeMemory <byte> buffer)
 {
     // This can work with Span<byte> because it's synchronous but we need pinning support
     unsafe {
         ArraySegment <byte> segment;
         if (buffer.TryGetArray(out segment))
         {
             return(Send(segment));
         }
         else
         {
             void *pointer;
             buffer.TryGetPointer(out pointer);
             return(SendPinned(new IntPtr(pointer), buffer.Length));
         }
     }
 }
Beispiel #28
0
            internal Node Get(Pointer data)
            {
                var node     = Root;
                var dataSize = DataSize;

                while (node != null)
                {
                    var c = UnsafeMemory.Compare(node.Data, data, dataSize);
                    if (c == 0)
                    {
                        return(node);
                    }
                    node = node.Link[c < 0 ? 1 : 0];
                }

                return(null);
            }
Beispiel #29
0
        public void Clear()
        {
            //for (int i = 0; i != 128; ++i)
            //    keycolor[i] = (i % 12) switch
            //    {
            //        1 or 3 or 6 or 8 or 10 => 0xFF000000,
            //        _ => 0xFFFFFFFF,
            //    };
            fixed(uint *p = keycolor) UnsafeMemory.Copy(p, keyColors, 512);

            //for (int i = keyh; i < Height; ++i)
            //{
            //    //for (int j = 0; j < Width; ++j)
            //    //data[i][j] = 0xFF000000;
            //    UnsafeMemory.Copy(data[i], emptyData, (ulong)Width * 4);
            //}
            UnsafeMemory.Copy(frame, emptyFrame, (ulong)(Width * Height) * 4);
        }
        static void SerializeWithLengthPrefixExt <T>(Stream stream, T data, IFormatterResolver resolver)
        {
            const int ExtTypeCode = 111; // sample ext code

            var serializedData = MessagePackSerializer.Serialize(data, resolver);
            var tmp            = MessagePackSerializer.Deserialize <T>(serializedData, resolver);

            var dataSize = serializedData.Length;
            var idx      = 0;
            var writer   = new MessagePackWriter(16);

            var headerLength = MessagePackBinary.GetExtensionFormatHeaderLength(dataSize);

            writer.Ensure(idx, headerLength + dataSize);
            writer.WriteExtensionFormatHeader(ExtTypeCode, dataSize, ref idx);
            UnsafeMemory.WriteRaw(ref writer, serializedData, ref idx);
            var buffer = writer.ToArray(idx);

            stream.Write(buffer);
        }
        public void Serialize(ref MessagePackWriter writer, ref int idx, object value, IFormatterResolver formatterResolver)
        {
            if (value == null)
            {
                writer.WriteNil(ref idx); return;
            }

            var type = value.GetType();

            if (!s_typeNameCache.TryGetValue(type, out Type expectedType))
            {
                GetExpectedTypeSlow(type, out expectedType);
            }

            if (expectedType == null)
            {
                Resolvers.TypelessFormatterFallbackResolver.Instance.GetFormatter <object>().Serialize(ref writer, ref idx, value, formatterResolver);
                return;
            }

            // don't use GetOrAdd for avoid closure capture.
            if (!s_serializers.TryGetValue(expectedType, out var formatterAndDelegate))
            {
                GetFormatterAndDelegateSlow(expectedType, formatterResolver, out formatterAndDelegate);
            }

            // mark as extension with code 100
            writer.Ensure(idx, 6);
            var startOffset = idx;

            idx += 6; // mark will be written at the end, when size is known

            var typeName = MessagePackBinary.GetEncodedTypeName(expectedType);

            UnsafeMemory.WriteRaw(ref writer, typeName, ref idx);
            formatterAndDelegate.Value(formatterAndDelegate.Key, ref writer, ref idx, value, formatterResolver);

            var dataLength = idx - startOffset - 6;

            MessagePackBinary.WriteExtensionFormatHeaderForceExt32Block(ref writer.PinnableAddress, startOffset, ExtensionTypeCode, dataLength);
        }
Beispiel #32
0
        public void MemoryCtorSubArrayWithPinnedPtr()
        {
            unsafe
            {
                var data = new byte[10];
                for (int i = 0; i < data.Length; i++)
                {
                    data[i] = (byte)i;
                }

                fixed (byte* ptr = data)
                {
                    var memory = new UnsafeMemory<byte>(data, 5, 5, ptr + 5);
                    Assert.Equal(5, memory.Length);
                    var span = memory.Span;
                    for (int i = 0; i < 5; i++)
                    {
                        Assert.Equal(span[i], i + 5);
                    }
                }
            }
        }
Beispiel #33
0
        public void GetArrayOrPointer()
        {
            var original = new int[] { 1, 2, 3 };
            ArraySegment<int> array;
            UnsafeMemory<int> slice;

            slice = new UnsafeMemory<int>(original, 1, 2);
            Assert.True(slice.TryGetArray(out array));
            Assert.Equal(2, array.Array[array.Offset + 0]);
            Assert.Equal(3, array.Array[array.Offset + 1]);

            slice = new UnsafeMemory<int>(original, 0, 3);
            Assert.True(slice.TryGetArray(out array));
            Assert.Equal(1, array.Array[array.Offset + 0]);
            Assert.Equal(2, array.Array[array.Offset + 1]);
            Assert.Equal(3, array.Array[array.Offset + 2]);

            slice = new UnsafeMemory<int>(original, 0, 0);
            Assert.True(slice.TryGetArray(out array));
            Assert.Equal(0, array.Offset);
            Assert.Equal(original, array.Array);
            Assert.Equal(0, array.Count);

            unsafe
            {
                fixed (int* pBytes = original)
                {
                    slice = new UnsafeMemory<int>(pBytes, 1);
                    Assert.False(slice.TryGetArray(out array));
                    void* p;
                    Assert.True(slice.TryGetPointer(out p));
                    Assert.True(null != p);
                    Assert.Equal(null, array.Array);
                    Assert.Equal(0, array.Offset);
                    Assert.Equal(0, array.Count);
                }
            }

            unsafe
            {
                fixed (int* pBytes = original)
                {
                    var roSlice = new ReadOnlySpan<int>(pBytes, 1);
                    Assert.False(slice.TryGetArray(out array));
                    void* p;
                    Assert.True(slice.TryGetPointer(out p));
                    Assert.True(null != p);
                    Assert.Equal(null, array.Array);
                    Assert.Equal(0, array.Offset);
                    Assert.Equal(0, array.Count);
                }
            }
        }
Beispiel #34
0
 void OnReadWindows(UVBuffer.Windows buffer, IntPtr bytesAvaliable)
 {
     // TODO: all branches need to release buffer, I think
     long bytesRead = bytesAvaliable.ToInt64();
     if (bytesRead == 0)
     {
         buffer.Dispose();
         return;
     }
     else if (bytesRead < 0)
     {
         var error = UVException.ErrorCodeToError((int)bytesRead);
         if (error == UVError.EOF)
         {
             OnEndOfStream();
             Dispose();
             buffer.Dispose();
         }
         else if (error == UVError.ECONNRESET)
         {
             Debug.Assert(buffer.Buffer == IntPtr.Zero && buffer.Length == 0);
             // no need to dispose
             // TODO: what should we do here?
         }
         else
         {
             Dispose();
             buffer.Dispose();
             throw new UVException((int)bytesRead);
         }
     }
     else
     {
         var readSlice = new UnsafeMemory<byte>((byte*)buffer.Buffer, (int)bytesRead);
         OnReadCompleted(readSlice);
         buffer.Dispose();
     }
 }
Beispiel #35
0
 public void TryGetPointerReturnsFalseIfNotPinned()
 {
     var data = new byte[10];
     var memory = new UnsafeMemory<byte>(data, 0, data.Length);
     unsafe
     {
         void* pointer;
         Assert.False(memory.TryGetPointer(out pointer));
     }
 }
Beispiel #36
0
 public int Receive(UnsafeMemory<byte> buffer)
 {
     // This can work with Span<byte> because it's synchronous but we need pinning support
     unsafe
     {
         ArraySegment<byte> segment;
         if (buffer.TryGetArray(out segment)) {
             return Receive(segment);
         }
         else {
             void* pointer;
             buffer.TryGetPointer(out pointer);
             return ReceivePinned(new IntPtr(pointer), buffer.Length);
         }
     }
 }
Beispiel #37
0
 public void TryGetPointerReturnsTrueIfPointerUsed()
 {
     unsafe
     {
         IntPtr raw = Marshal.AllocHGlobal(10);
         var memory = new UnsafeMemory<byte>((void*)raw, 10);
         void* pointer;
         Assert.True(memory.TryGetPointer(out pointer));
         Assert.True(raw.ToPointer() == pointer);
         Marshal.FreeHGlobal(raw);
     }
 }
Beispiel #38
0
 public void TryGetPointerReturnsTrueIfArrayAndPrePinned()
 {
     unsafe
     {
         var data = new byte[10];
         fixed (byte* ptr = data)
         {
             var memory = new UnsafeMemory<byte>(data, 0, data.Length, ptr);
             void* pointer;
             Assert.True(memory.TryGetPointer(out pointer));
             Assert.True(ptr == pointer);
         }
     }
 }
Beispiel #39
0
        public void MemoryCtorThrowsIfPtrDoesNotMatchArrayArgs()
        {
            Assert.Throws<ArgumentException>(() =>
            {
                unsafe
                {
                    var data = new byte[10];

                    fixed (byte* ptr = data)
                    {
                        var memory = new UnsafeMemory<byte>(data, 0, data.Length, ptr + 1);
                    }
                }
            });
        }
Beispiel #40
0
        public void SlicePointerBackedMemory()
        {
            unsafe
            {
                var data = new byte[10];
                for (int i = 0; i < 10; i++)
                {
                    data[i] = (byte)i;
                }

                fixed (byte* ptr = data)
                {
                    var memory = new UnsafeMemory<byte>(ptr, data.Length);
                    var slice = memory.Slice(0, 5);
                    var span = slice.Span;
                    for (int i = 0; i < 5; i++)
                    {
                        Assert.Equal(i, span[i]);
                    }

                    var subSlice = slice.Slice(2, 1);
                    Assert.Equal(2, subSlice.Span[0]);
                }
            }
        }
Beispiel #41
0
 void OnReadUnix(UVBuffer.Unix buffer, IntPtr bytesAvaliable)
 {
     long bytesRead = bytesAvaliable.ToInt64();
     if (bytesRead == 0)
     {
         return;
     }
     else if (bytesRead < 0)
     {
         var error = UVException.ErrorCodeToError((int)bytesRead);
         if (error == UVError.EOF)
         {
             OnEndOfStream();
             Dispose();
         }
         else
         {
             Dispose();
             throw new UVException((int)bytesRead);
         }
     }
     else
     {
         // This can be a Span<byte> but the samples pass it directly to TryWrite which
         // needs to unpack the data and turn it back into either an array or native memory
         var readSlice = new UnsafeMemory<byte>((byte*)buffer.Buffer, (int)bytesRead);
         OnReadCompleted(readSlice);
         buffer.Dispose();
     }
 }
Beispiel #42
0
        public void SliceArrayBackedMemory()
        {
            var data = new byte[10];

            for (int i = 0; i < 10; i++)
            {
                data[i] = (byte)i;
            }

            var memory = new UnsafeMemory<byte>(data, 0, data.Length);
            var slice = memory.Slice(0, 5);
            var span = slice.Span;
            for (int i = 0; i < 5; i++)
            {
                Assert.Equal(i, span[i]);
            }

            var subSlice = slice.Slice(2, 1);
            Assert.Equal(2, subSlice.Span[0]);
        }
Beispiel #43
0
 void OnReadCompleted(UnsafeMemory<byte> bytesRead)
 {
     if (ReadCompleted != null)
     {
         ReadCompleted(bytesRead);
     }
 }