Created
April 19, 2013 20:28
-
-
Save philiplaureano/5423009 to your computer and use it in GitHub Desktop.
This extension method is what allows Tao to find the first byte mismatch within two given streams, regardless of their size.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public static ShouldMatch(this stream : Stream, other : Stream) : void | |
{ | |
def hash = stream.GetHash(); | |
def otherHash = other.GetHash(); | |
mutable smallerStream = other; | |
when(other.Length > stream.Length) | |
{ | |
smallerStream = stream; | |
} | |
def getMismatchPosition(startPosition : int, windowSize : int, firstStream : Stream, | |
secondStream : Stream) : int | |
{ | |
_ = firstStream.Seek(startPosition, SeekOrigin.Begin); | |
_ = secondStream.Seek(startPosition, SeekOrigin.Begin); | |
def outputReader = BinaryReader(firstStream); | |
def inputReader = BinaryReader(secondStream); | |
def firstBytes = outputReader.ReadBytes(windowSize); | |
def secondBytes = inputReader.ReadBytes(windowSize); | |
mutable result = startPosition; | |
def newStartPosition = startPosition + windowSize; | |
if(firstBytes.GetHash() == secondBytes.GetHash()) | |
{ | |
result = getMismatchPosition(newStartPosition, windowSize, firstStream, secondStream); | |
} | |
else | |
{ | |
when(firstBytes.Length > 1) | |
{ | |
result = startPosition + getMismatchPosition(0, windowSize / 2, MemoryStream(firstBytes), MemoryStream(secondBytes)); | |
} | |
} | |
result; | |
} | |
when(hash != otherHash) | |
{ | |
def mismatchPosition : int = getMismatchPosition(0, smallerStream.Length :> int, stream, other); | |
_ = stream.Seek(mismatchPosition, SeekOrigin.Begin); | |
_ = other.Seek(mismatchPosition, SeekOrigin.Begin); | |
def expected = other.ReadByte(); | |
def actual = stream.ReadByte(); | |
NUnit.Framework.Assert.Fail("Streams don't match, starting at byte position {0}; Expected Value: {1}, Actual Value: {2}", mismatchPosition, expected, actual); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment