-
Notifications
You must be signed in to change notification settings - Fork 935
/
Customer.cc
77 lines (63 loc) · 1.55 KB
/
Customer.cc
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
#include <map>
#include <string>
#include <vector>
#include <boost/shared_ptr.hpp>
#include "../Mutex.h"
using std::string;
class CustomerData : boost::noncopyable
{
public:
CustomerData()
: data_(new Map)
{ }
int query(const string& customer, const string& stock) const;
private:
typedef std::pair<string, int> Entry;
typedef std::vector<Entry> EntryList;
typedef std::map<string, EntryList> Map;
typedef boost::shared_ptr<Map> MapPtr;
void update(const string& customer, const EntryList& entries);
void update(const string& message);
static int findEntry(const EntryList& entries, const string& stock);
static MapPtr parseData(const string& message);
MapPtr getData() const
{
muduo::MutexLockGuard lock(mutex_);
return data_;
}
mutable muduo::MutexLock mutex_;
MapPtr data_;
};
int CustomerData::query(const string& customer, const string& stock) const
{
MapPtr data = getData();
Map::const_iterator entries = data->find(customer);
if (entries != data->end())
return findEntry(entries->second, stock);
else
return -1;
}
void CustomerData::update(const string& customer, const EntryList& entries)
{
muduo::MutexLockGuard lock(mutex_);
if (!data_.unique())
{
MapPtr newData(new Map(*data_));
data_.swap(newData);
}
assert(data_.unique());
(*data_)[customer] = entries;
}
void CustomerData::update(const string& message)
{
MapPtr newData = parseData(message);
if (newData)
{
muduo::MutexLockGuard lock(mutex_);
data_.swap(newData);
}
}
int main()
{
CustomerData data;
}