-
Notifications
You must be signed in to change notification settings - Fork 2
/
autosave.go
57 lines (49 loc) · 1.38 KB
/
autosave.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
45
46
47
48
49
50
51
52
53
54
55
56
57
package engine
import "fmt"
var (
output = make(map[Slicer]*autosave) // when to save quantities
autonum = make(map[interface{}]int) // auto number for out file
)
func init() {
DeclFunc("Save", Save, "Save space-dependent quantity once, with auto filename")
DeclFunc("SaveAs", SaveAs, "Save space-dependent with custom filename")
DeclFunc("AutoSave", AutoSave, "Auto save space-dependent quantity every period (s).")
}
// Register quant to be auto-saved every period.
// period == 0 stops autosaving.
func AutoSave(quant Slicer, period float64) {
if period == 0 {
delete(output, quant)
} else {
output[quant] = &autosave{period, Time, 0}
}
}
// Called to save everything that's needed at this time.
func DoOutput() {
for q, a := range output {
if a.needSave() {
Save(q)
a.count++
}
}
if Table.needSave() {
Table.Save()
}
}
// Save once, with auto file name
func Save(q Slicer) {
fname := fmt.Sprintf("%s%06d.dump", q.Name(), autonum[q])
SaveAs(q, fname)
autonum[q]++
}
// keeps info needed to decide when a quantity needs to be periodically saved
type autosave struct {
period float64 // How often to save
start float64 // Starting point
count int // Number of times it has been autosaved
}
// returns true when the time is right to save.
func (a *autosave) needSave() bool {
t := Time - a.start
return a.period != 0 && t-float64(a.count)*a.period >= a.period
}