Exemplo n.º 1
0
 public void ArrayEqualToItself()
 {
     byte[] b = { 0, 1, 2, 3, 4, 5, 6 };
     Assert.Equal(0, _comparer.Compare(b, b));
     Assert.True(ByteArrayComparer.ArraysEqual(b, b));
     Assert.True(_comparer.Equals(b, b));
 }
Exemplo n.º 2
0
        static ICollection <CacheValue> Resolve(ICollection <byte[]> keys)
        {
            if (keys.Count == 0)
            {
                return(Array.Empty <CacheValue>());
            }
            var result   = new List <CacheValue>();
            var comparer = new ByteArrayComparer();

            using (var ms = new MemoryStream())
                foreach (var key in keys)
                {
                    ms.SetLength(0);
                    ms.Write(key, 0, key.Length);
                    ms.Position = 0;
                    var k      = ProtoBuf.Serializer.Deserialize <byte[]>(ms);
                    var hash   = comparer.GetHashCode(k);
                    var random = new Random(hash);
                    var length = Math.Max((hash & 0xff) << 8, 256);
                    var data   = new byte[length];
                    random.NextBytes(data);
                    ms.SetLength(0);
                    ProtoBuf.Serializer.Serialize(ms, data);

                    result.Add(new CacheValue(key, ms.ToArray(), TimeSpan.FromSeconds(60)));
                }

            return(result);
        }
Exemplo n.º 3
0
        public static FileType GetFileType(FileInfo file)
        {
            byte[] markerMKV = new byte[] { 0x1A, 0x45, 0xDF, 0xA3 };
            byte[] markerAVI = new byte[] { 0x52, 0x49, 0x46, 0x46 };
            byte[] markerRAR = new byte[] { 0x52, 0x61, 0x72, 0x21 };

            byte[] fileHeader = new byte[4];
            using (FileStream fs = file.OpenRead())
                fs.Read(fileHeader, 0, 4);

            if (ByteArrayComparer.AreEqual(fileHeader, markerRAR))
            {
                using (RarStream rs = new RarStream(file.FullName))
                    rs.Read(fileHeader, 0, 4);
            }

            if (ByteArrayComparer.AreEqual(fileHeader, markerMKV))
            {
                return(FileType.MKV);
            }
            else if (ByteArrayComparer.AreEqual(fileHeader, markerAVI))
            {
                return(FileType.AVI);
            }
            else
            {
                return(FileType.Unknown);
            }
        }
Exemplo n.º 4
0
        public void TestCompare()
        {
            ByteArrayComparer comparer = ByteArrayComparer.Default;

            byte[] x = new byte[0], y = new byte[0];
            comparer.Compare(x, y).Should().Be(0);

            x = new byte[] { 1 };
            comparer.Compare(x, y).Should().Be(1);
            y = x;
            comparer.Compare(x, y).Should().Be(0);

            x = new byte[] { 1 };
            y = new byte[] { 2 };
            comparer.Compare(x, y).Should().Be(-1);

            comparer = ByteArrayComparer.Reverse;
            x        = new byte[] { 3 };
            comparer.Compare(x, y).Should().Be(-1);
            y = x;
            comparer.Compare(x, y).Should().Be(0);

            x = new byte[] { 1 };
            y = new byte[] { 2 };
            comparer.Compare(x, y).Should().Be(1);
        }
Exemplo n.º 5
0
 public void UnequalLengthsNotEqual()
 {
     Assert.NotEqual(0, _comparer.Compare(new byte[] { 0 }, new byte[0]));
     Assert.NotEqual(0, _comparer.Compare(new byte[0], new byte[] { 0 }));
     Assert.False(ByteArrayComparer.ArraysEqual(new byte[0], new byte[] { 0 }));
     Assert.False(_comparer.Equals(new byte[0], new byte[] { 0 }));
     Assert.NotEqual(_comparer.GetHashCode(new byte[0]), _comparer.GetHashCode(new byte[] { 0 }));
 }
