fs use binary (um)marshaler

This commit is contained in:
Ilia Denisov
2025-09-23 22:02:21 +03:00
parent 4d733ae741
commit c777ba91dd
4 changed files with 51 additions and 10 deletions
+24 -5
View File
@@ -1,6 +1,7 @@
package fs
import (
"encoding"
"errors"
"fmt"
"math/big"
@@ -74,7 +75,11 @@ func (f *fs) Lock() (func() error, error) {
return unlock, nil
}
func (f *fs) Write(path string, data []byte) error {
func (f *fs) Write(path string, v encoding.BinaryMarshaler) error {
if v == nil {
return errors.New("cant't marshal from nil object")
}
if f.lock == nil {
return errors.New("lock must be acquired before write")
}
@@ -84,6 +89,11 @@ func (f *fs) Write(path string, data []byte) error {
return errors.New("can't write to the lock file")
}
data, err := v.MarshalBinary()
if err != nil {
return fmt.Errorf("marshal data: %s", err)
}
targetDir := filepath.Dir(targetFilePath)
if targetDir != f.root {
ok, err := dirExists(targetDir)
@@ -146,17 +156,26 @@ func (f *fs) Write(path string, data []byte) error {
return nil
}
func (f *fs) Read(path string) ([]byte, error) {
func (f *fs) Read(path string, v encoding.BinaryUnmarshaler) error {
if v == nil {
return errors.New("can't unmarshal to a nil object")
}
if f.lock != nil {
return nil, errors.New("lock must be released before read")
return errors.New("lock must be released before read")
}
targetFilePath := filepath.Join(f.root, path)
if targetFilePath == f.lockFilePath() {
return nil, errors.New("can't read from the lock file")
return errors.New("can't read from the lock file")
}
return os.ReadFile(targetFilePath)
data, err := os.ReadFile(targetFilePath)
if err != nil {
return fmt.Errorf("reading data file: %s", err)
}
return v.UnmarshalBinary(data)
}
func (f *fs) lockFilePath() string {