Skip to content

Commit

Permalink
fix: embedded datfile
Browse files Browse the repository at this point in the history
My understanding of compile-time evaluation was clearly flawed.
  • Loading branch information
mroach committed Aug 19, 2021
1 parent b0e05bb commit 7447dab
Show file tree
Hide file tree
Showing 2 changed files with 12 additions and 21 deletions.
2 changes: 1 addition & 1 deletion cmd/validate.go
Original file line number Diff line number Diff line change
Expand Up @@ -65,7 +65,7 @@ func init() {

func loadDatfile() (dat.DatFile, error) {
if datFilePath == "" {
return dat.IncludedDat, nil
return dat.ReadFromIncluded()
} else {
return dat.ReadFromFile(datFilePath)
}
Expand Down
31 changes: 11 additions & 20 deletions dat/dat.go
Original file line number Diff line number Diff line change
@@ -1,32 +1,15 @@
package dat

import (
_ "embed"
"encoding/xml"
"io"
"os"
"strings"
)

// Reading and parsing the file at build time reduces the binary size and eliminates
// duplicate parsing work at runtime if we were to embed the plain text file with go:embed
var IncludedDat = func() DatFile {
f, err := os.Open("dat/roms.dat.xml")
if err != nil {
panic(err)
}
defer f.Close()

bytes, err := io.ReadAll(f)
if err != nil {
panic(err)
}

df, err := Read(bytes)
if err != nil {
panic(err)
}
return df
}()
//go:embed roms.dat.xml
var embeddedDatFile []byte

type DatFile struct {
Name string `xml:"header>name"`
Expand All @@ -44,6 +27,14 @@ type Rom struct {
Status string `xml:"status"`
}

func ReadFromIncluded() (df DatFile, err error) {
df, err = Read(embeddedDatFile)
if err != nil {
return df, err
}
return df, nil
}

// Read a DatFile from an XML datfile on disk
func ReadFromFile(path string) (df DatFile, err error) {
f, err := os.Open(path)
Expand Down

0 comments on commit 7447dab

Please sign in to comment.