Exemplo n.º 6
0
        /// <summary>
        /// Checks whether the verified server ID matches the expected identifier.
        /// </summary>
        /// <param name="Id">Network identifier that the caller expects.</param>
        /// <returns>true if the server ID matches the expected identifier, false otherwise.</returns>
        public bool MatchServerId(byte[] Id)
        {
            log.Trace("(Id:'{0}',serverId:'{1}')", Id.ToHex(), serverId.ToHex());

            bool res = ByteArrayComparer.Equals(Id, serverId);

            log.Trace("(-):{0}", res);
            return(res);
        }
Exemplo n.º 7
0
 public IEnumerable<(byte[] Key, byte[] Value)> Seek(byte table, byte[] keyOrPrefix, SeekDirection direction = SeekDirection.Forward)
 {
     ByteArrayComparer comparer = direction == SeekDirection.Forward ? ByteArrayComparer.Default : ByteArrayComparer.Reverse;
     IEnumerable<KeyValuePair<byte[], byte[]>> records = immutableData[table];
     if (keyOrPrefix?.Length > 0)
         records = records.Where(p => comparer.Compare(p.Key, keyOrPrefix) >= 0);
     records = records.OrderBy(p => p.Key, comparer);
     return records.Select(p => (p.Key, p.Value));
 }
Exemplo n.º 8
0
        /// <summary>
        /// Seek to the entry with specific key
        /// </summary>
        /// <param name="keyOrPrefix">The key to be sought</param>
        /// <param name="direction">The direction of seek</param>
        /// <returns>An enumerator containing all the entries after seeking.</returns>
        public IEnumerable <(TKey Key, TValue Value)> Seek(byte[] keyOrPrefix = null, SeekDirection direction = SeekDirection.Forward)
        {
            IEnumerable <(byte[], TKey, TValue)> cached;
            HashSet <TKey>    cachedKeySet;
            ByteArrayComparer comparer = direction == SeekDirection.Forward ? ByteArrayComparer.Default : ByteArrayComparer.Reverse;

            lock (dictionary)
            {
                cached = dictionary
                         .Where(p => p.Value.State != TrackState.Deleted && (keyOrPrefix == null || comparer.Compare(p.Key.ToArray(), keyOrPrefix) >= 0))
                         .Select(p =>
                                 (
                                     KeyBytes: p.Key.ToArray(),
                                     p.Key,
                                     p.Value.Item
                                 ))
                         .OrderBy(p => p.KeyBytes, comparer)
                         .ToArray();
                cachedKeySet = new HashSet <TKey>(dictionary.Keys);
            }
            var uncached = SeekInternal(keyOrPrefix ?? Array.Empty <byte>(), direction)
                           .Where(p => !cachedKeySet.Contains(p.Key))
                           .Select(p =>
                                   (
                                       KeyBytes: p.Key.ToArray(),
                                       p.Key,
                                       p.Value
                                   ));

            using (var e1 = cached.GetEnumerator())
                using (var e2 = uncached.GetEnumerator())
                {
                    (byte[] KeyBytes, TKey Key, TValue Item)i1, i2;
                    bool c1 = e1.MoveNext();
                    bool c2 = e2.MoveNext();
                    i1 = c1 ? e1.Current : default;
                    i2 = c2 ? e2.Current : default;
                    while (c1 || c2)
                    {
                        if (!c2 || (c1 && comparer.Compare(i1.KeyBytes, i2.KeyBytes) < 0))
                        {
                            yield return(i1.Key, i1.Item);

                            c1 = e1.MoveNext();
                            i1 = c1 ? e1.Current : default;
                        }
                        else
                        {
                            yield return(i2.Key, i2.Item);

                            c2 = e2.MoveNext();
                            i2 = c2 ? e2.Current : default;
                        }
                    }
                }
        }
