-
Notifications
You must be signed in to change notification settings - Fork 32
Expand file tree
/
Copy pathUserListJSON.cpp
More file actions
88 lines (73 loc) · 1.95 KB
/
UserListJSON.cpp
File metadata and controls
88 lines (73 loc) · 1.95 KB
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
#include <map>
#include <string>
#include <mutex>
#include <time.h>
#include "UserListJSON.h"
using std::lock_guard;
using std::map;
using std::mutex;
using std::string;
extern "C"
{
struct JSONCache
{
int lastUserId;
string json;
};
mutex userIDMapLock;
map<string /* coin */, map<int /* puid */, string /* puname */>> userIDMaps;
map<string /* coin */, map<string /* puname */, time_t /* updateTime */>> userUpdateTimeMaps;
map<string /* coin */, JSONCache> userListJsonCaches;
void addUser(int puid, const char *puname, const char *coin)
{
lock_guard<mutex> scopeLock(userIDMapLock);
time_t now = time(nullptr);
userIDMaps[coin][puid] = puname;
userIDMaps[""][puid] = puname; // merged list
userUpdateTimeMaps[coin][puname] = now;
userUpdateTimeMaps[""][puname] = now; // merged list
// clear caches
userListJsonCaches.erase(coin);
userListJsonCaches.erase(""); // cache for merged list
}
const char *getUserListJson(int lastUserId, const char *coin)
{
lock_guard<mutex> scopeLock(userIDMapLock);
auto &cache = userListJsonCaches[coin];
if (!cache.json.empty() && cache.lastUserId == lastUserId) {
return cache.json.c_str();
}
cache.lastUserId = lastUserId;
auto &userIDMap = userIDMaps[coin];
map<int, string>::iterator iter;
if (lastUserId <= 0)
{
iter = userIDMap.begin();
}
else
{
iter = userIDMap.upper_bound(lastUserId);
}
cache.json = "{\"err_no\":0,\"err_msg\":null,\"data\":{";
while (iter != userIDMap.end())
{
cache.json += '"';
cache.json += iter->second;
cache.json += "\":";
cache.json += std::to_string(iter->first);
if (++iter != userIDMap.end())
{
cache.json += ',';
}
}
cache.json += "}}";
return cache.json.c_str();
}
int64_t getUserUpdateTime(const char *puname, const char *coin) {
auto itr = userUpdateTimeMaps[coin].find(puname);
if (itr == userUpdateTimeMaps[coin].end()) {
return 0;
}
return itr->second;
}
} // end of extern "C"