forked from 7574-sistemas-distribuidos/tp0-base
-
Notifications
You must be signed in to change notification settings - Fork 0
/
lottery.go
96 lines (78 loc) · 1.71 KB
/
lottery.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
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
package lottery
import (
"errors"
"io"
"os"
"time"
"github.com/juliangcalderon-fiuba/distribuidos-tp0/safeio"
"github.com/juliangcalderon-fiuba/distribuidos-tp0/protocol"
)
const STORAGE_FILEPATH = "./bets.csv"
const LOTTERY_WINNER_NUMBER = 7574
type Bet struct {
Agency int
FirstName string
LastName string
Document int
Birthdate time.Time
Number int
}
func (b Bet) HasWon() bool {
return b.Number == LOTTERY_WINNER_NUMBER
}
// Persist the information of each bet in the STORAGE_FILEPATH file.
// Not thread-safe/process-safe.
func StoreBets(bets []Bet) (err error) {
file, err := os.OpenFile(STORAGE_FILEPATH, os.O_RDWR|os.O_CREATE|os.O_APPEND, 0666)
if err != nil {
return
}
defer func() {
closeErr := file.Close()
err = errors.Join(err, closeErr)
}()
err = StoreBetsIn(file, bets)
return
}
func StoreBetsIn(w io.Writer, bets []Bet) (err error) {
writer := safeio.NewWriter(w)
for _, bet := range bets {
writer.Write(protocol.Serialize(bet))
}
err = writer.Flush()
return
}
// Loads the information all the bets in the STORAGE_FILEPATH file.
// Not thread-safe/process-safe.
func LoadBets() (bets []Bet, err error) {
file, err := os.Open(STORAGE_FILEPATH)
if err != nil {
return
}
defer func() {
closeErr := file.Close()
err = errors.Join(err, closeErr)
}()
bets, err = LoadBetsFrom(file)
return
}
func LoadBetsFrom(r io.Reader) ([]Bet, error) {
reader := safeio.NewReader(r)
bets := make([]Bet, 0)
for {
var row []string
row, err := reader.Read()
if errors.Is(err, io.EOF) {
break
}
if err != nil {
return bets, err
}
bet, err := protocol.Deserialize[Bet](row)
if err != nil {
return bets, err
}
bets = append(bets, bet)
}
return bets, nil
}