Last active
November 18, 2016 17:50
-
-
Save sparksp/a58367409b8f0f8b8b13fe7b3543cad4 to your computer and use it in GitHub Desktop.
Compare two io.Readers
This file contains 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
package io | |
// Copyright (c) 2016 Phill Sparks | |
// License MIT | |
import ( | |
"bytes" | |
"fmt" | |
"io" | |
) | |
const chunkSize = 1024 | |
// CompareReaders takes two io.Reader and compares them, byte for byte, | |
// returning true if they're identical. | |
func CompareReaders(a, b io.Reader) bool { | |
chunkA := make([]byte, chunkSize) | |
chunkB := make([]byte, chunkSize) | |
for { | |
readA, errA := a.Read(chunkA) | |
readB, errB := b.Read(chunkB) | |
if readA != readB { | |
return false | |
} | |
if bytes.Compare(chunkA[:readA], chunkB[:readB]) != 0 { | |
return false | |
} | |
if errA != errB { | |
return false | |
} | |
if errA == io.EOF || errB == io.EOF { | |
break | |
} | |
} | |
return true | |
} |
This file contains 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
package io | |
// Copyright (c) 2016 Phill Sparks | |
// License MIT | |
import ( | |
"bytes" | |
"io" | |
"testing" | |
) | |
func TestCompareReaders(t *testing.T) { | |
a := bytes.NewReader([]byte{'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k'}) | |
b := bytes.NewReader([]byte{'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k'}) | |
if !CompareReaders(a, b) { | |
t.Error("Identical readers not matching") | |
} | |
a.Seek(0, io.SeekStart) | |
c := bytes.NewReader([]byte{'a', 'b', 'c'}) | |
if CompareReaders(a, c) { | |
t.Error("First reader is longer than second, should not match") | |
} | |
a.Seek(0, io.SeekStart) | |
c.Seek(0, io.SeekStart) | |
if CompareReaders(c, a) { | |
t.Error("First reader is shorter than second, should not match") | |
} | |
a.Seek(0, io.SeekStart) | |
d := bytes.NewReader([]byte{'z', 'y', 'x', 'w', 'v', 'u', 't', 's', 'r', 'q', 'p'}) | |
if CompareReaders(a, d) { | |
t.Error("Readers with different content should not match") | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment