1
0
mirror of https://github.com/garraflavatra/go-fmp.git synced 2025-06-28 04:25:11 +00:00
Files
go-fmp/fmp/fmp.go

99 lines
1.9 KiB
Go
Raw Normal View History

2025-06-11 16:01:49 +02:00
package fmp
import (
"bytes"
2025-06-11 16:19:31 +02:00
"encoding/binary"
2025-06-11 16:01:49 +02:00
"io"
"os"
"time"
)
const (
magicSequence = "\x00\x01\x00\x00\x00\x02\x00\x01\x00\x05\x00\x02\x00\x02\xC0"
hbamSequence = "HBAM7"
magicSize = len(magicSequence)
hbamSize = len(hbamSequence)
sectorSize = 4096
)
type FmpFile struct {
2025-06-11 16:19:31 +02:00
Stream io.ReadSeeker
FileSize uint
NumSectors uint
2025-06-11 16:01:49 +02:00
VersionDate time.Time
ApplicationName string
}
2025-06-11 16:19:31 +02:00
type FmpSector struct {
Deleted bool
Level uint8
PrevSectorID uint32
NextSectorID uint32
Payload []byte
}
2025-06-11 16:01:49 +02:00
func OpenFile(path string) (*FmpFile, error) {
2025-06-11 16:19:31 +02:00
info, err := os.Stat(path)
if err != nil {
return nil, err
}
2025-06-11 16:01:49 +02:00
stream, err := os.Open(path)
if err != nil {
if stream != nil {
stream.Close()
}
return nil, err
}
ctx := &FmpFile{Stream: stream}
if err := ctx.readHeader(); err != nil {
stream.Close()
return nil, err
}
2025-06-11 16:19:31 +02:00
ctx.FileSize = uint(info.Size())
ctx.NumSectors = ctx.FileSize / sectorSize
2025-06-11 16:01:49 +02:00
return ctx, nil
}
func (ctx *FmpFile) readHeader() error {
buf := make([]byte, sectorSize)
_, err := ctx.Stream.Read(buf)
if err != nil {
return ErrRead
}
if !bytes.Equal(buf[:magicSize], []byte(magicSequence)) {
return ErrBadMagic
}
if !bytes.Equal(buf[magicSize:magicSize+hbamSize], []byte(hbamSequence)) {
return ErrBadMagic
}
ctx.VersionDate, err = time.Parse("06JAN02", string(buf[531:538]))
if err != nil {
return ErrBadHeader
}
appNameLength := int(buf[541])
ctx.ApplicationName = string(buf[542 : 542+appNameLength])
return nil
}
2025-06-11 16:19:31 +02:00
func (ctx *FmpFile) readSector() (*FmpSector, error) {
buf := make([]byte, sectorSize)
_, err := ctx.Stream.Read(buf)
if err != nil {
return nil, ErrRead
}
sector := &FmpSector{
Deleted: buf[0] != 0,
Level: uint8(buf[1]),
PrevSectorID: binary.BigEndian.Uint32(buf[2:6]),
NextSectorID: binary.BigEndian.Uint32(buf[6:10]),
Payload: buf[6:4076],
}
return sector, nil
}