-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathaccount.c
114 lines (100 loc) · 2.34 KB
/
account.c
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
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#include <assert.h>
#include "teller.h"
#include "account.h"
#include "error.h"
#include "debug.h"
#include "branch.h"
#include "report.h"
/*
* initialize the account based on the passed-in information.
*/
void
Account_Init(Bank *bank, Account *account, int id, int branch,
AccountAmount initialAmount)
{
extern int testfailurecode;
sem_init(&(account->accountLock), 0, 1);
account->accountNumber = Account_MakeAccountNum(branch, id);
account->balance = initialAmount;
if (testfailurecode) {
// To test failures, we initialize every 4th account with a negative value
if ((id & 0x3) == 0) {
account->balance = -1;
}
}
}
/*
* get the ID of the branch which the account is in.
*/
BranchID
AccountNum_GetBranchID(AccountNumber accountNum)
{
Y;
return (BranchID) (accountNum >> 32);
}
/*
* get the branch-wide subaccount number of the account.
*/
int
AcountNum_Subaccount(AccountNumber accountNum)
{
Y;
return (accountNum & 0x7ffffff);
}
/*
* find the account address based on the accountNum.
*/
Account *
Account_LookupByNumber(Bank *bank, AccountNumber accountNum)
{
BranchID branchID = AccountNum_GetBranchID(accountNum);
int branchIndex = AcountNum_Subaccount(accountNum);
return &(bank->branches[branchID].accounts[branchIndex]);
}
/*
* adjust the balance of the account.
*/
void
Account_Adjust(Bank *bank, Account *account, AccountAmount amount,
int updateBranch)
{
account->balance = Account_Balance(account) + amount;
if (updateBranch) {
Branch_UpdateBalance(bank, AccountNum_GetBranchID(account->accountNumber),
amount);
}
Y;
}
/*
* return the balance of the account.
*/
AccountAmount
Account_Balance(Account *account)
{
AccountAmount balance = account->balance; Y;
return balance;
}
/*
* make the account number based on the branch number and
* the branch-wise subaccount number.
*/
AccountNumber
Account_MakeAccountNum(int branch, int subaccount)
{
AccountNumber num;
num = subaccount;
num |= ((uint64_t) branch) << 32; Y;
return num;
}
/*
* Test to see if two accounts are in the same branch.
*/
int
Account_IsSameBranch(AccountNumber accountNum1, AccountNumber accountNum2)
{
return (AccountNum_GetBranchID(accountNum1) ==
AccountNum_GetBranchID(accountNum2));
}