Beispiel #1
0
 public bool IsRegionOverlap(RegionInfo other)
 {
     return(BinaryComparer.Equals(Namespace, other.Namespace) &&
            BinaryComparer.Equals(Table, other.Table) &&
            (other.StopKey?.Any() != true || BinaryComparer.Compare(StartKey, other.StopKey) < 0) &&
            (StopKey?.Any() != true || BinaryComparer.Compare(StopKey, other.StartKey) > 0));
 }
Beispiel #2
0
        private static async Task <IEnumerable <UmdDiscSector> > InternalMergePass(IEnumerable <UmdDiscSector> sectors)
        {
            UmdDiscSector?baseSector = null;
            var           result     = new List <UmdDiscSector>();

            foreach (var sector in sectors.OrderBy(s => s.Crc32))
            {
                //System.Console.WriteLine(sector.Crc32);
                if ((baseSector == null) || (baseSector.Crc32 != sector.Crc32))
                {
                    baseSector = sector;
                    continue;
                }

                if ((baseSector.Crc32 == sector.Crc32) && (baseSector.Data != null) && (sector.Data != null))
                {
                    if (await BinaryComparer.Compare(baseSector.Data, 0, sector.Data, 0, UmdDisc.SectorSize))
                    {
                        sector.Encoding = UmdEncoding.InternalLink;
                        sector.Data     = GetLinkData(baseSector.Id);
                        sector.Length   = (ushort)sector.Data.Length;
                    }
                    else
                    {
                        result.Add(sector);
                    }
                }
            }

            return(result);
        }
        public void TestSortable()
        {
            List <byte[]> all = new List <byte[]>();

            all.Add(null);
            all.Add(Guid.Empty.ToByteArray());
            for (int i = 0; i < 1000; i++)
            {
                all.Add(Guid.NewGuid().ToByteArray());
            }

            all.Sort(new BinaryComparer());

            byte[] last = null;
            Assert.IsNull(all[0]);
            all.RemoveAt(0);

            foreach (byte[] entry in all)
            {
                if (last != null)
                {
                    Assert.IsTrue(StringComparer.Ordinal.Compare(Convert.ToBase64String(last), Convert.ToBase64String(entry)) < 0);
                }
                Assert.IsTrue(BinaryComparer.Compare(last, entry) < 0);
            }
        }
        /// <summary>
        /// Compares two binaries given an operation <paramref name="id"/>
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public DiffResult CompareBinaries(int id)
        {
            var comparisonModel  = repository.Get(x => x.Id == id).Single();
            var comparisonResult = binaryComparer.Compare(comparisonModel.LeftMember, comparisonModel.RightMember);
            var result           = new DiffResult()
            {
                DiffOffsets = comparisonResult.Item2
            };

            switch (comparisonResult.Item1)
            {
            case BinaryComparerEnum.DifferentSize:
                result.ComparisonResult = "The binaries have different sizes";
                break;

            case BinaryComparerEnum.EqualSize:
                result.ComparisonResult = "The binaries are of equal size";
                break;

            case BinaryComparerEnum.IdenticalBinary:
                result.ComparisonResult = "The binaries are identical";
                break;

            default:
                break;
            }

            return(result);
        }
        public void Compare_DifferentArraysOfSameLength_DifferencesAreReportedCorrectly
            (byte[] binary1, byte[] binary2, Difference[] differences)
        {
            var result = BinaryComparer.Compare(binary1, binary2);

            result.Should().BeOfType <BinariesHaveDifferences>()
            .Which.Differences.ShouldBeEquivalentTo(differences);
        }
        public void Compare_ArrayAndItsCopy_AreSame()
        {
            var binary1 = new byte[] { 1, 5, 9, 0 };
            var binary2 = binary1.ToArray();
            var result  = BinaryComparer.Compare(binary1, binary2);

            result.Should().BeOfType <BinariesAreEqual>();
        }
        public void Compare_TwoEmptyArrays_AreSame()
        {
            var binary1 = new byte[0];
            var binary2 = new byte[0];
            var result  = BinaryComparer.Compare(binary1, binary2);

            result.Should().BeOfType <BinariesAreEqual>();
        }
        public void TestFromHexWithSpace()
        {
            const string hex = "01-0203-0405\t0607\r\n0809\r0a0b0c\n0d0e0f10 ";

            byte[] bin = new byte[] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16 };

            Assert.AreEqual(0, BinaryComparer.Compare(bin, HexEncoding.DecodeBytes(hex)));
            Assert.AreEqual(0, BinaryComparer.Compare(bin, HexEncoding.DecodeBytes(Encoding.ASCII.GetBytes(hex))));
        }
        public void TestToFromHexPartial()
        {
            const string hex = "0102030405060708090a0b0c0d0e0f10";

            byte[] bin = new byte[] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16 };

            Assert.AreEqual(hex.Substring(4, 10), HexEncoding.EncodeBytes(bin, 2, 5));
            Assert.AreEqual(0, BinaryComparer.Compare(new byte[] { 3, 4, 5, 6 }, HexEncoding.DecodeBytes(hex, 4, 8)));
        }
        static void ExersizeFile(ManualResetEvent stop, TransactedCompoundFile file)
        {
            const int LIMIT = 512 * 512 / 4 - 512 * 3;
            Random    r     = new Random();
            Dictionary <uint, byte[]> state = new Dictionary <uint, byte[]>();

            while (true)
            {
                while (state.Count < 1000)
                {
                    uint   h     = file.Create();
                    byte[] bytes = new byte[r.Next(5) == 0 ? r.Next(512) : r.Next(LIMIT)];
                    r.NextBytes(bytes);
                    file.Write(h, bytes, 0, bytes.Length);
                    state.Add(h, bytes);
                    if (stop.WaitOne(0, false))
                    {
                        return;
                    }
                }
                foreach (var kv in state)
                {
                    Assert.AreEqual(0, BinaryComparer.Compare(kv.Value, IOStream.ReadAllBytes(file.Read(kv.Key))));
                    if (stop.WaitOne(0, false))
                    {
                        return;
                    }
                }
                List <KeyValuePair <uint, byte[]> > capture = new List <KeyValuePair <uint, byte[]> >(state);
                for (int i = 0; i < capture.Count; i += r.Next(4))
                {
                    uint   h     = capture[i].Key;
                    byte[] bytes = new byte[r.Next(512)];
                    r.NextBytes(bytes);
                    file.Write(h, bytes, 0, bytes.Length);
                    state[h] = bytes;
                    Assert.AreEqual(0, BinaryComparer.Compare(bytes, IOStream.ReadAllBytes(file.Read(h))));
                    if (stop.WaitOne(0, false))
                    {
                        return;
                    }
                }
                for (int i = 0; i < capture.Count; i += 1 + r.Next(4))
                {
                    uint h = capture[i].Key;
                    file.Delete(h);
                    state.Remove(h);
                    if (stop.WaitOne(0, false))
                    {
                        return;
                    }
                }
            }
        }
        public void TestCompare()
        {
            Assert.AreEqual(0, BinaryComparer.Compare(null, null));
            Assert.AreEqual(0, BinaryComparer.Compare(new byte[] { }, new byte[] { }));
            Assert.AreEqual(0, BinaryComparer.Compare(new byte[] { 1, 2, 3 }, new byte[] { 1, 2, 3 }));

            Assert.AreEqual(-1, BinaryComparer.Compare(null, new byte[] { 1, 2, 3 }));
            Assert.AreEqual(1, BinaryComparer.Compare(new byte[] { 1, 2, 3 }, null));
            Assert.AreEqual(-1, BinaryComparer.Compare(new byte[] { 1, 2 }, new byte[] { 1, 2, 3 }));
            Assert.AreEqual(1, BinaryComparer.Compare(new byte[] { 1, 2, 3 }, new byte[] { 1, 2 }));
        }