Exemplo n.º 9
0
        public override List <string> GetDifferences(Chunk xiChunk)
        {
            if (ByteArrayComparer.CompareStatic(mData, ((RawDataChunk)xiChunk).mData) != 0)
            {
                List <string> lRet = base.GetDifferences(xiChunk);
                lRet.Add("Changed data named " + GivenName);
                return(lRet);
            }

            return(base.GetDifferences(xiChunk));
        }
Exemplo n.º 10
0
        /// <summary>
        /// Verifies whether the server successfully signed the correct start conversation challenge.
        /// </summary>
        /// <param name="StartConversationResponse">StartConversationResponse received from the server.</param>
        /// <returns>true if the signature is valid, false otherwise.</returns>
        public bool VerifyServerChallengeSignature(ProxProtocolMessage StartConversationResponse)
        {
            log.Trace("()");

            byte[] receivedChallenge = StartConversationResponse.Response.ConversationResponse.Start.ClientChallenge.ToByteArray();
            bool   res = ByteArrayComparer.Equals(receivedChallenge, clientChallenge) &&
                         MessageBuilder.VerifySignedConversationResponseBodyPart(StartConversationResponse, receivedChallenge, serverKey);

            log.Trace("(-):{0}", res);
            return(res);
        }
Exemplo n.º 11
0
        /// <summary>
        /// Compares this activity to other activity and returns list of changed properties.
        /// </summary>
        /// <param name="Other">Other activity to compare to.</param>
        /// <returns>Bit mask information about which properties are different.</returns>
        public ActivityChange CompareChangeTo(NeighborActivity Other)
        {
            ActivityChange res = base.CompareChangeTo(Other);

            if (!ByteArrayComparer.Equals(this.PrimaryServerId, Other.PrimaryServerId))
            {
                res |= ActivityChange.PrimaryServerId;
            }

            return(res);
        }
Exemplo n.º 12
0
        public override List <string> GetDifferences(Chunk xiChunk)
        {
            if (ByteArrayComparer.CompareStatic(mData, ((BumpImageChunk)xiChunk).mData) != 0)
            {
                List <string> lRet = base.GetDifferences(xiChunk);
                lRet.Add("Changed bump #" + mIdx.ToString());
                return(lRet);
            }

            return(base.GetDifferences(xiChunk));
        }
Exemplo n.º 13
0
        public async Task OpenListener_ReceiveWrongPacket()
        {
            await Task.Delay(2000);

            Random random   = new Random();
            var    comparer = new ByteArrayComparer();

            Byte[] randomBytes     = random.NextBytes(20);
            Int32  packetsReceived = 0;

            var serviceBusMock = new Mock <IServiceBus>(MockBehavior.Strict);

            serviceBusMock.Setup(x => x.Publish(
                                     It.Is <InvalidDHCPv6PacketArrivedMessage>(y => comparer.Equals(y.Packet.GetAsStream(), randomBytes) == true))).Callback(() => packetsReceived++).Returns(Task.CompletedTask).Verifiable();

            Mock <ILoggerFactory> factoryMock = new Mock <ILoggerFactory>(MockBehavior.Strict);

            factoryMock.Setup(x => x.CreateLogger(It.IsAny <String>())).Returns(Mock.Of <ILogger <DHCPv6Server> >());

            IDHCPv6InterfaceEngine engine = new DHCPv6InterfaceEngine(
                serviceBusMock.Object,
                Mock.Of <IDHCPv6StorageEngine>(MockBehavior.Strict),
                factoryMock.Object
                );

            var possibleListener = engine.GetPossibleListeners();
            var listener         = possibleListener.First();

            engine.OpenListener(listener);

            IPAddress  address        = new IPAddress(listener.Address.GetBytes());
            IPEndPoint ownEndPoint    = new IPEndPoint(address, 546);
            IPEndPoint serverEndPoint = new IPEndPoint(address, 547);

            UdpClient client = new UdpClient(ownEndPoint);

            client.Send(randomBytes, randomBytes.Length, serverEndPoint);

            Int32 trysLeft = 100;

            while (trysLeft-- > 0 && packetsReceived == 0)
            {
                await Task.Delay(1000);
            }

            engine.CloseListener(listener);
            client.Dispose();

            Assert.Equal(1, packetsReceived);

            serviceBusMock.Verify(x => x.Publish(
                                      It.Is <InvalidDHCPv6PacketArrivedMessage>(y => comparer.Equals(y.Packet.GetAsStream(), randomBytes) == true)), Times.Once);
        }
        public void ByteArraysEqual_BoundsTest()
        {
            byte[] dummyBuffer = new byte[1];
            AssertThrows <IndexOutOfRangeException>(() => ByteArrayComparer.ByteArraysEqual(buffer, 1, buffer.Length, dummyBuffer, 0, 1));
            AssertThrows <IndexOutOfRangeException>(() => ByteArrayComparer.ByteArraysEqual(dummyBuffer, 0, 1, buffer, 1, buffer.Length));

            AssertThrows <IndexOutOfRangeException>(() => ByteArrayComparer.ByteArraysEqual(buffer, -1, 1, dummyBuffer, 0, 1));
            AssertThrows <IndexOutOfRangeException>(() => ByteArrayComparer.ByteArraysEqual(dummyBuffer, 0, 1, buffer, -1, 1));

            AssertThrows <IndexOutOfRangeException>(() => ByteArrayComparer.ByteArraysEqual(buffer, 1, -1, dummyBuffer, 0, 1));
            AssertThrows <IndexOutOfRangeException>(() => ByteArrayComparer.ByteArraysEqual(dummyBuffer, 0, 1, buffer, 1, -1));
        }
        public DateInterval Deserialize(ref JsonReader reader, IJsonFormatterResolver formatterResolver)
        {
            if (reader.ReadIsNull())
            {
                return(null);
            }

            var dateIntervalFormatter = formatterResolver.GetFormatter <LocalDate>();

            reader.ReadIsBeginObjectWithVerify();
            LocalDate?startLocalDate  = null;
            LocalDate?endLocalDate    = null;
            var       expectSeparator = false;

            while (!reader.ReadIsEndObject())
            {
                if (expectSeparator)
                {
                    reader.ReadIsValueSeparatorWithVerify();
                }
                var propertyName = reader.ReadPropertyNameSegmentRaw();

                if (ByteArrayComparer.Equals(propertyName.Array, propertyName.Offset, propertyName.Count,
                                             _startPropertyName))
                {
                    startLocalDate  = dateIntervalFormatter.Deserialize(ref reader, formatterResolver);
                    expectSeparator = true;
                }
                else if (ByteArrayComparer.Equals(propertyName.Array, propertyName.Offset, propertyName.Count,
                                                  _endPropertyName))
                {
                    endLocalDate    = dateIntervalFormatter.Deserialize(ref reader, formatterResolver);
                    expectSeparator = true;
                }
                else
                {
                    break;
                }
            }

            if (!startLocalDate.HasValue)
            {
                throw new InvalidNodaDataException("Expected date interval; start date was missing.");
            }

            if (!endLocalDate.HasValue)
            {
                throw new InvalidNodaDataException("Expected date interval; end date was missing.");
            }

            return(new DateInterval(startLocalDate.Value, endLocalDate.Value));
        }
 public void ByteArraysEqual_HappyPathTest()
 {
     for (var size = 0; size < 255; size++)
     {
         for (var i = 0; i < buffer.Length - size + 1; i++)
         {
             for (var j = 0; j < bufferCopy.Length - size + 1; j++)
             {
                 AssertEquals(i == j || size == 0, ByteArrayComparer.ByteArraysEqual(buffer, i, size, bufferCopy, j, size));
             }
         }
     }
 }
