public void TestCopyTo_EmptyArraySegment()
        {
            var array  = new int[] { 1 };
            var target = new ArraySegment <int>(array, 0, 0);
            var result = new int[5];

            Assert.That(target.CopyTo(0, result, 0, 1), Is.EqualTo(0));
        }
        public void TestCopyTo_EmptySourceArray()
        {
            var array  = new int[0];
            var target = new ArraySegment <int>(array);
            var result = new int[5];

            Assert.That(target.CopyTo(0, result, 0, 1), Is.EqualTo(0));
        }
        [NotNull] internal static T[] ToArray <T>(this ArraySegment <T> segment)
            where T : struct
        {
            var arr = new T[segment.Count];

            segment.CopyTo(arr);
            return(arr);
        }
Example #4
0
        /// <summary>
        /// Write some bytes into the underlying array. Mutate this writer to represent the position after the write. </summary>
        /// <param name="data">data to write</param>
        /// <returns>A copy of this writer (after the write has been applied)</returns>
        public PacketWriter Write(ArraySegment <byte> data)
        {
            Write((ushort)data.Count);

            data.CopyTo(_array.Array, _array.Offset + _count);
            _count += data.Count;

            return(this);
        }
        async ValueTask <int> SendThenBufferAsync(ArraySegment <byte> buffer)
        {
            await WriteAsync(_sendBuffer).ConfigureAwait(false);

            buffer.CopyTo(_sendBuffer);
            _sendBufferFillLength = buffer.Count;

            return(0);
        }
Example #6
0
        /// <summary>
        /// Creates a new array containing the elements in this array segment.
        /// </summary>
        /// <typeparam name="T">The type of elements contained in the array.</typeparam>
        /// <param name="segment">The array segment.</param>
        /// <returns>The new array.</returns>
        public static T[] ToArray <T>(this ArraySegment <T> segment)
        {
            Contract.Ensures(Contract.Result <T[]>() != null);
            Contract.Ensures(Contract.Result <T[]>().Length == segment.Count);
            var ret = new T[segment.Count];

            segment.CopyTo(ret);
            return(ret);
        }
Example #7
0
        public async Task HandleWithCancellationTest()
        {
            // Arrange
            var buffer = DockerFraming.Frame(TestLogTexts);

            string id = "m1";
            var    runtimeInfoProvider = new Mock <IRuntimeInfoProvider>();

            runtimeInfoProvider.Setup(r => r.GetModuleLogs(id, true, Option.None <int>(), Option.None <string>(), Option.None <string>(), Option.None <bool>(), It.IsAny <CancellationToken>()))
            .ReturnsAsync(new MemoryStream(buffer));
            runtimeInfoProvider.Setup(r => r.GetModules(It.IsAny <CancellationToken>()))
            .ReturnsAsync(new[] { new ModuleRuntimeInfo(id, "docker", ModuleStatus.Running, "foo", 0, Option.None <DateTime>(), Option.None <DateTime>()) });

            var logsProcessor     = new LogsProcessor(new LogMessageParser("testIotHub", "d1"));
            var logsProvider      = new LogsProvider(runtimeInfoProvider.Object, logsProcessor);
            var logRequestItem    = new LogRequestItem(id, ModuleLogFilter.Empty);
            var logsStreamRequest = new LogsStreamRequest("1.0", new List <LogRequestItem> {
                logRequestItem
            }, LogsContentEncoding.None, LogsContentType.Text);

            byte[] logsStreamRequestBytes    = logsStreamRequest.ToBytes();
            var    logsStreamRequestArraySeg = new ArraySegment <byte>(logsStreamRequestBytes);
            var    clientWebSocket           = new Mock <IClientWebSocket>();

            clientWebSocket.Setup(c => c.ReceiveAsync(It.IsAny <ArraySegment <byte> >(), It.IsAny <CancellationToken>()))
            .Callback <ArraySegment <byte>, CancellationToken>((a, c) => logsStreamRequestArraySeg.CopyTo(a))
            .ReturnsAsync(new WebSocketReceiveResult(logsStreamRequestBytes.Length, WebSocketMessageType.Binary, true));

            var receivedBytes = new List <byte>();

            clientWebSocket.Setup(c => c.SendAsync(It.IsAny <ArraySegment <byte> >(), WebSocketMessageType.Binary, true, It.IsAny <CancellationToken>()))
            .Callback <ArraySegment <byte>, WebSocketMessageType, bool, CancellationToken>((a, w, f, c) => receivedBytes.AddRange(a.Array))
            .Returns(async() => await Task.Delay(TimeSpan.FromSeconds(3)));
            clientWebSocket.SetupGet(c => c.State).Returns(WebSocketState.Open);

            // Act
            var  logsStreamRequestHandler = new LogsStreamRequestHandler(logsProvider, runtimeInfoProvider.Object);
            Task handleTask = logsStreamRequestHandler.Handle(clientWebSocket.Object, CancellationToken.None);

            await Task.Delay(TimeSpan.FromSeconds(10));

            clientWebSocket.SetupGet(c => c.State).Returns(WebSocketState.Closed);

            // Assert
            await Task.Delay(TimeSpan.FromSeconds(5));

            Assert.True(handleTask.IsCompleted);
            runtimeInfoProvider.VerifyAll();
            clientWebSocket.VerifyAll();

            Assert.True(receivedBytes.Count < buffer.Length);
            IList <string> receivedChunks = SimpleFraming.Parse(receivedBytes.ToArray())
                                            .Select(r => Encoding.UTF8.GetString(r))
                                            .ToList();

            Assert.Equal(TestLogTexts.Take(receivedChunks.Count), receivedChunks);
        }
        public void TestCopyTo_SmallArray()
        {
            var array  = new int[] { 1, 2, 3 };
            var target = new ArraySegment <int>(array);
            var result = new int[2];

            Assert.That(target.CopyTo(0, result, 0, result.Length), Is.EqualTo(2));
            Assert.That(result, Is.EqualTo(new int[] { 1, 2 }));
        }
        /// <summary>
        /// Write some bytes into the underlying array. Mutate this writer to represent the position after the write. </summary>
        /// <param name="data">data to write</param>
        /// <returns>A copy of this writer (after the write has been applied)</returns>
        public PacketWriter Write(ArraySegment <byte> data)
        {
            Write((ushort)data.Count);

            // ReSharper disable once AssignNullToNotNullAttribute (Justification: Array segment cannot be null)
            data.CopyTo(_array.Array, _array.Offset + _count);
            _count += data.Count;

            return(this);
        }
Example #10
0
        public void IList_CopyTo()
        {
            var array = new long[] { 1, 2, 3, 4, 5, 6, -10 };

            IList <long> s = new ArraySegment <long> (array, 2, 3);

            long[] target = new long[s.Count];
            s.CopyTo(target, 0);

            Assert.AreEqual(3, target[0], "#1");
            Assert.AreEqual(4, target[1], "#2");
        }
        /// <summary>
        /// Simulates copying to the send buffer; what you would do for user's content buffers.
        /// </summary>
        ValueTask <int> WriteBufferedAsync(ArraySegment <byte> buffer, bool flush = false)
        {
            int available = _sendBuffer.Length - _sendBufferFillLength;

            if (available > buffer.Count && !flush)
            {
                buffer.CopyTo(_sendBuffer, _sendBufferFillLength);
                _sendBufferFillLength += buffer.Count;
                return(new ValueTask <int>(0));
            }

            if (_sendBufferFillLength == 0)
            {
                return(WriteAsync(buffer));
            }

            if (available > buffer.Count)
            {
                buffer.CopyTo(_sendBuffer, _sendBufferFillLength);

                int sendLen = _sendBufferFillLength + buffer.Count;
                _sendBufferFillLength = 0;

                return(WriteAsync(_sendBuffer.AsMemory(0, sendLen)));
            }

            if (!flush)
            {
                int remainingBufferLength = buffer.Count - available;

                if (remainingBufferLength < _sendBuffer.Length)
                {
                    buffer.AsSpan(0, available).CopyTo(_sendBuffer.AsSpan(_sendBufferFillLength));
                    return(SendThenBufferAsync(buffer.Slice(available)));
                }
            }

            return(SendThenSendAsync(buffer));
        }
        public async Task HandleTest()
        {
            // Arrange
            var random = new Random();
            var buffer = new byte[1024 * 128];

            random.NextBytes(buffer);

            string id = "m1";
            var    runtimeInfoProvider = new Mock <IRuntimeInfoProvider>();

            runtimeInfoProvider.Setup(r => r.GetModuleLogs(id, true, Option.None <int>(), Option.None <int>(), It.IsAny <CancellationToken>()))
            .ReturnsAsync(new MemoryStream(buffer));
            runtimeInfoProvider.Setup(r => r.GetModules(It.IsAny <CancellationToken>()))
            .ReturnsAsync(new[] { new ModuleRuntimeInfo(id, "docker", ModuleStatus.Running, "foo", 0, Option.None <DateTime>(), Option.None <DateTime>()) });

            var logsProvider      = new LogsProvider(runtimeInfoProvider.Object, Mock.Of <ILogsProcessor>());
            var logRequestItem    = new LogRequestItem(id, ModuleLogFilter.Empty);
            var logsStreamRequest = new LogsStreamRequest("1.0", new List <LogRequestItem> {
                logRequestItem
            }, LogsContentEncoding.None, LogsContentType.Text);

            byte[] logsStreamRequestBytes    = logsStreamRequest.ToBytes();
            var    logsStreamRequestArraySeg = new ArraySegment <byte>(logsStreamRequestBytes);
            var    clientWebSocket           = new Mock <IClientWebSocket>();

            clientWebSocket.Setup(c => c.ReceiveAsync(It.IsAny <ArraySegment <byte> >(), It.IsAny <CancellationToken>()))
            .Callback <ArraySegment <byte>, CancellationToken>((a, c) => logsStreamRequestArraySeg.CopyTo(a))
            .Returns(
                async() =>
            {
                await Task.Yield();
                return(new WebSocketReceiveResult(logsStreamRequestBytes.Length, WebSocketMessageType.Binary, true));
            });
            var receivedBytes = new List <byte>();

            clientWebSocket.Setup(c => c.SendAsync(It.IsAny <ArraySegment <byte> >(), WebSocketMessageType.Binary, true, It.IsAny <CancellationToken>()))
            .Callback <ArraySegment <byte>, WebSocketMessageType, bool, CancellationToken>((a, w, f, c) => receivedBytes.AddRange(a.Array))
            .Returns(async() => await Task.Yield());
            clientWebSocket.SetupGet(c => c.State).Returns(WebSocketState.Open);

            // Act
            var logsStreamRequestHandler = new LogsStreamRequestHandler(logsProvider);
            await logsStreamRequestHandler.Handle(clientWebSocket.Object, CancellationToken.None);

            // Assert
            runtimeInfoProvider.VerifyAll();
            clientWebSocket.VerifyAll();
            Assert.Equal(buffer, receivedBytes.ToArray());
        }
Example #13
0
        public T Deserialize <T>(ArraySegment <byte> input)
        {
            byte[] rent = ArrayPool <byte> .Shared.Rent(input.Count);

            try
            {
                input.CopyTo(rent);
                return(JsonSerializer.Deserialize <T>(rent));
            }
            finally
            {
                ArrayPool <byte> .Shared.Return(rent);
            }
        }
		public void TestCopyTo()
		{
			var array = new int[] { 1, 2, 3, 4, 5 };
			var target = new ArraySegment<int>( array, 1, 3 );
			var result = new int[ 5 ];

			// Copy all
			Assert.That( target.CopyTo( 0, result, 0, result.Length ), Is.EqualTo( target.Count ) );
			Assert.That( result, Is.EqualTo( new int[] { 2, 3, 4, 0, 0 } ) );

			// Source offset
			Array.Clear( result, 0, result.Length );
			Assert.That( target.CopyTo( 1, result, 0, result.Length ), Is.EqualTo( target.Count - 1 ) );
			Assert.That( result, Is.EqualTo( new int[] { 3, 4, 0, 0, 0 } ) );

			// Offset
			Array.Clear( result, 0, result.Length );
			Assert.That( target.CopyTo( 0, result, 1, result.Length ), Is.EqualTo( target.Count ) );
			Assert.That( result, Is.EqualTo( new int[] { 0, 2, 3, 4, 0 } ) );

			// Length
			Array.Clear( result, 0, result.Length );
			Assert.That( target.CopyTo( 0, result, 0, result.Length - 1 ), Is.EqualTo( target.Count ) );
			Assert.That( result, Is.EqualTo( new int[] { 2, 3, 4, 0, 0 } ) );

			Array.Clear( result, 0, result.Length );
			Assert.That( target.CopyTo( 0, result, 0, target.Count - 1 ), Is.EqualTo( target.Count - 1 ) );
			Assert.That( result, Is.EqualTo( new int[] { 2, 3, 0, 0, 0 } ) );

			Array.Clear( result, 0, result.Length );
			Assert.That( target.CopyTo( 0, result, 0, 0 ), Is.EqualTo( 0 ) );
			Assert.That( result, Is.EqualTo( new int[] { 0, 0, 0, 0, 0 } ) );

			Array.Clear( result, 0, result.Length );
			Assert.That( target.CopyTo( 0, result, 0, 1 ), Is.EqualTo( 1 ) );
			Assert.That( result, Is.EqualTo( new int[] { 2, 0, 0, 0, 0 } ) );
		}
