forked from OneOfOne/genh
-
Notifications
You must be signed in to change notification settings - Fork 0
/
files.go
44 lines (37 loc) · 840 Bytes
/
files.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
package genh
import (
"io"
"os"
)
type TypeEncoder interface {
Encode(v any) error
}
type TypeDecoder interface {
Decode(v any) error
}
func EncodeFile[EncT TypeEncoder](fp string, v any, fn func(w io.Writer) EncT) (err error) {
var f *os.File
if f, err = os.Create(fp); err != nil {
return
}
defer f.Close()
return Encode(f, v, fn)
}
func Encode[EncT TypeEncoder](w io.Writer, v any, fn func(w io.Writer) EncT) (err error) {
enc := fn(w)
err = enc.Encode(v)
return
}
func DecodeFile[T any, DecT DecoderType](fp string, fn func(r io.Reader) DecT) (v T, err error) {
var f *os.File
if f, err = os.Open(fp); err != nil {
return
}
defer f.Close()
return Decode[T](f, fn)
}
func Decode[T any, DecT DecoderType](r io.Reader, fn func(r io.Reader) DecT) (v T, err error) {
dec := fn(r)
err = dec.Decode(&v)
return
}