forked from perkeep/perkeep
-
Notifications
You must be signed in to change notification settings - Fork 0
/
blobref.go
253 lines (214 loc) · 5.71 KB
/
blobref.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
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
/*
Copyright 2011 Google Inc.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
// Package blobref provides the BlobRef type and associate types and parsers.
// A blobref is the immutable reference to an individual blob.
package blobref
import (
"crypto/sha1"
"fmt"
"hash"
"reflect"
"regexp"
)
// Pattern is the regular expression which matches a blobref.
// It does not contain ^ or $.
const Pattern = `\b([a-z][a-z0-9]*)-([a-f0-9]+)\b`
// whole blobref pattern
var kBlobRefPattern = regexp.MustCompile("^" + Pattern + "$")
var supportedDigests = map[string]func() hash.Hash{
"sha1": func() hash.Hash {
return sha1.New()
},
}
// BlobRef is an immutable reference to a blob.
type BlobRef struct {
hashName string
digest string
strValue string // "<hashname>-<digest>"
}
// AsUint64 returns the first 64-bits of the blobref as an integer.
func (br *BlobRef) AsUint64() uint64 {
var ret uint64
for i := 0; i < 16; i++ {
b := br.digest[i]
switch {
case b >= '0' && b <= '9':
b = b - '0'
default:
b = b - 'a' + 10
}
ret = ret<<4 | uint64(b)
}
return ret
}
func (br *BlobRef) GobEncode() ([]byte, error) {
return []byte(br.String()), nil
}
func (br *BlobRef) GobDecode(b []byte) error {
dec := Parse(string(b))
if dec == nil {
return fmt.Errorf("invalid blobref %q", string(b))
}
*br = *dec
return nil
}
// SizedBlobRef is like a BlobRef but includes because it includes a
// potentially mutable 'Size', this should be used as a stack value,
// not a *SizedBlobRef.
type SizedBlobRef struct {
*BlobRef
Size int64
}
func (sb *SizedBlobRef) Equal(o SizedBlobRef) bool {
return sb.Size == o.Size && sb.BlobRef.String() == o.BlobRef.String()
}
func (sb SizedBlobRef) String() string {
return fmt.Sprintf("[%s; %d bytes]", sb.BlobRef.String(), sb.Size)
}
func (br *BlobRef) HashName() string {
return br.hashName
}
func (br *BlobRef) Digest() string {
return br.digest
}
func (br *BlobRef) DigestPrefix(digits int) string {
if len(br.digest) < digits {
return br.digest
}
return br.digest[:digits]
}
func (br *BlobRef) String() string {
if br == nil {
return "<nil-BlobRef>"
}
return br.strValue
}
func (br *BlobRef) DomID() string {
if br == nil {
return ""
}
return "camli-" + br.String()
}
func (br *BlobRef) Equal(other *BlobRef) bool {
if (br == nil) != (other == nil) {
return false
}
if br == nil {
return true
}
return br.hashName == other.hashName && br.digest == other.digest
}
func (br *BlobRef) Hash() hash.Hash {
fn, ok := supportedDigests[br.hashName]
if !ok {
return nil // TODO: return an error here, not nil
}
return fn()
}
func (br *BlobRef) HashMatches(h hash.Hash) bool {
return fmt.Sprintf("%x", h.Sum(nil)) == br.digest
}
func (br *BlobRef) IsSupported() bool {
_, ok := supportedDigests[br.hashName]
return ok
}
func (br *BlobRef) Sum32() uint32 {
var h32 uint32
n, err := fmt.Sscanf(br.digest[len(br.digest)-8:], "%8x", &h32)
if err != nil {
panic(err)
}
if n != 1 {
panic("sum32")
}
return h32
}
var kExpectedDigestSize = map[string]int{
"md5": 32,
"sha1": 40,
}
func newBlob(hashName, digest string) *BlobRef {
strValue := fmt.Sprintf("%s-%s", hashName, digest)
return &BlobRef{
hashName: strValue[0:len(hashName)],
digest: strValue[len(hashName)+1:],
strValue: strValue,
}
}
func blobIfValid(hashname, digest string) *BlobRef {
expectedSize := kExpectedDigestSize[hashname]
if expectedSize != 0 && len(digest) != expectedSize {
return nil
}
return newBlob(hashname, digest)
}
// NewHash returns a new hash.Hash of the currently recommended hash type.
// Currently this is just SHA-1, but will likely change within the next
// year or so.
func NewHash() hash.Hash {
return sha1.New()
}
var sha1Type = reflect.TypeOf(sha1.New())
// FromHash returns a BlobRef representing the given hash.
func FromHash(h hash.Hash) *BlobRef {
if reflect.TypeOf(h) == sha1Type {
return newBlob("sha1", fmt.Sprintf("%x", h.Sum(nil)))
}
panic(fmt.Sprintf("Currently-unsupported hash type %T", h))
}
// SHA1FromString returns a SHA-1 blobref of the provided string.
func SHA1FromString(s string) *BlobRef {
s1 := sha1.New()
s1.Write([]byte(s))
return FromHash(s1)
}
// SHA1FromBytes returns a SHA-1 blobref of the provided bytes.
func SHA1FromBytes(b []byte) *BlobRef {
s1 := sha1.New()
s1.Write(b)
return FromHash(s1)
}
// FromPattern takes a pattern and if it matches 's' with two exactly two valid
// submatches, returns a BlobRef, else returns nil.
func FromPattern(r *regexp.Regexp, s string) *BlobRef {
matches := r.FindStringSubmatch(s)
if len(matches) != 3 {
return nil
}
return blobIfValid(matches[1], matches[2])
}
func Parse(ref string) *BlobRef {
return FromPattern(kBlobRefPattern, ref)
}
func (br *BlobRef) UnmarshalJSON(d []byte) error {
if len(d) < 2 || d[0] != '"' || d[len(d)-1] != '"' {
return fmt.Errorf("blobref: expecting a JSON string to unmarshal, got %q", d)
}
refStr := string(d[1 : len(d)-1])
p := Parse(refStr)
if p == nil {
return fmt.Errorf("blobref: invalid blobref %q (%d)", refStr, len(refStr))
}
*br = *p
return nil
}
func (br *BlobRef) MarshalJSON() ([]byte, error) {
return []byte(fmt.Sprintf("%q", br.String())), nil
}
func MustParse(ref string) *BlobRef {
br := Parse(ref)
if br == nil {
panic("Failed to parse blobref: " + ref)
}
return br
}