Beispiel #12
0
        // TODO: expand comparer to use CompareFlags flags
        public async Task <List <CdromSectorComparisonResult> > Compare(CdromImage image1, CdromImage image2)
        {
            var result = new List <CdromSectorComparisonResult>();

            var sectorMax = Math.Max(image1.Sectors.Count, image2.Sectors.Count);

            for (var i = 0; i < sectorMax; i++)
            {
                if (i >= image1.Sectors.Count)
                {
                    result.Add(new CdromSectorComparisonResult
                    {
                        SectorPhysicalAddress = i,
                        Message = "Sectors is missing in first image",
                        Equal   = false
                    });

                    continue;
                }

                if (i >= image2.Sectors.Count)
                {
                    result.Add(new CdromSectorComparisonResult
                    {
                        SectorPhysicalAddress = i,
                        Message = "Sectors is missing in second image",
                        Equal   = false
                    });

                    continue;
                }

                if (await BinaryComparer.Compare(image1.Sectors[i].Data, 0, image2.Sectors[i].Data, 0, CdromConstants.SectorDataSize))
                {
                    result.Add(new CdromSectorComparisonResult
                    {
                        SectorPhysicalAddress = i,
                        Message = "Sectors are equal",
                        Equal   = true
                    });
                }
                else
                {
                    result.Add(new CdromSectorComparisonResult
                    {
                        SectorPhysicalAddress = i,
                        Message = "Sectors are not equal",
                        Equal   = false
                    });
                }
            }

            return(result);
        }
