-
Notifications
You must be signed in to change notification settings - Fork 6
/
lsnowflake.c
102 lines (93 loc) · 2.5 KB
/
lsnowflake.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
#include <lua.h>
#include <lauxlib.h>
#include <stdlib.h>
#include <stdint.h>
#include "snowflake.h"
/**
* 根据UUID获得其包含的时间戳
* @function snowflake.getTimestampByUUID
* @param uuid int64 分布式唯一ID
* @return timestamp int 节点ID
*/
static int
lgetTimestampByUUID(lua_State *L) {
uint64_t i = luaL_checkinteger(L,1);
uint64_t timestamp = getTimestampByUUID(i);
lua_pushinteger(L,timestamp);
return 1;
}
/**
* 根据UUID获得其包含的节点ID
* @function snowflake.getNodeIdByUUID
* @param uuid int64 分布式唯一ID
* @return nodeId int 节点ID
*/
static int
lgetNodeIdByUUID(lua_State *L) {
uint64_t i = luaL_checkinteger(L,1);
int nodeId = getNodeIdByUUID(i);
lua_pushinteger(L,nodeId);
return 1;
}
/**
* 根据UUID获得其包含的序号ID
* @function snowflake.getSequenceByUUID
* @param uuid int64 分布式唯一ID
* @return sequence int 节点ID
*/
static int
lgetSequenceByUUID(lua_State *L) {
uint64_t i = luaL_checkinteger(L,1);
int sequence = getSequenceByUUID(i);
lua_pushinteger(L,sequence);
return 1;
}
/**
* 由时间戳,节点ID,序号构成uuid
* @function snowflake.composeUUID
* @param timestamp int 时间戳(范围:[0,2^41))
* @param nodeid int 节点ID(范围:[0,2^10))
* @param sequence int 序号(范围:[0,2^12))
* @return uuid uint64 分布式唯一ID
*/
static int
lcomposeUUID(lua_State *L) {
uint64_t timestamp = luaL_checkinteger(L,1);
int nodeid = luaL_checkinteger(L,2);
int sequence = luaL_checkinteger(L,3);
uint64_t id = composeUUID(timestamp,nodeid,sequence);
lua_pushinteger(L, id);
return 1;
}
/**
* 传递节点ID,生成分布式唯一ID
* @function snowflake.uuid
* @param nodeId int 节点ID
* @return uuid uint64 分布式唯一ID
*/
static int
luuid(lua_State *L) {
int nodeId = luaL_checkinteger(L,1);
int* sequence = (int*)lua_touserdata(L,lua_upvalueindex(1));
uint64_t id = uuid(nodeId,sequence);
lua_pushinteger(L, id);
return 1;
}
LUAMOD_API int
luaopen_snowflake_core(lua_State *L) {
luaL_checkversion(L);
luaL_Reg l[] = {
{"getTimestampByUUID",lgetTimestampByUUID},
{"getNodeIdByUUID",lgetNodeIdByUUID},
{"getSequenceByUUID",lgetSequenceByUUID},
{"composeUUID",lcomposeUUID},
{NULL,NULL},
};
luaL_newlibtable(L,l);
luaL_setfuncs(L,l,0);
int* sequence = (int*)lua_newuserdata(L,sizeof(int));
*sequence = 0;
lua_pushcclosure(L,luuid,1);
lua_setfield(L,-2,"uuid");
return 1;
}