forked from canonical/snapd
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcmp.go
103 lines (90 loc) · 2.39 KB
/
cmp.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
// -*- Mode: Go; indent-tabs-mode: t -*-
/*
* Copyright (C) 2014-2015 Canonical Ltd
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 3 as
* published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*/
package osutil
import (
"bytes"
"io"
"os"
)
const defaultChunkSize = 16 * 1024
func filesAreEqualChunked(a, b string, chunkSize int) bool {
fa, err := os.Open(a)
if err != nil {
return false
}
defer fa.Close()
fb, err := os.Open(b)
if err != nil {
return false
}
defer fb.Close()
fia, err := fa.Stat()
if err != nil {
return false
}
fib, err := fb.Stat()
if err != nil {
return false
}
if fia.Size() != fib.Size() {
return false
}
return streamsEqualChunked(fa, fb, chunkSize)
}
// FilesAreEqual compares the two files' contents and returns whether
// they are the same.
func FilesAreEqual(a, b string) bool {
return filesAreEqualChunked(a, b, 0)
}
func streamsEqualChunked(a, b io.Reader, chunkSize int) bool {
if a == b {
return true
}
if chunkSize <= 0 {
chunkSize = defaultChunkSize
}
bufa := make([]byte, chunkSize)
bufb := make([]byte, chunkSize)
for {
ra, erra := io.ReadAtLeast(a, bufa, chunkSize)
rb, errb := io.ReadAtLeast(b, bufb, chunkSize)
if erra == io.EOF && errb == io.EOF {
return true
}
if erra != nil || errb != nil {
// if both files finished in the middle of a
// ReadAtLeast, (returning io.ErrUnexpectedEOF), then we
// still need to check what was read to know whether
// they're equal. Otherwise, we know they're not equal
// (because we count any read error as a being non-equal
// also).
tailMightBeEqual := erra == io.ErrUnexpectedEOF && errb == io.ErrUnexpectedEOF
if !tailMightBeEqual {
return false
}
}
if !bytes.Equal(bufa[:ra], bufb[:rb]) {
return false
}
}
}
// StreamsEqual compares two streams and returns true if both
// have the same content.
func StreamsEqual(a, b io.Reader) bool {
return streamsEqualChunked(a, b, 0)
}