Debian Codegraph @

readseeker.go

raw
1 package desync
2
3 import (
4 "fmt"
5 "io"
6 "sort"
7 )
8
9 // TODO: Implement WriterTo interface
10 // default io.Copy implementation operates in 32k chunks; copying up to a full chunk at a time will improve perf
11
12 // IndexPos represents a position inside an index file, to permit a seeking reader
13 type IndexPos struct {
14 Store Store
15 Index Index
16 Length int64 // total length of file
17 pos int64 // Location within offset stream; must be 0 <= Pos <= Index.
18
19 curChunkID ChunkID // hash of current chunk
20 curChunk []byte // decompressed version of current chunk
21 curChunkIdx int // identity of current chunk
22 curChunkOffset int64 // offset within current chunk
23 nullChunk *NullChunk
24 }
25
26 // NewIndexReadSeeker initializes a ReadSeeker for indexes.
27 func NewIndexReadSeeker(i Index, s Store) *IndexPos {
28 ip := &IndexPos{
29 Store: s,
30 Index: i,
31 Length: i.Length(),
32 nullChunk: NewNullChunk(i.Index.ChunkSizeMax),
33 }
34 // An index of a zero-length file has no chunks
35 if len(i.Chunks) > 0 {
36 ip.curChunkID = i.Chunks[0].ID
37 }
38 return ip
39 }
40
41 /* findOffset - Actually update our IndexPos for a new Index
42 *
43 * - Seek forward within existing chunk if appropriate
44 * - Bisect the Chunks array to find the correct chunk
45 * - Decompress if id does not match curChunk
46 * - Update chunkIdx and chunkOffset
47 */
48 func (ip *IndexPos) findOffset(newPos int64) (int64, error) {
49 var newChunkIdx int
50 var newChunkOffset int64
51 var delta int64
52 var err error
53
54 // Degenerate case: Seeking to existing position
55 delta = newPos - ip.pos
56 if delta == 0 {
57 return ip.pos, nil
58 }
59
60 // Degenerate case: An empty index has no chunk to look up. Just track
61 // the position, Read() returns EOF for anything at or past the end.
62 if len(ip.Index.Chunks) == 0 {
63 ip.pos = newPos
64 return ip.pos, nil
65 }
66
67 // Degenerate case: Seeking within current chunk
68 if (delta+ip.curChunkOffset) >= 0 &&
69 (delta+ip.curChunkOffset) < int64(ip.Index.Chunks[ip.curChunkIdx].Size) {
70 ip.pos += delta
71 ip.curChunkOffset += delta
72 return ip.pos, nil
73 }
74
75 // General case: Bisect
76 chunks := ip.Index.Chunks
77 newChunkIdx = sort.Search(len(chunks), func(i int) bool { return newPos < int64(chunks[i].Start+chunks[i].Size) })
78 if newChunkIdx >= len(chunks) { // function was not true for any chunk -- meaning we're running off the end
79 newChunkIdx = len(chunks) - 1
80 }
81 newChunk := ip.Index.Chunks[newChunkIdx]
82 newChunkOffset = newPos - int64(newChunk.Start)
83
84 if newPos < int64(newChunk.Start) {
85 return ip.pos, fmt.Errorf("seek found chunk beginning at position %v, desired position is %v", newChunk.Start, newPos)
86 }
87 if newPos > int64(newChunk.Start+newChunk.Size) {
88 return ip.pos, fmt.Errorf("seek found chunk ending at position %v, desired position is %v", newChunk.Start+newChunk.Size, newPos)
89 }
90
91 // Only invalidate cache if new chunk is different from old one (avoid re-decompressing all-0 regions)
92 if newChunk.ID != ip.curChunkID {
93 ip.curChunk = nil // next read attempt will call loadChunk()
94 }
95 // BELOW HERE, WE HAVE UPDATED THE DATA AND MUST NOT ERROR
96 ip.curChunkIdx = newChunkIdx
97 ip.curChunkID = newChunk.ID
98 ip.curChunkOffset = newChunkOffset
99 ip.pos = newPos
100 return newPos, err
101 }
102
103 func (ip *IndexPos) loadChunk() error {
104 // See if we can simply read a blank slice from memory if the null chunk
105 // is being loaded
106 if ip.curChunkID == ip.nullChunk.ID {
107 ip.curChunk = ip.nullChunk.Data
108 } else {
109 chunk, err := ip.Store.GetChunk(ip.curChunkID)
110 if err != nil {
111 return err
112 }
113 b, err := chunk.Data()
114 if err != nil {
115 return err
116 }
117 ip.curChunk = b
118 }
119 // The read path assumes len(curChunk) matches the size the index declares
120 // for this chunk. A mismatch means a corrupt or malicious index; without
121 // this check Read() can slice curChunk out of bounds (panic) or spin in a
122 // zero-progress loop. AssembleFile performs the same check.
123 if uint64(len(ip.curChunk)) != ip.Index.Chunks[ip.curChunkIdx].Size {
124 ip.curChunk = nil
125 return fmt.Errorf("unexpected size for chunk %s", ip.curChunkID)
126 }
127 return nil
128 }
129
130 // Seek implements the io.Seeker interface. Sets the offset for the next Read operation.
131 func (ip *IndexPos) Seek(offset int64, whence int) (int64, error) {
132 var newPos int64
133 var err error
134 switch whence {
135 case io.SeekStart:
136 newPos = offset
137 case io.SeekCurrent:
138 newPos = ip.pos + offset
139 case io.SeekEnd:
140 newPos = ip.Length + offset
141 default:
142 return ip.pos, fmt.Errorf("invalid whence")
143 }
144 if newPos < 0 {
145 return ip.pos, fmt.Errorf("unable to seek before start of file")
146 }
147 newOffset, err := ip.findOffset(newPos)
148 if err == nil && newPos > ip.Length {
149 err = io.EOF
150 }
151 return newOffset, err
152 }
153
154 func (ip *IndexPos) Read(p []byte) (n int, err error) {
155 var totalCopiedBytes int
156 remainingBytes := p[:]
157 if ip.pos >= ip.Length { // if initially called when already at or past the end, return EOF
158 return 0, io.EOF
159 }
160 for len(remainingBytes) > 0 {
161 if len(ip.curChunk) == 0 {
162 err = ip.loadChunk()
163 if err != nil {
164 break
165 }
166 }
167 chunkRemainingBytes := ip.curChunk[ip.curChunkOffset:len(ip.curChunk)]
168 if len(chunkRemainingBytes) == 0 && ip.curChunkIdx == (len(ip.Index.Chunks)-1) {
169 break // if running into the end after successful read, return a short read
170 }
171 copiedBytes := copy(remainingBytes, chunkRemainingBytes)
172 remainingBytes = remainingBytes[copiedBytes:]
173 totalCopiedBytes += copiedBytes
174 _, err = ip.Seek(int64(copiedBytes), io.SeekCurrent)
175 if err != nil {
176 break
177 }
178 }
179 return totalCopiedBytes, err
180 }