Debian Codegraph @

plumbing/format/idxfile/idxfile.go

raw
1 package idxfile
2
3 import (
4 "bytes"
5 "fmt"
6 "io"
7 "sort"
8 "sync"
9
10 encbin "encoding/binary"
11
12 "github.com/go-git/go-git/v5/plumbing"
13 "github.com/go-git/go-git/v5/plumbing/hash"
14 )
15
16 const (
17 // VersionSupported is the only idx version supported.
18 VersionSupported = 2
19
20 noMapping = -1
21 )
22
23 var (
24 idxHeader = []byte{255, 't', 'O', 'c'}
25 )
26
27 // Index represents an index of a packfile.
28 type Index interface {
29 // Contains checks whether the given hash is in the index.
30 Contains(h plumbing.Hash) (bool, error)
31 // FindOffset finds the offset in the packfile for the object with
32 // the given hash.
33 FindOffset(h plumbing.Hash) (int64, error)
34 // FindCRC32 finds the CRC32 of the object with the given hash.
35 FindCRC32(h plumbing.Hash) (uint32, error)
36 // FindHash finds the hash for the object with the given offset.
37 FindHash(o int64) (plumbing.Hash, error)
38 // Count returns the number of entries in the index.
39 Count() (int64, error)
40 // Entries returns an iterator to retrieve all index entries.
41 Entries() (EntryIter, error)
42 // EntriesByOffset returns an iterator to retrieve all index entries ordered
43 // by offset.
44 EntriesByOffset() (EntryIter, error)
45 }
46
47 // MemoryIndex is the in memory representation of an idx file.
48 type MemoryIndex struct {
49 Version uint32
50 Fanout [256]uint32
51 // FanoutMapping maps the position in the fanout table to the position
52 // in the Names, Offset32 and CRC32 slices. This improves the memory
53 // usage by not needing an array with unnecessary empty slots.
54 FanoutMapping [256]int
55 Names [][]byte
56 Offset32 [][]byte
57 CRC32 [][]byte
58 Offset64 []byte
59 PackfileChecksum [hash.Size]byte
60 IdxChecksum [hash.Size]byte
61
62 offsetHash map[int64]plumbing.Hash
63 offsetBuildOnce sync.Once
64 mu sync.RWMutex
65 }
66
67 var _ Index = (*MemoryIndex)(nil)
68
69 // NewMemoryIndex returns an instance of a new MemoryIndex.
70 func NewMemoryIndex() *MemoryIndex {
71 return &MemoryIndex{}
72 }
73
74 func (idx *MemoryIndex) findHashIndex(h plumbing.Hash) (int, bool) {
75 k := idx.FanoutMapping[h[0]]
76 if k == noMapping {
77 return 0, false
78 }
79
80 if len(idx.Names) <= k {
81 return 0, false
82 }
83
84 data := idx.Names[k]
85 high := uint64(len(idx.Offset32[k])) >> 2
86 if high == 0 {
87 return 0, false
88 }
89
90 low := uint64(0)
91 for {
92 mid := (low + high) >> 1
93 offset := mid * objectIDLength
94
95 cmp := bytes.Compare(h[:], data[offset:offset+objectIDLength])
96 if cmp < 0 {
97 high = mid
98 } else if cmp == 0 {
99 return int(mid), true
100 } else {
101 low = mid + 1
102 }
103
104 if low >= high {
105 break
106 }
107 }
108
109 return 0, false
110 }
111
112 // Contains implements the Index interface.
113 func (idx *MemoryIndex) Contains(h plumbing.Hash) (bool, error) {
114 _, ok := idx.findHashIndex(h)
115 return ok, nil
116 }
117
118 // FindOffset implements the Index interface.
119 func (idx *MemoryIndex) FindOffset(h plumbing.Hash) (int64, error) {
120 if len(idx.FanoutMapping) <= int(h[0]) {
121 return 0, plumbing.ErrObjectNotFound
122 }
123
124 k := idx.FanoutMapping[h[0]]
125 i, ok := idx.findHashIndex(h)
126 if !ok {
127 return 0, plumbing.ErrObjectNotFound
128 }
129
130 offset, err := idx.getOffset(k, i)
131 if err != nil {
132 return 0, err
133 }
134
135 // Save the offset for reverse lookup
136 idx.mu.Lock()
137 if idx.offsetHash == nil {
138 idx.offsetHash = make(map[int64]plumbing.Hash)
139 }
140 idx.offsetHash[int64(offset)] = h
141 idx.mu.Unlock()
142
143 return int64(offset), nil
144 }
145
146 const isO64Mask = uint64(1) << 31
147
148 func (idx *MemoryIndex) getOffset(firstLevel, secondLevel int) (uint64, error) {
149 offset := secondLevel << 2
150 ofs := encbin.BigEndian.Uint32(idx.Offset32[firstLevel][offset : offset+4])
151
152 if (uint64(ofs) & isO64Mask) != 0 {
153 offset := 8 * (uint64(ofs) & ^isO64Mask)
154 if l := uint64(len(idx.Offset64)); l < 8 || offset > l-8 {
155 return 0, fmt.Errorf("%w: offset64 index out of range", ErrMalformedIdxFile)
156 }
157 return encbin.BigEndian.Uint64(idx.Offset64[offset : offset+8]), nil
158 }
159
160 return uint64(ofs), nil
161 }
162
163 // FindCRC32 implements the Index interface.
164 func (idx *MemoryIndex) FindCRC32(h plumbing.Hash) (uint32, error) {
165 k := idx.FanoutMapping[h[0]]
166 i, ok := idx.findHashIndex(h)
167 if !ok {
168 return 0, plumbing.ErrObjectNotFound
169 }
170
171 return idx.getCRC32(k, i), nil
172 }
173
174 func (idx *MemoryIndex) getCRC32(firstLevel, secondLevel int) uint32 {
175 offset := secondLevel << 2
176 return encbin.BigEndian.Uint32(idx.CRC32[firstLevel][offset : offset+4])
177 }
178
179 // FindHash implements the Index interface.
180 func (idx *MemoryIndex) FindHash(o int64) (plumbing.Hash, error) {
181 var hash plumbing.Hash
182 var ok bool
183
184 var genErr error
185 idx.offsetBuildOnce.Do(func() {
186 genErr = idx.genOffsetHash()
187 })
188 if genErr != nil {
189 return plumbing.ZeroHash, genErr
190 }
191
192 idx.mu.RLock()
193 hash, ok = idx.offsetHash[o]
194 idx.mu.RUnlock()
195
196 if !ok {
197 return plumbing.ZeroHash, plumbing.ErrObjectNotFound
198 }
199
200 return hash, nil
201 }
202
203 // genOffsetHash generates the offset/hash mapping for reverse search.
204 func (idx *MemoryIndex) genOffsetHash() error {
205 count, err := idx.Count()
206 if err != nil {
207 return err
208 }
209
210 offsetHash := make(map[int64]plumbing.Hash, count)
211
212 var hash plumbing.Hash
213 i := uint32(0)
214 for firstLevel, fanoutValue := range idx.Fanout {
215 mappedFirstLevel := idx.FanoutMapping[firstLevel]
216 for secondLevel := uint32(0); i < fanoutValue; i++ {
217 copy(hash[:], idx.Names[mappedFirstLevel][secondLevel*objectIDLength:])
218 off, err := idx.getOffset(mappedFirstLevel, int(secondLevel))
219 if err != nil {
220 return err
221 }
222 offsetHash[int64(off)] = hash
223 secondLevel++
224 }
225 }
226
227 idx.mu.Lock()
228 idx.offsetHash = offsetHash
229 idx.mu.Unlock()
230
231 return nil
232 }
233
234 // Count implements the Index interface.
235 func (idx *MemoryIndex) Count() (int64, error) {
236 return int64(idx.Fanout[fanout-1]), nil
237 }
238
239 // Entries implements the Index interface.
240 func (idx *MemoryIndex) Entries() (EntryIter, error) {
241 return &idxfileEntryIter{idx, 0, 0, 0}, nil
242 }
243
244 // EntriesByOffset implements the Index interface.
245 func (idx *MemoryIndex) EntriesByOffset() (EntryIter, error) {
246 count, err := idx.Count()
247 if err != nil {
248 return nil, err
249 }
250
251 iter := &idxfileEntryOffsetIter{
252 entries: make(entriesByOffset, count),
253 }
254
255 entries, err := idx.Entries()
256 if err != nil {
257 return nil, err
258 }
259
260 for pos := 0; int64(pos) < count; pos++ {
261 entry, err := entries.Next()
262 if err != nil {
263 return nil, err
264 }
265
266 iter.entries[pos] = entry
267 }
268
269 sort.Sort(iter.entries)
270
271 return iter, nil
272 }
273
274 // EntryIter is an iterator that will return the entries in a packfile index.
275 type EntryIter interface {
276 // Next returns the next entry in the packfile index.
277 Next() (*Entry, error)
278 // Close closes the iterator.
279 Close() error
280 }
281
282 type idxfileEntryIter struct {
283 idx *MemoryIndex
284 total int
285 firstLevel, secondLevel int
286 }
287
288 func (i *idxfileEntryIter) Next() (*Entry, error) {
289 for {
290 if i.firstLevel >= fanout {
291 return nil, io.EOF
292 }
293
294 if i.total >= int(i.idx.Fanout[i.firstLevel]) {
295 i.firstLevel++
296 i.secondLevel = 0
297 continue
298 }
299
300 mappedFirstLevel := i.idx.FanoutMapping[i.firstLevel]
301 entry := new(Entry)
302 copy(entry.Hash[:], i.idx.Names[mappedFirstLevel][i.secondLevel*objectIDLength:])
303 var err error
304 entry.Offset, err = i.idx.getOffset(mappedFirstLevel, i.secondLevel)
305 if err != nil {
306 return nil, err
307 }
308 entry.CRC32 = i.idx.getCRC32(mappedFirstLevel, i.secondLevel)
309
310 i.secondLevel++
311 i.total++
312
313 return entry, nil
314 }
315 }
316
317 func (i *idxfileEntryIter) Close() error {
318 i.firstLevel = fanout
319 return nil
320 }
321
322 // Entry is the in memory representation of an object entry in the idx file.
323 type Entry struct {
324 Hash plumbing.Hash
325 CRC32 uint32
326 Offset uint64
327 }
328
329 type idxfileEntryOffsetIter struct {
330 entries entriesByOffset
331 pos int
332 }
333
334 func (i *idxfileEntryOffsetIter) Next() (*Entry, error) {
335 if i.pos >= len(i.entries) {
336 return nil, io.EOF
337 }
338
339 entry := i.entries[i.pos]
340 i.pos++
341
342 return entry, nil
343 }
344
345 func (i *idxfileEntryOffsetIter) Close() error {
346 i.pos = len(i.entries) + 1
347 return nil
348 }
349
350 type entriesByOffset []*Entry
351
352 func (o entriesByOffset) Len() int {
353 return len(o)
354 }
355
356 func (o entriesByOffset) Less(i int, j int) bool {
357 return o[i].Offset < o[j].Offset
358 }
359
360 func (o entriesByOffset) Swap(i int, j int) {
361 o[i], o[j] = o[j], o[i]
362 }