Example #15
0
    public static void TestIList_CopyTo_Invalid()
    {
        IList <int> iList = new ArraySegment <int>();

        Assert.Throws <InvalidOperationException>(() => iList.CopyTo(new int[7], 0)); // Array is null

        var intArray = new int[] { 7, 8, 9, 10, 11, 12, 13 };

        iList = new ArraySegment <int>(intArray, 2, 3);

        Assert.Throws <ArgumentNullException>("dest", () => iList.CopyTo(null, 0));                  // Destination array is null

        Assert.Throws <ArgumentOutOfRangeException>("dstIndex", () => iList.CopyTo(new int[7], -1)); // Index < 0
        Assert.Throws <ArgumentException>("", () => iList.CopyTo(new int[7], 8));                    // Index > destinationArray.Length
    }
 public override Task SendAsync(ArraySegment <byte> buffer, WebSocketMessageType messageType, bool endOfMessage, CancellationToken cancellationToken)
 {
     lock (sendingSemaphore)
     {
         if (!endOfMessage)
         {
             throw new InvalidOperationException("Only completed messages are supported.");
         }
         var message = XdrBufferFactory.Rent(buffer.Count);
         var segment = message.AsSegment(0, buffer.Count);
         buffer.CopyTo(segment);
         message.Resize(buffer.Count);
         secondPartyPendingMessages.Add(new TestMessage(message, messageType, endOfMessage));
     }
     return(Task.CompletedTask);
 }
Example #17
0
            public void CopyTo(T[] array, int arrayIndex)
            {
                if (array is null)
                {
                    throw new ArgumentNullException(nameof(array));
                }
                if (arrayIndex <= 0)
                {
                    throw new ArgumentOutOfRangeException(nameof(arrayIndex), "Is less than 0.");
                }
                if (array.Length - arrayIndex < Count)
                {
                    throw new ArgumentException("The number of elements in the source ICollection<T> is greater than the available space from arrayIndex to the end of the destination array.");
                }

                _seg0.CopyTo(array, arrayIndex);
                _seg1.CopyTo(array, arrayIndex + _seg0.Count);
            }
        public static X509Extension MakeAuthorityKey(this X509SubjectKeyIdentifierExtension subjectKeyIdentifierExtension)
        {
            // Make the AuthorityKeyIdentifierExtension. There is no built-in
            // support, so it needs to be copied from the Subject Key
            // Identifier of the signing certificate and massaged slightly.
            // AuthorityKeyIdentifier is "KeyID=<subject key identifier>"
            var issuerSubjectKey       = subjectKeyIdentifierExtension.RawData;
            var segment                = new ArraySegment <byte>(issuerSubjectKey, 2, issuerSubjectKey.Length - 2);
            var authorityKeyIdentifier = new byte[segment.Count + 4];

            // these bytes define the "KeyID" part of the AuthorityKeyIdentifier
            authorityKeyIdentifier[0] = 0x30;
            authorityKeyIdentifier[1] = 0x16;
            authorityKeyIdentifier[2] = 0x80;
            authorityKeyIdentifier[3] = 0x14;
            segment.CopyTo(authorityKeyIdentifier, 4);
            return(new X509Extension("2.5.29.35", authorityKeyIdentifier, false));
        }
 internal bool PreprocessPacketToClient(ArraySegment <byte> packet, HlapiConn destination)
 {
     if (base.Server == null)
     {
         throw this.Log.CreatePossibleBugException("server packet preprocessing running, but this peer is not a server", "8f9dc0a0-1b48-4a7f-9bb6-f767b2542ab1");
     }
     if (base.Client == null)
     {
         return(false);
     }
     if (NetworkManager.singleton.client.connection != destination.Connection)
     {
         return(false);
     }
     if (base.Client != null)
     {
         this._loopbackQueue.Add(packet.CopyTo(this._loopbackBuffers.Get(), 0));
     }
     return(true);
 }
Example #20
0
        private void Test5()
        {
            int[] ii             = Enumerable.Range(1, 1_000_000).ToArray();
            long  total          = 0;
            int   simdLongLength = Vector <long> .Count;
            int   simdIntLength  = Vector <int> .Count;

            int[] inu   = new ArraySegment <int>(ii, 0, simdIntLength).ToArray();
            var   vInu  = new Vector <int>(inu);
            var   tako  = new ArraySegment <int>(ii, 0, simdIntLength);
            var   vTako = new Vector <int>(tako);

            //var neko = new ArraySegment<long>(nums, 0, simdLongLength);//エラー型が違う

            var neko = new long[simdLongLength];

            //Array.ConstrainedCopy(ii, 1, neko, 0, 8);//エラー
            for (int i = 0; i < simdLongLength; i++)
            {
                neko[i] = ii[i];
            }
            var uma = new long[ii.Length];

            ii.CopyTo(uma, 0);

            int[]  iii = new ArraySegment <int>(ii, 10, simdLongLength).ToArray();
            long[] ll  = new long[simdLongLength];
            iii.CopyTo(ll, 0);

            int[]  mm = ii.Skip(10).Take(simdLongLength).ToArray();
            long[] nn = new long[simdLongLength];
            mm.CopyTo(nn, 0);

            int[]  sp = new Span <int>(ii, 10, simdLongLength).ToArray();
            long[] oo = new long[simdLongLength];
            sp.CopyTo(oo, 0);

            long[] pp = new long[simdLongLength];
            new Span <int>(ii, 10, simdLongLength).ToArray().CopyTo(pp, 0);
        }
