Debian Codegraph @

fat/cluster_chain.go

raw symbols SCIP
1 package fat
2
3 import (
4 "io"
5 "math"
6
7 "github.com/mitchellh/go-fs"
8 )
9
10 type ClusterChain struct {
11 device fs.BlockDevice
12 fat *FAT
13 startCluster uint32
14 readOffset uint32
15 writeOffset uint32
16 }
17
18 func (c *ClusterChain) Read(p []byte) (n int, err error) {
19 bpc := c.fat.bs.BytesPerCluster()
20 chain := c.fat.Chain(c.startCluster)
21
22 dataOffset := uint32(0)
23 for dataOffset < uint32(len(p)) {
24 chainIdx := c.readOffset / bpc
25 if int(chainIdx) >= len(chain) {
26 err = io.EOF
27 return
28 }
29
30 clusterOffset := c.fat.bs.ClusterOffset(int(chain[chainIdx]))
31 clusterOffset += c.readOffset % bpc
32 dataOffsetEnd := dataOffset + bpc
33 dataOffsetEnd -= c.readOffset % bpc
34 dataOffsetEnd = uint32(math.Min(float64(dataOffsetEnd), float64(len(p))))
35
36 var nw int
37 nw, err = c.device.ReadAt(p[dataOffset:dataOffsetEnd], int64(clusterOffset))
38 if err != nil {
39 return
40 }
41
42 c.readOffset += uint32(nw)
43 dataOffset += uint32(nw)
44 n += nw
45 }
46
47 return
48 }
49
50 // Write will write to the cluster chain, expanding it if necessary.
51 func (c *ClusterChain) Write(p []byte) (n int, err error) {
52 bpc := c.fat.bs.BytesPerCluster()
53 chain := c.fat.Chain(c.startCluster)
54 chainLength := uint32(len(chain)) * bpc
55
56 if chainLength < c.writeOffset+uint32(len(p)) {
57 // We need to grow the chain
58 bytesNeeded := (c.writeOffset + uint32(len(p))) - chainLength
59 clustersNeeded := int(math.Ceil(float64(bytesNeeded) / float64(bpc)))
60 chain, err = c.fat.ResizeChain(c.startCluster, len(chain)+clustersNeeded)
61 if err != nil {
62 return
63 }
64
65 // Write the FAT out
66 if err = c.fat.WriteToDevice(c.device); err != nil {
67 return
68 }
69 }
70
71 dataOffset := uint32(0)
72 for dataOffset < uint32(len(p)) {
73 chainIdx := c.writeOffset / bpc
74 clusterOffset := c.fat.bs.ClusterOffset(int(chain[chainIdx]))
75 clusterOffset += c.writeOffset % bpc
76 dataOffsetEnd := dataOffset + bpc
77 dataOffsetEnd -= c.writeOffset % bpc
78 dataOffsetEnd = uint32(math.Min(float64(dataOffsetEnd), float64(len(p))))
79
80 var nw int
81 nw, err = c.device.WriteAt(p[dataOffset:dataOffsetEnd], int64(clusterOffset))
82 if err != nil {
83 return
84 }
85
86 c.writeOffset += uint32(nw)
87 dataOffset += uint32(nw)
88 n += nw
89 }
90
91 return
92 }