Beispiel #13
0
        // TODO: optimize this method
        public static async Task Merge(UmdDisc masterDisc, UmdDisc disc)
        {
            var masterSectors = masterDisc.Sectors.Where(s => s.Encoding == UmdEncoding.None).OrderBy(s => s.Crc32).ToList();
            var sectors       = disc.Sectors.Where(s => s.Encoding == UmdEncoding.None).OrderBy(s => s.Crc32).ToList();

            // if nothing to compare return
            if ((masterSectors == null) ||
                (sectors == null) ||
                (!masterSectors.Any()) ||
                (!sectors.Any()))
            {
                return;
            }

            int masterCursor = 0, cursor = 0;

            // sync cursors
            while ((masterCursor < masterSectors.Count) && (cursor < sectors.Count))
            {
                if (masterSectors[masterCursor].Crc32 == sectors[cursor].Crc32)
                {
                    int subCursor = 0;
                    while ((masterCursor + subCursor < masterSectors.Count) && (masterSectors[masterCursor].Crc32 == masterSectors[masterCursor + subCursor].Crc32))
                    {
                        if ((masterSectors[masterCursor + subCursor].Data != null) &&
                            (sectors[cursor].Data != null) &&
                            (await BinaryComparer.Compare(masterSectors[masterCursor + subCursor].Data, 0, sectors[cursor].Data, 0, UmdDisc.SectorSize)))
                        {
                            sectors[cursor].Encoding = UmdEncoding.ExternalLink;
                            sectors[cursor].Data     = GetLinkData(masterSectors[masterCursor + subCursor].Id);
                            sectors[cursor].Length   = 4;
                            sectors[cursor].Crc32    = Crc32Algorithm.Compute(sectors[cursor].Data, 0, 4);
                            break;
                        }
                        subCursor++;
                    }

                    cursor++;
                    continue;
                }

                if (masterSectors[masterCursor].Crc32 < sectors[cursor].Crc32)
                {
                    masterCursor++;
                    continue;
                }

                if (masterSectors[masterCursor].Crc32 > sectors[cursor].Crc32)
                {
                    cursor++;
                    continue;
                }
            }
        }
        public void TestToFromHex()
        {
            byte[] all = new byte[256];
            for (int i = 0; i < all.Length; i++)
            {
                all[i] = (byte)i;
            }

            Assert.AreEqual(AllHex, HexEncoding.EncodeBytes(all));
            Assert.AreEqual(0, BinaryComparer.Compare(all, HexEncoding.DecodeBytes(AllHex)));
            Assert.AreEqual(0, BinaryComparer.Compare(all, HexEncoding.DecodeBytes(AllHex.ToUpper())));
        }
        public void TestSafe64EncodingLargeArray()
        {
            Random rand = new Random();

            byte[] data = new byte[0x400000];

            rand.NextBytes(data);
            string testAsc = Safe64Encoding.EncodeBytes(data);

            Assert.AreEqual(0, BinaryComparer.Compare(data, Safe64Encoding.DecodeBytes(testAsc)));
            testAsc = AsciiEncoder.EncodeBytes(data);
            Assert.AreEqual(0, BinaryComparer.Compare(data, AsciiEncoder.DecodeBytes(testAsc)));
        }
Beispiel #16
0
        void TestEncryptDecrypt(SymmetricAlgorithm ealg, SymmetricAlgorithm dalg)
        {
            System.Diagnostics.Trace.WriteLine(String.Format("b={0}, k={1}, r={2}", ealg.BlockSize, ealg.KeySize,
                                                             ealg is ModifiedRijndael ? ((ModifiedRijndael)ealg).Rounds : ((ModifiedRijndael)dalg).Rounds));
            byte[] test = Encoding.ASCII.GetBytes("Testing 123");

            byte[] copy;
            using (ICryptoTransform enc = ealg.CreateEncryptor())
                copy = enc.TransformFinalBlock(test, 0, test.Length);

            using (ICryptoTransform dec = dalg.CreateDecryptor())
                copy = dec.TransformFinalBlock(copy, 0, copy.Length);

            Assert.AreEqual(0, BinaryComparer.Compare(test, copy));
        }