Example #21
0
        /// <summary>
        /// Create a new <see cref="Ulid"/> with the specified timestamp.
        /// </summary>
        /// <param name="timestamp">
        /// Timestamp to use.
        /// </param>
        /// <returns>
        /// An <see cref="Ulid"/> with the specified timestamp and cryptographically randomness.
        /// </returns>
        /// <exception cref="ArgumentOutOfRangeException">
        /// <paramref name="timestamp"/> is less than <see cref="MinTimestamp"/> or greater than <see cref="MaxTimestamp"/>.
        /// </exception>
        /// <exception cref="OverflowException">
        /// <paramref name="timestamp"/> is the same as the last generated value and the randomness incrementing is overflow.
        /// </exception>
        public static Ulid Generate(long timestamp)
        {
            if (timestamp < MinTimestamp || timestamp > MaxTimestamp)
            {
                throw new ArgumentOutOfRangeException(nameof(timestamp));
            }

            //https://github.com/ulid/spec#monotonicity
            //When generating a ULID within the same millisecond, we can provide some guarantees regarding sort order.
            //Namely, if the same millisecond is detected, the random component is incremented by 1 bit in the least
            //significant bit position (with carrying)

            if (timestamp == LatestTimeStamp)
            {
                LatestRandomness++;
            }
            else
            {
                LatestTimeStamp  = timestamp;
                LatestRandomness = RandomLong(0, long.MaxValue);
            }

            byte[] timestampBytes = BitConverter.GetBytes(LatestTimeStamp);
            Array.Reverse(timestampBytes);
            timestampBytes = new ArraySegment <byte>(timestampBytes, 2, 6).ToArray();

            //find randomness
            byte[] randomness = BitConverter.GetBytes(LatestRandomness);
            Array.Reverse(randomness);
            byte[] finalRandomness = new byte[10];
            randomness.CopyTo(finalRandomness, 2);

            byte[] finalId = new byte[finalRandomness.Length + timestampBytes.Length];

            timestampBytes.CopyTo(finalId, 0);
            finalRandomness.CopyTo(finalId, timestampBytes.Length);

            return(new Ulid(finalId));
        }
Example #22
0
        private void ROMix(ArraySegment <byte> B, byte[] X, byte[] Y, byte[] V)
        {
            B.CopyTo(X, 0);

            for (int i = 0; i < Cost; ++i)
            {
                Array.Copy(X, 0, V, i * (128 * BlockSize), 128 * BlockSize);
                BlockMix(X, Y);
            }

            for (int i = 0; i < Cost; ++i)
            {
                ulong j = BitConverter.ToUInt64(X, (2 * BlockSize - 1) * 64);
                j %= (ulong)Cost;

                for (int k = 0; k < 128 * BlockSize; ++k)
                {
                    X[k] ^= V[j * (128 * (ulong)BlockSize) + (ulong)k];
                }
                BlockMix(X, Y);
            }

            ArraySegment <byte> .Copy(X, B, 128 *BlockSize);
        }
Example #23
0
    public static void TestIList_CopyTo()
    {
        var            stringArray   = new string[] { "0", "1", "2", "3", "4" };
        IList <string> stringSegment = new ArraySegment <string>(stringArray, 1, 3);

        stringSegment.CopyTo(stringArray, 2);
        Assert.Equal(new string[] { "0", "1", "1", "2", "3" }, stringArray);

        stringArray   = new string[] { "0", "1", "2", "3", "4" };
        stringSegment = new ArraySegment <string>(stringArray, 1, 3);
        stringSegment.CopyTo(stringArray, 0);
        Assert.Equal(new string[] { "1", "2", "3", "3", "4" }, stringArray);

        var         intArray   = new int[] { 0, 1, 2, 3, 4 };
        IList <int> intSegment = new ArraySegment <int>(intArray, 1, 3);

        intSegment.CopyTo(intArray, 2);
        Assert.Equal(new int[] { 0, 1, 1, 2, 3 }, intArray);

        intArray   = new int[] { 0, 1, 2, 3, 4 };
        intSegment = new ArraySegment <int>(intArray, 1, 3);
        intSegment.CopyTo(intArray, 0);
        Assert.Equal(new int[] { 1, 2, 3, 3, 4 }, intArray);
    }
        public void TestCopyTo()
        {
            var array  = new int[] { 1, 2, 3, 4, 5 };
            var target = new ArraySegment <int>(array, 1, 3);
            var result = new int[5];

            // Copy all
            Assert.That(target.CopyTo(0, result, 0, result.Length), Is.EqualTo(target.Count));
            Assert.That(result, Is.EqualTo(new int[] { 2, 3, 4, 0, 0 }));

            // Source offset
            Array.Clear(result, 0, result.Length);
            Assert.That(target.CopyTo(1, result, 0, result.Length), Is.EqualTo(target.Count - 1));
            Assert.That(result, Is.EqualTo(new int[] { 3, 4, 0, 0, 0 }));

            // Offset
            Array.Clear(result, 0, result.Length);
            Assert.That(target.CopyTo(0, result, 1, result.Length), Is.EqualTo(target.Count));
            Assert.That(result, Is.EqualTo(new int[] { 0, 2, 3, 4, 0 }));

            // Length
            Array.Clear(result, 0, result.Length);
            Assert.That(target.CopyTo(0, result, 0, result.Length - 1), Is.EqualTo(target.Count));
            Assert.That(result, Is.EqualTo(new int[] { 2, 3, 4, 0, 0 }));

            Array.Clear(result, 0, result.Length);
            Assert.That(target.CopyTo(0, result, 0, target.Count - 1), Is.EqualTo(target.Count - 1));
            Assert.That(result, Is.EqualTo(new int[] { 2, 3, 0, 0, 0 }));

            Array.Clear(result, 0, result.Length);
            Assert.That(target.CopyTo(0, result, 0, 0), Is.EqualTo(0));
            Assert.That(result, Is.EqualTo(new int[] { 0, 0, 0, 0, 0 }));

            Array.Clear(result, 0, result.Length);
            Assert.That(target.CopyTo(0, result, 0, 1), Is.EqualTo(1));
            Assert.That(result, Is.EqualTo(new int[] { 2, 0, 0, 0, 0 }));
        }
Example #25
0
    public static void TestCopyTo()
    {
        {
            string[] src;
            IList<string> seg;

            src = new string[] { "0", "1", "2", "3", "4" };
            seg = new ArraySegment<string>(src, 1, 3);
            seg.CopyTo(src, 2);
            Assert.Equal(src, new string[] { "0", "1", "1", "2", "3" });

            src = new string[] { "0", "1", "2", "3", "4" };
            seg = new ArraySegment<string>(src, 1, 3);
            seg.CopyTo(src, 0);
            Assert.Equal(src, new string[] { "1", "2", "3", "3", "4" });
        }

        {
            int[] src;
            IList<int> seg;

            src = new int[] { 0, 1, 2, 3, 4 };
            seg = new ArraySegment<int>(src, 1, 3);
            seg.CopyTo(src, 2);
            Assert.Equal(src, new int[] { 0, 1, 1, 2, 3 });

            src = new int[] { 0, 1, 2, 3, 4 };
            seg = new ArraySegment<int>(src, 1, 3);
            seg.CopyTo(src, 0);
            Assert.Equal(src, new int[] { 1, 2, 3, 3, 4 });
        }
    }
        public X509Certificate2 NewChainedCertificate(
            DistinguishedName distinguishedName,
            BasicConstraints basicConstraints,
            ValidityPeriod validityPeriod,
            SubjectAlternativeName subjectAlternativeName,
            X509Certificate2 signingCertificate,
            OidCollection enhancedKeyUsages,
            X509KeyUsageFlags x509KeyUsageFlags)
        {
            if (signingCertificate == null)
            {
                throw new ArgumentNullException(nameof(signingCertificate));
            }
            if (!signingCertificate.HasPrivateKey)
            {
                throw new Exception("Signing cert must have private key");
            }

            using var ecdsa = ECDsa.Create("ECDsa");
            ecdsa.KeySize   = 256;
            var request = new CertificateRequest(
                _certificateUtility.CreateIssuerOrSubject(distinguishedName),
                ecdsa,
                HashAlgorithmName.SHA256);

            _certificateUtility.AddBasicConstraints(request, basicConstraints);
            _certificateUtility.AddExtendedKeyUsages(request, x509KeyUsageFlags);

            // set the AuthorityKeyIdentifier. There is no built-in
            // support, so it needs to be copied from the Subject Key
            // Identifier of the signing certificate and massaged slightly.
            // AuthorityKeyIdentifier is "KeyID=<subject key identifier>"
            var issuerSubjectKey       = signingCertificate.Extensions["Subject Key Identifier"].RawData;
            var segment                = new ArraySegment <byte>(issuerSubjectKey, 2, issuerSubjectKey.Length - 2);
            var authorityKeyIdentifier = new byte[segment.Count + 4];

            // "KeyID" bytes
            authorityKeyIdentifier[0] = 0x30;
            authorityKeyIdentifier[1] = 0x16;
            authorityKeyIdentifier[2] = 0x80;
            authorityKeyIdentifier[3] = 0x14;
            segment.CopyTo(authorityKeyIdentifier, 4);
            request.CertificateExtensions.Add(new X509Extension("2.5.29.35", authorityKeyIdentifier, false));

            _certificateUtility.AddSubjectAlternativeName(request, subjectAlternativeName);

            // Enhanced key usages
            request.CertificateExtensions.Add(
                new X509EnhancedKeyUsageExtension(enhancedKeyUsages, false));

            // add this subject key identifier
            request.CertificateExtensions.Add(
                new X509SubjectKeyIdentifierExtension(request.PublicKey, false));

            // certificate expiry: Valid from Yesterday to Now+365 days
            // Unless the signing cert's validity is less. It's not possible
            // to create a cert with longer validity than the signing cert.
            var notbefore = validityPeriod.ValidFrom.AddDays(-1);

            if (notbefore < signingCertificate.NotBefore)
            {
                notbefore = new DateTimeOffset(signingCertificate.NotBefore);
            }

            var notafter = validityPeriod.ValidTo;

            if (notafter > signingCertificate.NotAfter)
            {
                notafter = new DateTimeOffset(signingCertificate.NotAfter);
            }

            // cert serial is the epoch/unix timestamp
            var epoch    = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc);
            var unixTime = Convert.ToInt64((DateTime.UtcNow - epoch).TotalSeconds);
            var serial   = BitConverter.GetBytes(unixTime);

            // create and return the generated and signed
            using var cert = request.Create(
                      signingCertificate,
                      notbefore,
                      notafter,
                      serial);
            return(cert.CopyWithPrivateKey(ecdsa));
        }
        /// <summary>
        /// Creates a new certificate with the given subject name and signs it with the
        /// certificate contained in the <paramref name="signingCertificate"/> parameter.
        /// </summary>
        /// <remarks>The generated certificate has the same attributes as the ones created
        /// by the IoT Hub Device Provisioning samples</remarks>
        /// <param name="subjectName">Subject name to give the new certificate</param>
        /// <param name="signingCertificate">Certificate to sign the new certificate with</param>
        /// <returns>A signed <see cref="X509Certificate2"/>.</returns>
        internal static X509Certificate2 CreateAndSignCertificate(string subjectName, X509Certificate2 signingCertificate)
        {
            if (signingCertificate == null)
            {
                throw new ArgumentNullException(nameof(signingCertificate));
            }
            if (!signingCertificate.HasPrivateKey)
            {
                throw new Exception("Signing cert must have private key");
            }
            if (string.IsNullOrEmpty(subjectName))
            {
                throw new ArgumentException($"{nameof(subjectName)} must be a valid DNS name", nameof(subjectName));
            }
            if (UriHostNameType.Unknown == Uri.CheckHostName(subjectName))
            {
                throw new ArgumentException("Must be a valid DNS name", nameof(subjectName));
            }

            using (var ecdsa = ECDsa.Create("ECDsa"))
            {
                ecdsa.KeySize = 256;
                var request = new CertificateRequest(
                    $"CN={subjectName}",
                    ecdsa,
                    HashAlgorithmName.SHA256);

                // set basic certificate contraints
                request.CertificateExtensions.Add(
                    new X509BasicConstraintsExtension(false, false, 0, true));

                // key usage: Digital Signature and Key Encipherment
                request.CertificateExtensions.Add(
                    new X509KeyUsageExtension(
                        X509KeyUsageFlags.DigitalSignature | X509KeyUsageFlags.KeyEncipherment,
                        true));

                // set the AuthorityKeyIdentifier. There is no built-in
                // support, so it needs to be copied from the Subject Key
                // Identifier of the signing certificate and massaged slightly.
                // AuthorityKeyIdentifier is "KeyID=<subject key identifier>"
                var issuerSubjectKey      = signingCertificate.Extensions["Subject Key Identifier"].RawData;
                var segment               = new ArraySegment <byte>(issuerSubjectKey, 2, issuerSubjectKey.Length - 2);
                var authorityKeyIdentifer = new byte[segment.Count + 4];
                // these bytes define the "KeyID" part of the AuthorityKeyIdentifer
                authorityKeyIdentifer[0] = 0x30;
                authorityKeyIdentifer[1] = 0x16;
                authorityKeyIdentifer[2] = 0x80;
                authorityKeyIdentifer[3] = 0x14;
                segment.CopyTo(authorityKeyIdentifer, 4);
                request.CertificateExtensions.Add(new X509Extension("2.5.29.35", authorityKeyIdentifer, false));

                // DPS samples create certs with the device name as a SAN name
                // in addition to the subject name
                var sanBuilder = new SubjectAlternativeNameBuilder();
                sanBuilder.AddDnsName(subjectName);
                var sanExtension = sanBuilder.Build();
                request.CertificateExtensions.Add(sanExtension);

                // Enhanced key usages
                request.CertificateExtensions.Add(
                    new X509EnhancedKeyUsageExtension(
                        new OidCollection {
                    new Oid("1.3.6.1.5.5.7.3.2"),         // TLS Client auth
                    new Oid("1.3.6.1.5.5.7.3.1")          // TLS Server auth
                },
                        false));

                // add this subject key identifier
                request.CertificateExtensions.Add(
                    new X509SubjectKeyIdentifierExtension(request.PublicKey, false));

                // certificate expiry: Valid from Yesterday to Now+365 days
                // Unless the signing cert's validity is less. It's not possible
                // to create a cert with longer validity than the signing cert.
                var notbefore = DateTimeOffset.UtcNow.AddDays(-1);
                if (notbefore < signingCertificate.NotBefore)
                {
                    notbefore = new DateTimeOffset(signingCertificate.NotBefore);
                }
                var notafter = DateTimeOffset.UtcNow.AddDays(365);
                if (notafter > signingCertificate.NotAfter)
                {
                    notafter = new DateTimeOffset(signingCertificate.NotAfter);
                }

                // cert serial is the epoch/unix timestamp
                var epoch    = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc);
                var unixTime = Convert.ToInt64((DateTime.UtcNow - epoch).TotalSeconds);
                var serial   = BitConverter.GetBytes(unixTime);

                // create and return the generated and signed
                using (var cert = request.Create(
                           signingCertificate,
                           notbefore,
                           notafter,
                           serial))
                {
                    return(cert.CopyWithPrivateKey(ecdsa));
                }
            }
        }
        internal static X509Certificate2 CreateCaCertificate(string subjectName, string certificatePassword,
                                                             X509Certificate2 issuingCa)
        {
            using (var ecdsa = ECDsa.Create("ECDsa"))
            {
                ecdsa.KeySize = 256;
                var request = new CertificateRequest(
                    $"CN={subjectName}",
                    ecdsa,
                    HashAlgorithmName.SHA256);

                // set basic certificate contraints
                request.CertificateExtensions.Add(
                    new X509BasicConstraintsExtension(true, true, 12, true));

                // key usage: Digital Signature and Key Encipherment
                request.CertificateExtensions.Add(
                    new X509KeyUsageExtension(
                        X509KeyUsageFlags.KeyCertSign,
                        true));

                if (issuingCa != null)
                {
                    // set the AuthorityKeyIdentifier. There is no built-in
                    // support, so it needs to be copied from the Subject Key
                    // Identifier of the signing certificate and massaged slightly.
                    // AuthorityKeyIdentifier is "KeyID=<subject key identifier>"
                    var issuerSubjectKey       = issuingCa.Extensions["Subject Key Identifier"].RawData;
                    var segment                = new ArraySegment <byte>(issuerSubjectKey, 2, issuerSubjectKey.Length - 2);
                    var authorityKeyIdentifier = new byte[segment.Count + 4];
                    // these bytes define the "KeyID" part of the AuthorityKeyIdentifer
                    authorityKeyIdentifier[0] = 0x30;
                    authorityKeyIdentifier[1] = 0x16;
                    authorityKeyIdentifier[2] = 0x80;
                    authorityKeyIdentifier[3] = 0x14;
                    segment.CopyTo(authorityKeyIdentifier, 4);
                    request.CertificateExtensions.Add(new X509Extension("2.5.29.35", authorityKeyIdentifier, false));
                }
                // DPS samples create certs with the device name as a SAN name
                // in addition to the subject name
                var sanBuilder = new SubjectAlternativeNameBuilder();
                sanBuilder.AddDnsName(subjectName);
                var sanExtension = sanBuilder.Build();
                request.CertificateExtensions.Add(sanExtension);

                // Enhanced key usages
                request.CertificateExtensions.Add(
                    new X509EnhancedKeyUsageExtension(
                        new OidCollection {
                    new Oid("1.3.6.1.5.5.7.3.2"),         // TLS Client auth
                    new Oid("1.3.6.1.5.5.7.3.1")          // TLS Server auth
                },
                        false));

                // add this subject key identifier
                request.CertificateExtensions.Add(
                    new X509SubjectKeyIdentifierExtension(request.PublicKey, false));

                // certificate expiry: Valid from Yesterday to Now+365 days
                // Unless the signing cert's validity is less. It's not possible
                // to create a cert with longer validity than the signing cert.
                var notbefore = DateTimeOffset.UtcNow.AddDays(-1);
                if ((issuingCa != null) && (notbefore < issuingCa.NotBefore))
                {
                    notbefore = new DateTimeOffset(issuingCa.NotBefore);
                }
                var notafter = DateTimeOffset.UtcNow.AddDays(365);
                if ((issuingCa != null) && (notafter > issuingCa.NotAfter))
                {
                    notafter = new DateTimeOffset(issuingCa.NotAfter);
                }

                // cert serial is the epoch/unix timestamp
                var epoch    = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc);
                var unixTime = Convert.ToInt64((DateTime.UtcNow - epoch).TotalSeconds);
                var serial   = BitConverter.GetBytes(unixTime);

                X509Certificate2 generatedCertificate = null;
                if (issuingCa != null)
                {
                    generatedCertificate = request.Create(issuingCa, notbefore, notafter, serial);
                    return(generatedCertificate.CopyWithPrivateKey(ecdsa));
                }
                else
                {
                    generatedCertificate = request.CreateSelfSigned(
                        notbefore, notafter);
                    return(generatedCertificate);
                }
            }
        }
		public void TestCopyTo_EmptyArraySegment()
		{
			var array = new int[] { 1 };
			var target = new ArraySegment<int>( array, 0, 0 );
			var result = new int[ 5 ];
			Assert.That( target.CopyTo( 0, result, 0, 1 ), Is.EqualTo( 0 ) );
		}
		public void TestCopyTo_SmallArray()
		{
			var array = new int[] { 1, 2, 3 };
			var target = new ArraySegment<int>( array );
			var result = new int[ 2 ];
			Assert.That( target.CopyTo( 0, result, 0, result.Length ), Is.EqualTo( 2 ) );
			Assert.That( result, Is.EqualTo( new int[] { 1, 2 } ) );
		}
