59 lines
1001 B
Go
59 lines
1001 B
Go
package account
|
|
|
|
import "sync"
|
|
|
|
// Account just represents a user's account
|
|
type Account struct {
|
|
sync.RWMutex
|
|
balance int
|
|
closed bool
|
|
}
|
|
|
|
// Open returns a new account
|
|
func Open(amt int) *Account {
|
|
a := new(Account)
|
|
_, ok := a.Deposit(amt)
|
|
if ok {
|
|
return a
|
|
}
|
|
return nil
|
|
}
|
|
|
|
// Close returns the payout amount and an 'ok' flag
|
|
func (a *Account) Close() (int, bool) {
|
|
a.Lock()
|
|
ret := a.balance
|
|
if a.closed {
|
|
a.Unlock()
|
|
return 0, false
|
|
}
|
|
a.closed = true
|
|
a.balance = 0
|
|
a.Unlock()
|
|
return ret, true
|
|
}
|
|
|
|
// Balance returns the current account balance
|
|
// and an 'ok' flag
|
|
func (a *Account) Balance() (int, bool) {
|
|
if a.closed {
|
|
return 0, false
|
|
}
|
|
return a.balance, true
|
|
}
|
|
|
|
// Deposit takes an amount (can be a withdrawal)
|
|
// and returns the new balance and an 'ok' flag
|
|
func (a *Account) Deposit(amount int) (int, bool) {
|
|
var ret int
|
|
var ok bool
|
|
a.Lock()
|
|
if !a.closed && a.balance+amount >= 0 {
|
|
a.balance += amount
|
|
ret = a.balance
|
|
ok = true
|
|
}
|
|
a.Unlock()
|
|
return ret, ok
|
|
}
|