-
-
Notifications
You must be signed in to change notification settings - Fork 485
Implement Performance.now() and Performance.timeOrigin #4551
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
HalidOdat
wants to merge
1
commit into
boa-dev:main
Choose a base branch
from
HalidOdat:feature/performance-now
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from all commits
Commits
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,152 @@ | ||
| //! Boa's implementation of the `performance` Web API object. | ||
| //! | ||
| //! The `performance` object provides access to performance-related information. | ||
| //! | ||
| //! More information: | ||
| //! - [MDN documentation][mdn] | ||
| //! - [W3C High Resolution Time specification][spec] | ||
| //! | ||
| //! [spec]: https://w3c.github.io/hr-time/ | ||
| //! [mdn]: https://developer.mozilla.org/en-US/docs/Web/API/Performance | ||
|
|
||
| use boa_engine::{ | ||
| Context, JsData, JsNativeError, JsResult, JsValue, NativeFunction, | ||
| context::time::JsInstant, | ||
| js_string, | ||
| object::{FunctionObjectBuilder, ObjectInitializer}, | ||
| property::Attribute, | ||
| }; | ||
| use boa_gc::{Finalize, Trace}; | ||
|
|
||
| #[cfg(test)] | ||
| mod tests; | ||
|
|
||
| /// The `Performance` object. | ||
| #[derive(Debug, Trace, Finalize, JsData)] | ||
| pub struct Performance { | ||
| #[unsafe_ignore_trace] | ||
| time_origin: JsInstant, | ||
| } | ||
|
|
||
| impl Performance { | ||
| /// Create a new `Performance` object. | ||
| #[must_use] | ||
| pub fn new(context: &Context) -> Self { | ||
| Self { | ||
| time_origin: context.clock().now(), | ||
| } | ||
| } | ||
|
|
||
| /// Register the `Performance` object in the context. | ||
| /// | ||
| /// # Errors | ||
| /// Returns an error if the `performance` property already exists in the global object. | ||
| pub fn register(context: &mut Context) -> JsResult<()> { | ||
| let performance = Self::new(context); | ||
|
|
||
| let get_time_origin = FunctionObjectBuilder::new( | ||
| context.realm(), | ||
| NativeFunction::from_fn_ptr(Self::get_time_origin), | ||
| ) | ||
| .name(js_string!("get timeOrigin")) | ||
| .length(0) | ||
| .build(); | ||
|
|
||
| let performance_obj = ObjectInitializer::with_native_data(performance, context) | ||
| .function(NativeFunction::from_fn_ptr(Self::now), js_string!("now"), 0) | ||
| .accessor( | ||
| js_string!("timeOrigin"), | ||
| Some(get_time_origin), | ||
| None, | ||
| Attribute::CONFIGURABLE | Attribute::NON_ENUMERABLE, | ||
| ) | ||
| .build(); | ||
|
|
||
| context.register_global_property( | ||
| js_string!("performance"), | ||
| performance_obj, | ||
| Attribute::WRITABLE | Attribute::NON_ENUMERABLE | Attribute::CONFIGURABLE, | ||
| )?; | ||
|
|
||
| Ok(()) | ||
| } | ||
|
|
||
| /// `Performance.timeOrigin` getter | ||
| /// | ||
| /// The `timeOrigin` read-only property returns the high resolution timestamp | ||
| /// that is used as the baseline for performance-related timestamps. | ||
| /// | ||
| /// More information: | ||
| /// - [MDN documentation][mdn] | ||
| /// - [W3C specification][spec] | ||
| /// | ||
| /// [spec]: https://w3c.github.io/hr-time/#dom-performance-timeorigin | ||
| /// [mdn]: https://developer.mozilla.org/en-US/docs/Web/API/Performance/timeOrigin | ||
| fn get_time_origin( | ||
| this: &JsValue, | ||
| _args: &[JsValue], | ||
| _context: &mut Context, | ||
| ) -> JsResult<JsValue> { | ||
| // The timeOrigin attribute MUST return the number of milliseconds in the duration returned by get | ||
| // time origin timestamp for the relevant global object of this. | ||
| // | ||
| // The time values returned when getting Performance.timeOrigin MUST use the same monotonic clock | ||
| // that is shared by time origins, and whose reference point is the [ECMA-262] time definition - | ||
| // see 9. Security Considerations. | ||
|
|
||
| let obj = this.as_object().ok_or_else(|| { | ||
| JsNativeError::typ().with_message("'this' is not a Performance object") | ||
| })?; | ||
|
|
||
| let performance = obj.downcast_ref::<Self>().ok_or_else(|| { | ||
| JsNativeError::typ().with_message("'this' is not a Performance object") | ||
| })?; | ||
|
|
||
| #[allow(clippy::cast_precision_loss)] | ||
| let time_origin_millis = performance.time_origin.nanos_since_epoch() as f64 / 1_000_000.0; | ||
| Ok(JsValue::from(time_origin_millis)) | ||
| } | ||
|
|
||
| /// `performance.now()` | ||
| /// | ||
| /// The `now()` method returns a high resolution timestamp in milliseconds. | ||
| /// It represents the time elapsed since `time_origin`. | ||
| /// | ||
| /// More information: | ||
| /// - [MDN documentation][mdn] | ||
| /// - [W3C specification][spec] | ||
| /// | ||
| /// [spec]: https://w3c.github.io/hr-time/#dom-performance-now | ||
| /// [mdn]: https://developer.mozilla.org/en-US/docs/Web/API/Performance/now | ||
| fn now(this: &JsValue, _args: &[JsValue], context: &mut Context) -> JsResult<JsValue> { | ||
| // The now() method MUST return the number of milliseconds in the current high resolution time | ||
| // given this's relevant global object (a duration). | ||
| // | ||
| // The time values returned when calling the now() method on Performance objects with the | ||
| // same time origin MUST use the same monotonic clock. The difference between any two | ||
| // chronologically recorded time values returned from the now() method MUST never be | ||
| // negative if the two time values have the same time origin. | ||
|
|
||
| let obj = this.as_object().ok_or_else(|| { | ||
| JsNativeError::typ().with_message("'this' is not a Performance object") | ||
| })?; | ||
|
|
||
| let performance = obj.downcast_ref::<Self>().ok_or_else(|| { | ||
| JsNativeError::typ().with_message("'this' is not a Performance object") | ||
| })?; | ||
|
|
||
| // Step 1: Get time origin from the Performance object | ||
| let time_origin = performance.time_origin; | ||
|
|
||
| // Step 2: Get current high resolution time | ||
| let now = context.clock().now(); | ||
|
|
||
| // Step 3: Calculate duration from time_origin to now in milliseconds | ||
| let elapsed = now - time_origin; | ||
|
|
||
| #[allow(clippy::cast_precision_loss)] | ||
| let milliseconds = elapsed.as_nanos() as f64 / 1_000_000.0; | ||
|
|
||
| Ok(JsValue::from(milliseconds)) | ||
| } | ||
| } | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,52 @@ | ||
| use crate::Performance; | ||
| use crate::test::{TestAction, run_test_actions}; | ||
| use indoc::indoc; | ||
|
|
||
| const TEST_HARNESS: &str = r#" | ||
| function assert_true(condition, message) { | ||
| if (!condition) { | ||
| throw new Error(`Assertion failed: ${message || ''}`); | ||
| } | ||
| } | ||
| "#; | ||
|
|
||
| #[test] | ||
| fn performance_now_returns_number() { | ||
| run_test_actions([ | ||
| TestAction::inspect_context(|ctx| { | ||
| Performance::register(ctx).unwrap(); | ||
| }), | ||
| TestAction::run(TEST_HARNESS), | ||
| TestAction::run(indoc! {r#" | ||
| assert_true(typeof performance.now() === 'number'); | ||
| "#}), | ||
| ]); | ||
| } | ||
|
|
||
| #[test] | ||
| fn performance_now_increases() { | ||
| run_test_actions([ | ||
| TestAction::inspect_context(|ctx| { | ||
| Performance::register(ctx).unwrap(); | ||
| }), | ||
| TestAction::run(TEST_HARNESS), | ||
| TestAction::run(indoc! {r#" | ||
| const t1 = performance.now(); | ||
| const t2 = performance.now(); | ||
| assert_true(t2 >= t1, 'time should increase'); | ||
| "#}), | ||
| ]); | ||
| } | ||
|
|
||
| #[test] | ||
| fn performance_now_is_non_negative() { | ||
| run_test_actions([ | ||
| TestAction::inspect_context(|ctx| { | ||
| Performance::register(ctx).unwrap(); | ||
| }), | ||
| TestAction::run(TEST_HARNESS), | ||
| TestAction::run(indoc! {r#" | ||
| assert_true(performance.now() >= 0, 'time should be non-negative'); | ||
| "#}), | ||
| ]); | ||
| } |
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Any reason you don't use the
boa_classproc macro here? It would significantly reduce the code.