Example #31
0
		public void IList_CopyTo ()
		{
			var array = new long[] { 1, 2, 3, 4, 5, 6, -10 };

			IList<long> s = new ArraySegment<long> (array, 2, 3);
			long[] target = new long[s.Count];
			s.CopyTo (target, 0);

			Assert.AreEqual (3, target[0], "#1");
			Assert.AreEqual (4, target[1], "#2");
		}
Example #32
0
        internal static void CopyTo <T>(this T[] src, int srcOffset, IList <T> dst, int dstOffset, int count)
        {
            var srcArray = new ArraySegment <T>(src);

            srcArray.CopyTo(srcOffset, dst, dstOffset, count);
        }
Example #33
0
        unsafe UIntPtr NativeRead(SDL_RWops *io, byte *ptr, UIntPtr size, UIntPtr maxnum)
        {
            if (Implementation == null)
            {
                SetError($"{nameof(RWOpsFromInterface)} is missing an implementation to call");
                return(UIntPtr.Zero);
            }
            try
            {
                for (ulong i = 0; i < (ulong)maxnum; ++i)
                {
                    if (partial.Count < (int)size)
                    {
                        if (partial.Count > 0)
                        {
                            var arr = partial.Array;
                            System.Diagnostics.Debug.Assert(arr.Length > 0);
                            var l = partial.Count;
                            partial.CopyTo(arr);
                            partial = arr;
                            partial = partial.Slice(l);
                        }
                        else
                        {
                            partial = partial.Array;
                        }

                        Span <byte> buffer = partial;
                        try
                        {
                            int read = Implementation.Read(buffer);
                            if (read == 0)
                            {
                                return((UIntPtr)i - 1);
                            }
                            if (read < partial.Count)
                            {
                                partial = partial.Slice(0, read);
                            }
                        }
                        catch (Exception ex)
                        {
                            SetError(ex);
                            return((UIntPtr)i - 1);
                        }

                        if (partial.Count < (int)size)
                        {
                            return((UIntPtr)i - 1);
                        }
                    }

                    var         target = new Span <byte>(ptr + i * (ulong)size, (int)size);
                    Span <byte> src    = partial.Slice(0, (int)size);
                    partial = partial.Slice((int)size);
                    src.CopyTo(target);
                }
                return(maxnum);
            }
            catch (Exception ex)
            {
                SetError(ex);
                return(UIntPtr.Zero);
            }
        }