Exemplo n.º 17
0
            public void LowerContextInputLengthIs5()
            {
                byte[] input    = { 10, 11, 12, 13, 14 };
                byte[] expected = { 11, 12, 13, 14 };
                var    entry    = new Entry(11, input);

                entry.NextContext();
                var actual = entry.Context;

                var byteArrayComparer = new ByteArrayComparer();

                Assert.AreEqual(0, byteArrayComparer.Compare(expected, actual));
            }
Exemplo n.º 18
0
        /// <summary>
        /// Find the entries that between [start, end)
        /// </summary>
        /// <param name="direction">The search direction.</param>
        /// <returns>Entries found with the desired range</returns>
        public IEnumerable <(TKey Key, TValue Value)> FindRange(byte[] start, byte[] end, SeekDirection direction = SeekDirection.Forward)
        {
            ByteArrayComparer comparer = direction == SeekDirection.Forward
                ? ByteArrayComparer.Default
                : ByteArrayComparer.Reverse;

            foreach (var(key, value) in Seek(start, direction))
            {
                if (comparer.Compare(key.ToArray(), end) < 0)
                {
                    yield return(key, value);
                }
            }
        }
Exemplo n.º 19
0
        public void StructuralEqualityComparer()
        {
            List <byte[]> inputs = new List <byte[]>()
            {
                null,
                null,
                new byte[] { },
                new byte[] { },
                new byte[] { 1 },
                new byte[] { 1, 2, 3 },
                new byte[] { 4, 5, 6 },
                new byte[] { 1, 2, 3 },
            };

            List <bool> expectedResults = new List <bool>()
            {
                // null #1 vs others
                true, false, false, false, false, false, false,

                // null #2 vs others
                false, false, false, false, false, false,

                // empty #1 array vs others
                true, false, false, false, false,

                // empty #2 array vs others
                false, false, false, false,

                // { 1 } vs others
                false, false, false,

                // { 1, 2, 3 } vs others
                false, true,

                // { 4, 5, 6 } vs others
                false,
            };

            int index = 0;

            for (int i = 0; i < inputs.Count - 1; i++)
            {
                for (int j = i + 1; j < inputs.Count; j++)
                {
                    Assert.Equal(expectedResults[index], ByteArrayComparer.Equals(inputs[i], inputs[j]));

                    index++;
                }
            }
        }