Beispiel #17
0
        private void TestAes256CBC(bool enc, string key, string iv, string input, string expect)
        {
            ModifiedRijndael r = ModifiedRijndael.Create();

            r.Mode      = CipherMode.CBC;
            r.Padding   = PaddingMode.None;
            r.BlockSize = iv.Length / 2 * 8;
            r.IV        = HexEncoding.DecodeBytes(iv);
            r.KeySize   = key.Length / 2 * 8;
            r.Key       = HexEncoding.DecodeBytes(key);
            ICryptoTransform xf = enc ? r.CreateEncryptor() : r.CreateDecryptor();

            byte[] result = xf.TransformFinalBlock(HexEncoding.DecodeBytes(input), 0, input.Length / 2);
            byte[] test   = HexEncoding.DecodeBytes(expect);
            Assert.AreEqual(0, BinaryComparer.Compare(test, result));
        }
Beispiel #18
0
        public void BinaryComparer_ShouldReturn_SameSizesAndIdenticalBinaries()
        {
            var binaryComparer = new BinaryComparer();

            //var
            var leftBinary = new byte[15];

            new Random().NextBytes(leftBinary);
            var rightBinary = leftBinary;

            var actualResult   = binaryComparer.Compare(leftBinary, rightBinary);
            var expectedResult = new Tuple <BinaryComparerEnum, List <DiffOffset> >(BinaryComparerEnum.IdenticalBinary, new List <DiffOffset>());

            Assert.AreEqual(actualResult.Item1, expectedResult.Item1);
            CollectionAssert.AreEquivalent(expectedResult.Item2.ToSimpleList(), actualResult.Item2.ToSimpleList());
        }
        void TestEncoderAgainstBase64(int repeat, int size)
        {
            Random rand = new Random();

            byte[] data = new byte[size];

            while (repeat-- > 0)
            {
                rand.NextBytes(data);
                string testB64 = Convert.ToBase64String(data);
                string testAsc = Safe64Encoding.EncodeBytes(data);

                Assert.AreEqual(testB64.Replace('+', '-').Replace('/', '_').Replace("=", ""), testAsc);
                Assert.AreEqual(0, BinaryComparer.Compare(data, Safe64Encoding.DecodeBytes(testAsc)));
                Assert.AreEqual(0, BinaryComparer.Compare(data, AsciiEncoder.DecodeBytes(testAsc)));
            }
        }
Beispiel #20
0
        private RegionInfo GetInfoFromCache(byte[] table, byte[] key)
        {
            if (BinaryComparer.Compare(table, _metaTableName) == 0)
            {
                return(_metaRegionInfo);
            }
            var search = RegionInfo.CreateRegionSearchKey(table, key);
            var info   = _cache.GetInfo(search);

            if (info == null || false == BinaryComparer.Equals(table, info.Table))
            {
                return(null);
            }
            if (info.StopKey.Length > 0 && BinaryComparer.Compare(key, info.StopKey) >= 0)
            {
                return(null);
            }
            return(info);
        }
Beispiel #21
0
        public void BinaryComparer_ShouldReturn_SameSizesAndDifferentBinaries()
        {
            var binaryComparer = new BinaryComparer();

            var leftBinary = new byte[15] {
                1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0
            };
            var rightBinary = new byte[15] {
                0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1
            };

            var actualResult   = binaryComparer.Compare(leftBinary, rightBinary);
            var expectedResult = new Tuple <BinaryComparerEnum, List <DiffOffset> >(BinaryComparerEnum.EqualSize, new List <DiffOffset>()
            {
                new DiffOffset {
                    StartIndex = 0, Length = 15
                }
            }
                                                                                    );

            Assert.AreEqual(actualResult.Item1, expectedResult.Item1);
            CollectionAssert.AreEquivalent(expectedResult.Item2.ToSimpleList(), actualResult.Item2.ToSimpleList());
        }
 private void AssertCompare(BinaryComparer comparer, int expected, string v1, string v2)
 {
     Assert.Equal(expected, comparer.Compare(Encoding.UTF8.GetBytes(v1), Encoding.UTF8.GetBytes(v2)));
 }
 public void Compare_WithNullArgument_ThrowsArgumentNullException()
 {
     Assert.Throws <ArgumentNullException>(() => BinaryComparer.Compare(null, new byte[1]));
     Assert.Throws <ArgumentNullException>(() => BinaryComparer.Compare(new byte[2], null));
 }
 private void AssertCompare(BinaryComparer comparer, int expected, string v1, string v2)
 {
     Assert.AreEqual(expected, comparer.Compare(Encoding.UTF8.GetBytes(v1), Encoding.UTF8.GetBytes(v2)), string.Format("{0} -> {1}", v1, v2));
 }
        public void Compare_ArraysOfDifferentLength_ReportedAsOfDifferentSize(byte[] binary1, byte[] binary2)
        {
            var result = BinaryComparer.Compare(binary1, binary2);

            result.Should().BeOfType <BinariesOfDifferentSize>();
        }