Skip to content

Commit

Permalink
Implement console#time and console#timeEnd methods
Browse files Browse the repository at this point in the history
Fixes #9325
  • Loading branch information
Joshua Holmer committed Jan 25, 2016
1 parent 842ec7c commit f076589
Show file tree
Hide file tree
Showing 2 changed files with 41 additions and 0 deletions.
39 changes: 39 additions & 0 deletions components/script/dom/console.rs
Expand Up @@ -3,23 +3,28 @@
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */

use devtools_traits::{ConsoleMessage, LogLevel, ScriptToDevtoolsControlMsg};
use dom::bindings::cell::DOMRefCell;
use dom::bindings::codegen::Bindings::ConsoleBinding;
use dom::bindings::codegen::Bindings::ConsoleBinding::ConsoleMethods;
use dom::bindings::global::GlobalRef;
use dom::bindings::js::Root;
use dom::bindings::reflector::{Reflectable, Reflector, reflect_dom_object};
use std::collections::HashMap;
use time::{Timespec, get_time};
use util::str::DOMString;

// https://developer.mozilla.org/en-US/docs/Web/API/Console
#[dom_struct]
pub struct Console {
reflector_: Reflector,
timers: DOMRefCell<HashMap<DOMString, u64>>,
}

impl Console {
fn new_inherited() -> Console {
Console {
reflector_: Reflector::new(),
timers: DOMRefCell::new(HashMap::new()),
}
}

Expand Down Expand Up @@ -92,6 +97,40 @@ impl ConsoleMethods for Console {
self.send_to_devtools(LogLevel::Error, message);
}
}

// https://developer.mozilla.org/en-US/docs/Web/API/Console/time
fn Time(&self, label: DOMString) {
let mut timers = self.timers.borrow_mut();
if timers.contains_key(&label) {
// Timer already started
return;
}
if timers.len() >= 10000 {
// Too many timers on page
return;
}

timers.insert(label.clone(), timestamp_in_ms(get_time()));
let message = DOMString::from(format!("{}: timer started", label));
println!("{}", message);
self.send_to_devtools(LogLevel::Log, message);
}

// https://developer.mozilla.org/en-US/docs/Web/API/Console/timeEnd
fn TimeEnd(&self, label: DOMString) {
let mut timers = self.timers.borrow_mut();
if let Some(start) = timers.remove(&label) {
let message = DOMString::from(
format!("{}: {}ms", label, timestamp_in_ms(get_time()) - start)
);
println!("{}", message);
self.send_to_devtools(LogLevel::Log, message);
};
}
}

fn timestamp_in_ms(time: Timespec) -> u64 {
(time.sec * 1000 + (time.nsec / 1000000) as i64) as u64
}

fn prepare_message(logLevel: LogLevel, message: DOMString) -> ConsoleMessage {
Expand Down
2 changes: 2 additions & 0 deletions components/script/dom/webidls/Console.webidl
Expand Up @@ -18,4 +18,6 @@ interface Console {
void warn(DOMString... messages);
void error(DOMString... messages);
void assert(boolean condition, optional DOMString message);
void time(DOMString message);
void timeEnd(DOMString message);
};

0 comments on commit f076589

Please sign in to comment.