Exemplo n.º 20
0
        private static async Task <int> Send(IDistributedCacheClient <byte[], byte[]> client, int messages_per_thread, int seed, CancellationToken token)
        {
            var now       = DateTime.UtcNow;
            var requested = new Dictionary <byte[], DateTime>(new ByteArrayComparer());
            var comparer  = new ByteArrayComparer();
            var rand      = new Random(seed);

            for (var i = 0; i < messages_per_thread; i++)
            {
                var key = CreateId(rand);
                if (client.TryGet(key, out var data, out var expired) && !expired)
                {
                    requested.Remove(key, out var _);
                }
Exemplo n.º 21
0
        public void TestContentHashListsNoPayloadOrderInvalidation()
        {
            var vsoContentHash1 = ContentHash.Random();
            var vsoContentHash2 = ContentHash.Random();

            var contentHashList = new ContentHashList(new[] { vsoContentHash1, vsoContentHash2 });

            byte[] hashOfContentHashes = contentHashList.GetHashOfHashes();

            var secondOrderContentHashList = new ContentHashList(new[] { vsoContentHash2, vsoContentHash1 });

            byte[] secondOrderHashOfContentHashes = secondOrderContentHashList.GetHashOfHashes();

            ByteArrayComparer.ArraysEqual(hashOfContentHashes, secondOrderHashOfContentHashes).Should().BeFalse();
        }
Exemplo n.º 22
0
        public IEnumerable <(byte[] Key, byte[] Value)> Seek(byte table, byte[] keyOrPrefix, SeekDirection direction = SeekDirection.Forward)
        {
            ByteArrayComparer comparer = direction == SeekDirection.Forward ? ByteArrayComparer.Default : ByteArrayComparer.Reverse;
            IEnumerable <KeyValuePair <byte[], byte[]> > records = innerData[table];

            if (keyOrPrefix?.Length > 0)
            {
                records = records.Where(p => comparer.Compare(p.Key, keyOrPrefix) >= 0);
            }
            records = records.OrderBy(p => p.Key, comparer);
            foreach (var pair in records)
            {
                yield return(pair.Key, pair.Value);
            }
        }
Exemplo n.º 23
0
        public void TestCompare()
        {
            ByteArrayComparer comparer = new ByteArrayComparer();

            byte[] x = new byte[0], y = new byte[0];
            comparer.Compare(x, y).Should().Be(0);

            x = new byte[] { 1 };
            comparer.Compare(x, y).Should().Be(1);
            y = x;
            comparer.Compare(x, y).Should().Be(0);

            x = new byte[] { 1 };
            y = new byte[] { 2 };
            comparer.Compare(x, y).Should().Be(-1);
        }
Exemplo n.º 24
0
        public void TestContentHashListsEqualityCheckNoPayload()
        {
            var vsoContentHash1 = ContentHash.Random();
            var vsoContentHash2 = ContentHash.Random();

            var contentHashes   = new[] { vsoContentHash1, vsoContentHash2 };
            var contentHashList = new ContentHashList(contentHashes);

            byte[] hashOfContentHashes = contentHashList.GetHashOfHashes();

            var secondOrderContentHashList = new ContentHashList(contentHashes);

            byte[] secondOrderHashOfContentHashes = secondOrderContentHashList.GetHashOfHashes();

            ByteArrayComparer.ArraysEqual(hashOfContentHashes, secondOrderHashOfContentHashes).Should().BeTrue();
        }
Exemplo n.º 25
0
        public void TestContentHashListsPayloadDoesNotInvalidate()
        {
            var vsoContentHash1 = ContentHash.Random();
            var vsoContentHash2 = ContentHash.Random();

            var contentHashes   = new[] { vsoContentHash1, vsoContentHash2 };
            var contentHashList = new ContentHashList(contentHashes);

            byte[] hashOfContentHashes = contentHashList.GetHashOfHashes();

            var secondOrderContentHashList = new ContentHashList(contentHashes, ThreadSafeRandom.GetBytes(RandomBytesSize));

            byte[] secondOrderHashOfContentHashes = secondOrderContentHashList.GetHashOfHashes();

            ByteArrayComparer.ArraysEqual(hashOfContentHashes, secondOrderHashOfContentHashes).Should().BeTrue();
        }
Exemplo n.º 26
0
        public void TestContentHashListsEqualityCheckWithPayload()
        {
            var byteStream      = ThreadSafeRandom.GetBytes(RandomBytesSize);
            var vsoContentHash1 = ContentHash.Random();
            var vsoContentHash2 = ContentHash.Random();

            var contentHashes   = new[] { vsoContentHash1, vsoContentHash2 };
            var contentHashList = new ContentHashList(contentHashes, byteStream);

            byte[] hashOfContentHashes = contentHashList.GetHashOfHashes();

            var secondOrderContentHashList = new ContentHashList(contentHashes, byteStream);

            byte[] secondOrderHashOfContentHashes = secondOrderContentHashList.GetHashOfHashes();

            ByteArrayComparer.ArraysEqual(hashOfContentHashes, secondOrderHashOfContentHashes).Should().BeTrue();
        }
Exemplo n.º 27
0
 public void TestByteArrayComparer()
 {
     string[] ss = new string[] { "", "asd", "ass", "qwer", "qwe" };
       StringComparer sComp = StringComparer.InvariantCulture;
       ByteArrayComparer bComp = new ByteArrayComparer();
       for (int i=0; i<ss.Length; i++)
     for (int j = 0; j < ss.Length; j++)
     {
       string sa = ss[i];
       string sb = ss[j];
       byte[] ba = Encoding.ASCII.GetBytes(sa);
       byte[] bb = Encoding.ASCII.GetBytes(sb);
       Assert.AreEqual(
     sComp.Compare(sa, sb),
     bComp.Compare(ba, bb));
     }
 }
Exemplo n.º 28
0
        public void EqualityComparerTest()
        {
            byte[] key1 = Merkle.transactionHasher.Invoke(Util.GetNewTransaction(1));
            byte[] key2 = Merkle.transactionHasher.Invoke(Util.GetNewTransaction(1));

            EqualityComparer <byte[]> equalityComparer = EqualityComparer <byte[]> .Default;

            Assert.IsFalse(key1 == key2);                        // should fail
            Assert.IsFalse(key1.Equals(key2));                   // should fail
            Assert.IsFalse(equalityComparer.Equals(key1, key2)); // should fail

            Assert.IsTrue(Enumerable.SequenceEqual(key1, key2));

            ByteArrayComparer byteArrayComparer = new ByteArrayComparer();

            Assert.IsTrue(byteArrayComparer.Equals(key1, key2));
        }
Exemplo n.º 29
0
        /// <summary>
        /// Checks whether binary data represent a valid PNG or JPEG image and checks that the claimed hash matches the data.
        /// </summary>
        /// <param name="Data">Binary data to check.</param>
        /// <param name="ImageHash">Claimed image hash that has to be equal to SHA256 hash of <paramref name="Data"/> for the function to be able to succeed.</param>
        /// <returns>true if the data represents a valid PNG or JPEG image and if the data hash matches, false otherwise</returns>
        public static bool ValidateImageWithHash(byte[] Data, byte[] ImageHash)
        {
            log.Trace("(Data.Length:{0},ImageHash:'{1}')", Data.Length, ImageHash.ToHex());

            bool res = false;

            if (ValidateImageFormat(Data))
            {
                byte[] hash = Crypto.Sha256(Data);
                if (ByteArrayComparer.Equals(hash, ImageHash))
                {
                    res = true;
                }
            }

            log.Trace("(-):{0}", res);
            return(res);
        }
Exemplo n.º 30
0
        public void Compare()
        {
            for (int i = 0; i < 200; i++)
            {
                for (int j = 0; j < Math.Min(10, i); j++)
                {
                    var xs = Enumerable.Range(1, i).Select(x => (byte)x).ToArray();
                    var ys = xs.ToArray();

                    ByteArrayComparer.Equals(xs.AsSpan(j, xs.Length - j), ys.AsSpan(j, ys.Length - j)).IsTrue();

                    if (ys.Length != 0)
                    {
                        ys[ys.Length - 1] = 255;
                        ByteArrayComparer.Equals(xs.AsSpan(j, xs.Length - j), ys.AsSpan(j, ys.Length - j)).IsFalse();
                    }
                }
            }
        }
Exemplo n.º 31
0
        public void TestByteArrayComparer()
        {
            string[]          ss    = new string[] { "", "asd", "ass", "qwer", "qwe" };
            StringComparer    sComp = StringComparer.InvariantCulture;
            ByteArrayComparer bComp = new ByteArrayComparer();

            for (int i = 0; i < ss.Length; i++)
            {
                for (int j = 0; j < ss.Length; j++)
                {
                    string sa = ss[i];
                    string sb = ss[j];
                    byte[] ba = Encoding.ASCII.GetBytes(sa);
                    byte[] bb = Encoding.ASCII.GetBytes(sb);
                    Assert.AreEqual(
                        sComp.Compare(sa, sb),
                        bComp.Compare(ba, bb));
                }
            }
        }
 public void SetUp()
 {
     _comparer = new ByteArrayComparer();
 }