Mercurial > prosody-hg
comparison util-src/time.c @ 14080:973609bad40a
util.time: Import sleep from luasocket
We might not want to use the full LuaSocket for such a tiny function which will
never change.
This drops win32 support but that should be fine.
| author | Link Mauve <linkmauve@linkmauve.fr> |
|---|---|
| date | Fri, 30 Jan 2026 14:08:53 +0100 |
| parents | a187600ec7d6 |
| children |
comparison
equal
deleted
inserted
replaced
| 14079:0ea2848d7771 | 14080:973609bad40a |
|---|---|
| 2 #define _POSIX_C_SOURCE 200809L | 2 #define _POSIX_C_SOURCE 200809L |
| 3 #endif | 3 #endif |
| 4 | 4 |
| 5 #include <time.h> | 5 #include <time.h> |
| 6 #include <lua.h> | 6 #include <lua.h> |
| 7 #include <lauxlib.h> | |
| 7 | 8 |
| 8 static lua_Number tv2number(struct timespec *tv) { | 9 static lua_Number tv2number(struct timespec *tv) { |
| 9 return tv->tv_sec + tv->tv_nsec * 1e-9; | 10 return tv->tv_sec + tv->tv_nsec * 1e-9; |
| 10 } | 11 } |
| 11 | 12 |
| 21 clock_gettime(CLOCK_MONOTONIC, &t); | 22 clock_gettime(CLOCK_MONOTONIC, &t); |
| 22 lua_pushnumber(L, tv2number(&t)); | 23 lua_pushnumber(L, tv2number(&t)); |
| 23 return 1; | 24 return 1; |
| 24 } | 25 } |
| 25 | 26 |
| 27 /* This function has been imported from luasocket */ | |
| 28 static int lc_sleep(lua_State *L) { | |
| 29 double n = luaL_checknumber(L, 1); | |
| 30 struct timespec t, r; | |
| 31 if (n < 0.0) n = 0.0; | |
| 32 if (n > INT_MAX) n = INT_MAX; | |
| 33 t.tv_sec = (int) n; | |
| 34 n -= t.tv_sec; | |
| 35 t.tv_nsec = (int) (n * 1000000000); | |
| 36 if (t.tv_nsec >= 1000000000) t.tv_nsec = 999999999; | |
| 37 while (nanosleep(&t, &r) != 0) { | |
| 38 t.tv_sec = r.tv_sec; | |
| 39 t.tv_nsec = r.tv_nsec; | |
| 40 } | |
| 41 return 0; | |
| 42 } | |
| 43 | |
| 26 int luaopen_prosody_util_time(lua_State *L) { | 44 int luaopen_prosody_util_time(lua_State *L) { |
| 27 lua_createtable(L, 0, 2); | 45 lua_createtable(L, 0, 2); |
| 28 { | 46 { |
| 29 lua_pushcfunction(L, lc_time_realtime); | 47 lua_pushcfunction(L, lc_time_realtime); |
| 30 lua_setfield(L, -2, "now"); | 48 lua_setfield(L, -2, "now"); |
| 31 lua_pushcfunction(L, lc_time_monotonic); | 49 lua_pushcfunction(L, lc_time_monotonic); |
| 32 lua_setfield(L, -2, "monotonic"); | 50 lua_setfield(L, -2, "monotonic"); |
| 51 lua_pushcfunction(L, lc_sleep); | |
| 52 lua_setfield(L, -2, "sleep"); | |
| 33 } | 53 } |
| 34 return 1; | 54 return 1; |
| 35 } | 55 } |
| 36 int luaopen_util_time(lua_State *L) { | 56 int luaopen_util_time(lua_State *L) { |
| 37 return luaopen_prosody_util_time(L); | 57 return luaopen_prosody_util_time(L); |