Example #34
0
        public async ValueTask InitializeAsync(CancellationToken cancel)
        {
            await _underlying.InitializeAsync(cancel).ConfigureAwait(false);

            try
            {
                // The server waits for the client's upgrade request, the client sends the upgrade request.
                if (!_incoming)
                {
                    // Compose the upgrade request.
                    var sb = new StringBuilder();
                    sb.Append("GET " + _resource + " HTTP/1.1\r\n");
                    sb.Append("Host: " + _host + "\r\n");
                    sb.Append("Upgrade: websocket\r\n");
                    sb.Append("Connection: Upgrade\r\n");
                    sb.Append("Sec-WebSocket-Protocol: " + IceProtocol + "\r\n");
                    sb.Append("Sec-WebSocket-Version: 13\r\n");
                    sb.Append("Sec-WebSocket-Key: ");

                    // The value for Sec-WebSocket-Key is a 16-byte random number, encoded with Base64.
                    byte[] key = new byte[16];
                    _rand.NextBytes(key);
                    _key = Convert.ToBase64String(key);
                    sb.Append(_key + "\r\n\r\n"); // EOM
                    byte[] data = _utf8.GetBytes(sb.ToString());
                    _sendBuffer.Add(data);

                    await _underlying.SendAsync(_sendBuffer, cancel).ConfigureAwait(false);
                }
                _sendBuffer.Clear();

                // Try to read the client's upgrade request or the server's response.
                var httpBuffer = new ArraySegment <byte>();
                while (true)
                {
                    ReadOnlyMemory <byte> buffer = await _underlying.ReceiveAsync(0, cancel).ConfigureAwait(false);

                    if (httpBuffer.Count + buffer.Length > _communicator.IncomingFrameSizeMax)
                    {
                        throw new InvalidDataException(
                                  "WebSocket frame size is greater than the configured IncomingFrameSizeMax value");
                    }

                    ArraySegment <byte> tmpBuffer = new byte[httpBuffer.Count + buffer.Length];
                    if (httpBuffer.Count > 0)
                    {
                        httpBuffer.CopyTo(tmpBuffer);
                    }
                    buffer.CopyTo(tmpBuffer.Slice(httpBuffer.Count));
                    httpBuffer = tmpBuffer;

                    // Check if we have enough data for a complete frame.
                    int endPos = HttpParser.IsCompleteMessage(httpBuffer);
                    if (endPos != -1)
                    {
                        // Add back the un-consumed data to the buffer.
                        _underlying.Rewind(httpBuffer.Count - endPos);
                        httpBuffer = httpBuffer.Slice(0, endPos);
                        break; // Done
                    }
                }

                try
                {
                    if (_parser.Parse(httpBuffer))
                    {
                        if (_incoming)
                        {
                            (bool addProtocol, string key) = ReadUpgradeRequest();

                            // Compose the response.
                            var sb = new StringBuilder();
                            sb.Append("HTTP/1.1 101 Switching Protocols\r\n");
                            sb.Append("Upgrade: websocket\r\n");
                            sb.Append("Connection: Upgrade\r\n");
                            if (addProtocol)
                            {
                                sb.Append($"Sec-WebSocket-Protocol: {IceProtocol}\r\n");
                            }

                            // The response includes:
                            //
                            // "A |Sec-WebSocket-Accept| header field.  The value of this header field is constructed
                            // by concatenating /key/, defined above in step 4 in Section 4.2.2, with the string
                            // "258EAFA5-E914-47DA-95CA-C5AB0DC85B11", taking the SHA-1 hash of this concatenated value
                            // to obtain a 20-byte value and base64-encoding (see Section 4 of [RFC4648]) this 20-byte
                            // hash.
                            sb.Append("Sec-WebSocket-Accept: ");
                            string input = key + WsUUID;
#pragma warning disable CA5350 // Do Not Use Weak Cryptographic Algorithms
                            using var sha1 = SHA1.Create();
                            byte[] hash = sha1.ComputeHash(_utf8.GetBytes(input));
#pragma warning restore CA5350                                                         // Do Not Use Weak Cryptographic Algorithms
                            sb.Append(Convert.ToBase64String(hash) + "\r\n" + "\r\n"); // EOM

                            Debug.Assert(_sendBuffer.Count == 0);
                            byte[] data = _utf8.GetBytes(sb.ToString());
                            _sendBuffer.Add(data);
                            await _underlying.SendAsync(_sendBuffer, cancel).ConfigureAwait(false);

                            _sendBuffer.Clear();
                        }
                        else
                        {
                            ReadUpgradeResponse();
                        }
                    }
                    else
                    {
                        throw new InvalidDataException("incomplete WebSocket request frame");
                    }
                }
                catch (WebSocketException ex)
                {
                    throw new InvalidDataException(ex.Message, ex);
                }
            }
            catch (Exception ex)
            {
                if (_communicator.TraceLevels.Transport >= 2)
                {
                    _communicator.Logger.Trace(TraceLevels.TransportCategory,
                                               $"{_transportName} connection HTTP upgrade request failed\n{this}\n{ex}");
                }
                throw;
            }

            if (_communicator.TraceLevels.Transport >= 1)
            {
                if (_incoming)
                {
                    _communicator.Logger.Trace(TraceLevels.TransportCategory,
                                               $"accepted {_transportName} connection HTTP upgrade request\n{this}");
                }
                else
                {
                    _communicator.Logger.Trace(TraceLevels.TransportCategory,
                                               $"{_transportName} connection HTTP upgrade request accepted\n{this}");
                }
            }
        }
