I need to extract various fields in a byte buffer. I came up with this solution:
func (fs *FileSystem) readSB() {
// fs.f is a *os.File
buf := make([]byte, 1024)
fs.f.ReadAt(buf, 1024)
// Offset: type
var p *bytes.Buffer
// 0: uint32
p = bytes.NewBuffer(buf[0:])
binary.Read(p, binary.LittleEndian, &fs.sb.inodeCount)
// 4: uint32
p = bytes.NewBuffer(buf[4:])
binary.Read(p, binary.LittleEndian, &fs.sb.blockCount)
// 20: uint32
p = bytes.NewBuffer(buf[20:])
binary.Read(p, binary.LittleEndian, &fs.sb.firstDataBlock)
// 24: uint32
p = bytes.NewBuffer(buf[24:])
binary.Read(p, binary.LittleEndian, &fs.sb.blockSize)
fs.sb.blockSize = 1024 << fs.sb.blockSize
// 32: uint32
p = bytes.NewBuffer(buf[32:])
binary.Read(p, binary.LittleEndian, &fs.sb.blockPerGroup)
// 40: uint32
p = bytes.NewBuffer(buf[40:])
binary.Read(p, binary.LittleEndian, &fs.sb.inodePerBlock)
}
Is there a more better/idiomatic/straightforward way of doing this?
- I want to keep offsets explicit
- I want to read from the byte buffer, not seeking and reading from the file when possible.
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…