ichigo/engine/asset.go

52 lines
1 KiB
Go
Raw Normal View History

2021-07-30 17:26:23 +10:00
package engine
2021-07-31 16:38:54 +10:00
import (
2021-08-23 20:28:49 +10:00
"compress/gzip"
"encoding/gob"
2021-08-23 10:09:49 +10:00
"io/fs"
2021-08-25 15:04:38 +10:00
"os"
2021-08-26 11:38:55 +10:00
"path/filepath"
2021-07-31 16:38:54 +10:00
)
2021-07-30 17:26:23 +10:00
type assetKey struct {
assets fs.FS
path string
}
2021-08-26 11:38:55 +10:00
// LoadGobz gunzips and gob-decodes a component from a file from a FS.
2021-08-26 11:31:39 +10:00
func LoadGobz(dst interface{}, assets fs.FS, path string) error {
2021-08-23 20:28:49 +10:00
f, err := assets.Open(path)
if err != nil {
return err
2021-07-31 17:17:26 +10:00
}
2021-08-23 20:28:49 +10:00
defer f.Close()
gz, err := gzip.NewReader(f)
if err != nil {
return err
2021-07-31 19:49:24 +10:00
}
2021-08-23 20:28:49 +10:00
return gob.NewDecoder(gz).Decode(dst)
2021-07-31 17:17:26 +10:00
}
2021-08-26 11:31:39 +10:00
// SaveGobz takes an object, gob-encodes it, gzips it, and writes to disk.
2021-08-25 16:54:22 +10:00
// This requires running on something with a disk to write to (not JS)
2021-08-26 11:31:39 +10:00
func SaveGobz(src interface{}, name string) error {
2021-08-26 11:38:55 +10:00
f, err := os.CreateTemp(".", filepath.Base(name))
2021-08-25 15:04:38 +10:00
if err != nil {
return err
}
defer os.Remove(f.Name())
defer f.Close()
gz := gzip.NewWriter(f)
if err := gob.NewEncoder(gz).Encode(src); err != nil {
return err
}
if err := gz.Close(); err != nil {
return err
}
if err := f.Close(); err != nil {
return err
}
return os.Rename(f.Name(), name)
}