From 0c05215b9466ae0218a53d25dca6fdd3c169db12 Mon Sep 17 00:00:00 2001 From: "Valeriano A.R" Date: Mon, 21 Aug 2023 03:20:24 +0200 Subject: [PATCH] Add ByteArraySearcher to CsvLib. --- CsvLib.Tests/ByteArraySearcherTests.cs | 66 ++++++++++++++++++++++++++ CsvLib/ByteArraySearcher.cs | 41 ++++++++++++++++ 2 files changed, 107 insertions(+) create mode 100644 CsvLib.Tests/ByteArraySearcherTests.cs create mode 100644 CsvLib/ByteArraySearcher.cs diff --git a/CsvLib.Tests/ByteArraySearcherTests.cs b/CsvLib.Tests/ByteArraySearcherTests.cs new file mode 100644 index 0000000..b7c5c5d --- /dev/null +++ b/CsvLib.Tests/ByteArraySearcherTests.cs @@ -0,0 +1,66 @@ +using CsvLib; + +namespace CvsLib; + +public class ByteArraySearcherTests +{ + [Fact] + public void Contains__EmptyNeedle_ReturnsTrue() + { + byte[] haystack = { 1, 2, 3, 4, 5 }; + byte[] needle = Array.Empty(); + ByteArraySearcher searcher = new(needle); + + bool result = searcher.Contains(haystack); + + Assert.True(result); + } + + [Fact] + public void Contains__NeedleAtBeginning_ReturnsTrue() + { + byte[] haystack = { 1, 2, 3, 4, 5 }; + byte[] needle = { 1, 2, 3 }; + ByteArraySearcher searcher = new(needle); + + bool result = searcher.Contains(haystack); + + Assert.True(result); + } + + [Fact] + public void Contains__NeedleInMiddle_ReturnsTrue() + { + byte[] haystack = { 1, 2, 3, 4, 5 }; + byte[] needle = { 3, 4 }; + ByteArraySearcher searcher = new(needle); + + bool result = searcher.Contains(haystack); + + Assert.True(result); + } + + [Fact] + public void Contains__NeedleAtEnd_ReturnsTrue() + { + byte[] haystack = { 1, 2, 3, 4, 5 }; + byte[] needle = { 4, 5 }; + ByteArraySearcher searcher = new(needle); + + bool result = searcher.Contains(haystack); + + Assert.True(result); + } + + [Fact] + public void Contains__NeedleNotPresent_ReturnsFalse() + { + byte[] haystack = { 1, 2, 3, 4, 5 }; + byte[] needle = { 5, 6, 7 }; + ByteArraySearcher searcher = new(needle); + + bool result = searcher.Contains(haystack); + + Assert.False(result); + } +} diff --git a/CsvLib/ByteArraySearcher.cs b/CsvLib/ByteArraySearcher.cs new file mode 100644 index 0000000..f6ac65c --- /dev/null +++ b/CsvLib/ByteArraySearcher.cs @@ -0,0 +1,41 @@ +#nullable enable + +namespace CsvLib; + +public class ByteArraySearcher +{ + private readonly byte[] _needle; + + public ByteArraySearcher(byte[] needle) + { + _needle = needle; + } + + public bool Contains(byte[] haystack) + { + return Contains(haystack, haystack.Length); + } + + public bool Contains(byte[] haystack, int length) + { + // TODO: Implement the Boyer-Moore algorithm + for (int i = 0; i <= length - _needle.Length; i++) + { + bool found = true; + + for (int j = 0; j < _needle.Length; j++) + { + if (haystack[i + j] != _needle[j]) + { + found = false; + break; + } + } + + if (found) + return true; + } + + return false; + } +}