Skip to content

Commit

Permalink
perf(runtime): optimize PermissionState::check (denoland#9993)
Browse files Browse the repository at this point in the history
  • Loading branch information
AaronO committed Apr 12, 2021
1 parent 875ac73 commit 5c2a8cd
Showing 1 changed file with 47 additions and 29 deletions.
76 changes: 47 additions & 29 deletions runtime/permissions.rs
Original file line number Diff line number Diff line change
Expand Up @@ -34,35 +34,60 @@ pub enum PermissionState {
}

impl PermissionState {
#[inline(always)]
fn log_perm_access(name: &str, info: Option<&str>) {
debug!(
"{}",
colors::bold(&format!(
"{}️ Granted {}",
PERMISSION_EMOJI,
Self::fmt_access(name, info)
))
);
}

fn fmt_access(name: &str, info: Option<&str>) -> String {
format!(
"{} access{}",
name,
info.map_or(String::new(), |info| { format!(" to {}", info) }),
)
}

fn error(name: &str, info: Option<&str>) -> AnyError {
custom_error(
"PermissionDenied",
format!(
"Requires {}, run again with the --allow-{} flag",
Self::fmt_access(name, info),
name
),
)
}

/// Check the permission state. bool is whether a prompt was issued.
fn check(
self,
name: &str,
info: Option<&str>,
prompt: bool,
) -> (Result<(), AnyError>, bool) {
let access = format!(
"{} access{}",
name,
info.map_or(String::new(), |info| { format!(" to {}", info) }),
);
let result = if self == PermissionState::Granted
|| (prompt
&& self == PermissionState::Prompt
&& permission_prompt(&access))
{
log_perm_access(&access);
Ok(())
} else {
Err(custom_error(
"PermissionDenied",
format!(
"Requires {}, run again with the --allow-{} flag",
access, name
),
))
};
(result, prompt && self == PermissionState::Prompt)
match self {
PermissionState::Granted => {
Self::log_perm_access(name, info);
(Ok(()), false)
}
PermissionState::Prompt if prompt => {
let msg = Self::fmt_access(name, info);
if permission_prompt(&msg) {
Self::log_perm_access(name, info);
(Ok(()), true)
} else {
(Err(Self::error(name, info)), true)
}
}
_ => (Err(Self::error(name, info)), false),
}
}
}

Expand Down Expand Up @@ -820,13 +845,6 @@ impl deno_websocket::WebSocketPermissions for Permissions {
}
}

fn log_perm_access(message: &str) {
debug!(
"{}",
colors::bold(&format!("{}️ Granted {}", PERMISSION_EMOJI, message))
);
}

fn boolean_permission_from_flag_bool(
flag: bool,
name: &'static str,
Expand Down

0 comments on commit 5c2a8cd

Please sign in to comment.