2 ** mrb_sleep - sleep methods for mruby
4 ** Copyright (c) mod_mruby developers 2012-
5 ** Copyright (c) mruby developers 2018
7 ** Permission is hereby granted, free of charge, to any person obtaining
8 ** a copy of this software and associated documentation files (the
9 ** "Software"), to deal in the Software without restriction, including
10 ** without limitation the rights to use, copy, modify, merge, publish,
11 ** distribute, sublicense, and/or sell copies of the Software, and to
12 ** permit persons to whom the Software is furnished to do so, subject to
13 ** the following conditions:
15 ** The above copyright notice and this permission notice shall be
16 ** included in all copies or substantial portions of the Software.
18 ** THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
19 ** EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
20 ** MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
21 ** IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
22 ** CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
23 ** TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
24 ** SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
26 ** [ MIT license: http://www.opensource.org/licenses/mit-license.php ]
32 #define sleep(x) Sleep(x * 1000)
33 #define usleep(x) Sleep((DWORD)(((x)<1000) ? 1 : ((x)/1000)))
41 /* not implemented forever sleep (called without an argument)*/
43 mrb_f_sleep(mrb_state *mrb, mrb_value self)
47 #ifndef MRB_WITHOUT_FLOAT
50 mrb_get_args(mrb, "f", &sec);
52 usleep(sec * 1000000);
55 mrb_raise(mrb, E_ARGUMENT_ERROR, "time interval must not be negative");
60 mrb_get_args(mrb, "i", &sec);
64 mrb_raise(mrb, E_ARGUMENT_ERROR, "time interval must not be negative");
69 return mrb_fixnum_value(end);
72 /* mruby special; needed for mruby without float numbers */
74 mrb_f_usleep(mrb_state *mrb, mrb_value self)
79 unsigned __int64 st_time = 0;
80 unsigned __int64 ed_time = 0;
82 struct timeval st_tm,ed_tm;
87 GetSystemTimeAsFileTime(&st_ft);
89 gettimeofday(&st_tm, NULL);
92 /* not implemented forever sleep (called without an argument)*/
93 mrb_get_args(mrb, "i", &usec);
98 mrb_raise(mrb, E_ARGUMENT_ERROR, "time interval must not be negative integer");
102 GetSystemTimeAsFileTime(&ed_ft);
104 st_time |= st_ft.dwHighDateTime;
106 st_time |= st_ft.dwLowDateTime;
107 ed_time |= ed_ft.dwHighDateTime;
109 ed_time |= ed_ft.dwLowDateTime;
111 slp_tm = (ed_time - st_time) / 10;
113 gettimeofday(&ed_tm, NULL);
115 if (st_tm.tv_usec > ed_tm.tv_usec) {
116 slp_tm = 1000000 + ed_tm.tv_usec - st_tm.tv_usec;
119 slp_tm = ed_tm.tv_usec - st_tm.tv_usec;
123 return mrb_fixnum_value(slp_tm);
127 mrb_mruby_sleep_gem_init(mrb_state *mrb)
129 mrb_define_method(mrb, mrb->kernel_module, "sleep", mrb_f_sleep, MRB_ARGS_REQ(1));
130 mrb_define_method(mrb, mrb->kernel_module, "usleep", mrb_f_usleep, MRB_ARGS_REQ(1));
134 mrb_mruby_sleep_gem_final(mrb_state *mrb)