2024-01-01 14:58:21 -05:00
|
|
|
// Copyright 2018-2024 the Deno authors. All rights reserved. MIT license.
|
2021-04-14 15:10:48 -04:00
|
|
|
|
2021-12-07 07:39:58 -05:00
|
|
|
//! This module helps deno implement timers and performance APIs.
|
2021-04-14 15:10:48 -04:00
|
|
|
|
2023-10-05 08:34:38 -04:00
|
|
|
use deno_core::op2;
|
2021-04-14 15:10:48 -04:00
|
|
|
use deno_core::OpState;
|
|
|
|
use std::time::Instant;
|
|
|
|
|
|
|
|
pub trait TimersPermission {
|
|
|
|
fn allow_hrtime(&mut self) -> bool;
|
|
|
|
}
|
|
|
|
|
2024-06-06 23:37:53 -04:00
|
|
|
impl TimersPermission for deno_permissions::PermissionsContainer {
|
|
|
|
#[inline(always)]
|
|
|
|
fn allow_hrtime(&mut self) -> bool {
|
|
|
|
deno_permissions::PermissionsContainer::allow_hrtime(self)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2021-04-14 15:10:48 -04:00
|
|
|
pub type StartTime = Instant;
|
|
|
|
|
|
|
|
// Returns a milliseconds and nanoseconds subsec
|
|
|
|
// since the start time of the deno runtime.
|
|
|
|
// If the High precision flag is not set, the
|
|
|
|
// nanoseconds are rounded on 2ms.
|
2023-10-05 08:34:38 -04:00
|
|
|
#[op2(fast)]
|
|
|
|
pub fn op_now<TP>(state: &mut OpState, #[buffer] buf: &mut [u8])
|
2021-04-14 15:10:48 -04:00
|
|
|
where
|
|
|
|
TP: TimersPermission + 'static,
|
|
|
|
{
|
|
|
|
let start_time = state.borrow::<StartTime>();
|
2022-08-16 11:30:16 -04:00
|
|
|
let elapsed = start_time.elapsed();
|
|
|
|
let seconds = elapsed.as_secs();
|
2022-08-28 02:51:49 -04:00
|
|
|
let mut subsec_nanos = elapsed.subsec_nanos();
|
2021-04-14 15:10:48 -04:00
|
|
|
|
|
|
|
// If the permission is not enabled
|
|
|
|
// Round the nano result on 2 milliseconds
|
|
|
|
// see: https://developer.mozilla.org/en-US/docs/Web/API/DOMHighResTimeStamp#Reduced_time_precision
|
|
|
|
if !state.borrow_mut::<TP>().allow_hrtime() {
|
2022-08-28 02:51:49 -04:00
|
|
|
let reduced_time_precision = 2_000_000; // 2ms in nanoseconds
|
2021-04-14 15:10:48 -04:00
|
|
|
subsec_nanos -= subsec_nanos % reduced_time_precision;
|
|
|
|
}
|
2022-09-07 06:51:47 -04:00
|
|
|
if buf.len() < 8 {
|
|
|
|
return;
|
2022-08-28 02:51:49 -04:00
|
|
|
}
|
2022-09-07 06:51:47 -04:00
|
|
|
let buf: &mut [u32] =
|
|
|
|
// SAFETY: buffer is at least 8 bytes long.
|
|
|
|
unsafe { std::slice::from_raw_parts_mut(buf.as_mut_ptr() as _, 2) };
|
|
|
|
buf[0] = seconds as u32;
|
2022-12-17 17:20:15 -05:00
|
|
|
buf[1] = subsec_nanos;
|
2021-04-14 15:10:48 -04:00
|
|
|
}
|
|
|
|
|
2024-03-11 23:48:00 -04:00
|
|
|
#[allow(clippy::unused_async)]
|
2024-02-16 10:35:51 -05:00
|
|
|
#[op2(async(lazy), fast)]
|
2024-03-01 13:15:18 -05:00
|
|
|
pub async fn op_defer() {}
|