Example #35
0
 internal bool TryLoopbackToServer(ArraySegment <byte> packet)
 {
     if (IsServer)
     {
         var p = new PureP2PPeer(true);
         _loopbackToServer.Add(new KeyValuePair <PureP2PPeer, ArraySegment <byte> >(p, packet.CopyTo(_loopbackBuffers.Get())));
         return(true);
     }
     return(false);
 }
Example #36
0
    public static void TestIList_CopyTo_Invalid()
    {
        IList<int> iList = new ArraySegment<int>();
        Assert.Throws<InvalidOperationException>(() => iList.CopyTo(new int[7], 0)); // Array is null

        var intArray = new int[] { 7, 8, 9, 10, 11, 12, 13 };
        iList = new ArraySegment<int>(intArray, 2, 3);

        Assert.Throws<ArgumentNullException>("dest", () => iList.CopyTo(null, 0)); // Destination array is null

        Assert.Throws<ArgumentOutOfRangeException>("dstIndex", () => iList.CopyTo(new int[7], -1)); // Index < 0
        Assert.Throws<ArgumentException>("", () => iList.CopyTo(new int[7], 8)); // Index > destinationArray.Length
    }
Example #37
0
        private void ROMix(ArraySegment<byte> B, byte[] X, byte[] Y, byte[] V)
        {
            B.CopyTo(X, 0);

            for (int i = 0; i < Cost; ++i)
            {
                Array.Copy(X, 0, V, i * (128 * BlockSize), 128 * BlockSize);
                BlockMix(X, Y);
            }

            for (int i = 0; i < Cost; ++i)
            {
                ulong j = BitConverter.ToUInt64(X, (2 * BlockSize - 1) * 64);
                j %= (ulong)Cost;

                for (int k = 0; k < 128 * BlockSize; ++k)
                {
                    X[k] ^= V[j * (128 * (ulong)BlockSize) + (ulong)k];
                }
                BlockMix(X, Y);
            }

            ArraySegment<byte>.Copy(X, B, 128 * BlockSize);
        }
		public void TestCopyTo_EmptySourceArray()
		{
			var array = new int[ 0 ];
			var target = new ArraySegment<int>( array );
			var result = new int[ 5 ];
			Assert.That( target.CopyTo( 0, result, 0, 1 ), Is.EqualTo( 0 ) );
		}
Example #39
0
    public static void TestIList_CopyTo()
    {
        var stringArray = new string[] { "0", "1", "2", "3", "4" };
        IList<string> stringSegment = new ArraySegment<string>(stringArray, 1, 3);
        stringSegment.CopyTo(stringArray, 2);
        Assert.Equal(new string[] { "0", "1", "1", "2", "3" }, stringArray);

        stringArray = new string[] { "0", "1", "2", "3", "4" };
        stringSegment = new ArraySegment<string>(stringArray, 1, 3);
        stringSegment.CopyTo(stringArray, 0);
        Assert.Equal(new string[] { "1", "2", "3", "3", "4" }, stringArray);

        var intArray = new int[] { 0, 1, 2, 3, 4 };
        IList<int> intSegment = new ArraySegment<int>(intArray, 1, 3);
        intSegment.CopyTo(intArray, 2);
        Assert.Equal(new int[] { 0, 1, 1, 2, 3 }, intArray);

        intArray = new int[] { 0, 1, 2, 3, 4 };
        intSegment = new ArraySegment<int>(intArray, 1, 3);
        intSegment.CopyTo(intArray, 0);
        Assert.Equal(new int[] { 1, 2, 3, 3, 4 }, intArray);
    }