Exemplo n.º 1
0
        async ValueTask <Rent <byte> > ReceivePacketAsync(CancellationToken token)
        {
            byte[] lengthBuffer = new byte[4];
            if (!await tcpClient.ReadChunkAsync(lengthBuffer, 4, token))
            {
                throw new IOException("Partner closed connection");
            }

            int length = BitConverter.ToInt32(lengthBuffer, 0);

            if (length == 0)
            {
                return(Rent.Empty <byte>());
            }

            var readBuffer = new Rent <byte>(length);

            try
            {
                if (!await tcpClient.ReadChunkAsync(readBuffer.Array, length, token))
                {
                    throw new IOException("Partner closed connection");
                }
            }
            catch (Exception)
            {
                readBuffer.Dispose();
                throw;
            }

            return(readBuffer);
        }
Exemplo n.º 2
0
        public void RentTest()
        {
            using (var rent = new Rent <byte>(100))
            {
                Assert.True(rent.Array != null && rent.Array.Length >= rent.Length);
                Assert.Catch <IndexOutOfRangeException>(() =>
                {
                    int _ = rent[100];
                });
            }

            using (var rent = new Rent <byte>(1000))
            {
                Assert.True(rent.Array != null && rent.Array.Length >= rent.Length);
            }

            using (var rent = new Rent <byte>(0))
            {
                Assert.True(rent.Array != null && rent.Array.Length == 0);
            }

            using (var rent = Rent.Empty <byte>())
            {
                Assert.True(rent.Array != null && rent.Array.Length == 0);
            }

            var rent2 = new UniqueRef <string>(200, true);

            Assert.True(rent2.Array != null && rent2.Array.Length >= rent2.Length);

            string[] rent2Array = rent2.Array;

            rent2.Dispose();

            Assert.Catch <IndexOutOfRangeException>(() =>
            {
                string _ = rent2[0];
            });

            Assert.Catch <ObjectDisposedException>(() =>
            {
                var _ = rent2.Array;
            });

            Assert.True(rent2Array[0] == null);
        }