file_name
large_stringlengths 4
69
| prefix
large_stringlengths 0
26.7k
| suffix
large_stringlengths 0
24.8k
| middle
large_stringlengths 0
2.12k
| fim_type
large_stringclasses 4
values |
---|---|---|---|---|
lib.rs | #![deny(missing_debug_implementations)]
use janus_plugin_sys as ffi;
use bitflags::bitflags;
pub use debug::LogLevel;
pub use debug::log;
pub use jansson::{JanssonDecodingFlags, JanssonEncodingFlags, JanssonValue, RawJanssonValue};
pub use session::SessionWrapper;
pub use ffi::events::janus_eventhandler as EventHandler;
pub use ffi::plugin::janus_callbacks as PluginCallbacks;
pub use ffi::plugin::janus_plugin as Plugin;
pub use ffi::plugin::janus_plugin_result as RawPluginResult;
pub use ffi::plugin::janus_plugin_session as PluginSession;
pub use ffi::plugin::janus_plugin_rtp as PluginRtpPacket;
pub use ffi::plugin::janus_plugin_rtcp as PluginRtcpPacket;
pub use ffi::plugin::janus_plugin_data as PluginDataPacket;
pub use ffi::plugin::janus_plugin_rtp_extensions as PluginRtpExtensions;
use ffi::plugin::janus_plugin_result_type as PluginResultType;
use std::error::Error;
use std::fmt;
use std::ffi::CStr;
use std::mem;
use std::ops::Deref;
use std::os::raw::{c_char, c_int};
use std::ptr;
pub mod debug;
pub mod rtcp;
pub mod sdp;
pub mod session;
pub mod jansson;
pub mod utils;
pub mod refcount;
bitflags! {
/// Flags that control which events an event handler receives.
pub struct JanusEventType: u32 {
const JANUS_EVENT_TYPE_SESSION = 1 << 0;
const JANUS_EVENT_TYPE_HANDLE = 1 << 1;
const JANUS_EVENT_TYPE_JSEP = 1 << 3; // yes, really
const JANUS_EVENT_TYPE_WEBRTC = 1 << 4;
const JANUS_EVENT_TYPE_MEDIA = 1 << 5;
const JANUS_EVENT_TYPE_PLUGIN = 1 << 6;
const JANUS_EVENT_TYPE_TRANSPORT = 1 << 7;
const JANUS_EVENT_TYPE_CORE = 1 << 8;
}
}
/// An error emitted by the Janus core in response to a plugin pushing an event.
#[derive(Debug, Clone, Copy)]
pub struct JanusError {
pub code: i32
}
/// A result from pushing an event to Janus core.
pub type JanusResult = Result<(), JanusError>;
impl JanusError {
/// Returns Janus's description text for this error.
pub fn to_cstr(self) -> &'static CStr {
unsafe { CStr::from_ptr(ffi::janus_get_api_error(self.code)) }
}
/// Converts a Janus result code to either success or a potential error.
pub fn from(val: i32) -> JanusResult {
match val {
0 => Ok(()),
e => Err(JanusError { code: e })
}
}
}
impl Error for JanusError {}
impl fmt::Display for JanusError {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "{} (code: {})", self.to_cstr().to_str().unwrap()
, self.code)
}
}
/// A Janus plugin result; what a plugin returns to the gateway as a direct response to a signalling message.
#[derive(Debug)]
pub struct PluginResult {
ptr: *mut RawPluginResult,
}
impl PluginResult {
/// Creates a new plugin result.
pub unsafe fn new(type_: PluginResultType, text: *const c_char, content: *mut RawJanssonValue) -> Self {
Self { ptr: ffi::plugin::janus_plugin_result_new(type_, text, content) }
}
/// Creates a plugin result indicating a synchronously successful request. The provided response
/// JSON will be passed back to the client.
pub fn ok(response: JanssonValue) -> Self {
unsafe { Self::new(PluginResultType::JANUS_PLUGIN_OK, ptr::null(), response.into_raw()) }
}
/// Creates a plugin result indicating an asynchronous request in progress. If provided, the hint text
/// will be synchronously passed back to the client in the acknowledgement.
pub fn ok_wait(hint: Option<&'static CStr>) -> Self {
let hint_ptr = hint.map(|x| x.as_ptr()).unwrap_or_else(ptr::null);
unsafe { Self::new(PluginResultType::JANUS_PLUGIN_OK_WAIT, hint_ptr, ptr::null_mut()) }
}
/// Creates a plugin result indicating an error. The provided error text will be synchronously passed
/// back to the client.
pub fn error(msg: &'static CStr) -> Self {
unsafe { Self::new(PluginResultType::JANUS_PLUGIN_ERROR, msg.as_ptr(), ptr::null_mut()) }
}
/// Transfers ownership of this result to the wrapped raw pointer. The consumer is responsible for calling
/// `janus_plugin_result_destroy` on the pointer when finished.
pub fn into_raw(self) -> *mut RawPluginResult {
let ptr = self.ptr;
mem::forget(self);
ptr
}
}
impl Deref for PluginResult {
type Target = RawPluginResult;
fn deref(&self) -> &RawPluginResult {
unsafe { &*self.ptr }
}
}
impl Drop for PluginResult {
fn drop(&mut self) {
unsafe { ffi::plugin::janus_plugin_result_destroy(self.ptr) }
}
}
unsafe impl Send for PluginResult {}
#[derive(Debug)]
/// Represents metadata about this library which Janus can query at runtime.
pub struct LibraryMetadata<'a> {
pub api_version: c_int,
pub version: c_int,
pub version_str: &'a CStr,
pub description: &'a CStr,
pub name: &'a CStr,
pub author: &'a CStr,
pub package: &'a CStr,
}
/// Helper macro to produce a Janus plugin instance. Should be called with
/// a `LibraryMetadata` instance and a series of exported plugin callbacks.
#[macro_export]
macro_rules! build_plugin {
($md:expr, $($cb:ident),*) => {{
extern "C" fn get_api_compatibility() -> c_int { $md.api_version }
extern "C" fn get_version() -> c_int { $md.version } | $crate::Plugin {
get_api_compatibility,
get_version,
get_version_string,
get_description,
get_name,
get_author,
get_package,
$($cb,)*
}
}}
}
/// Macro to export a Janus plugin instance from this module.
#[macro_export]
macro_rules! export_plugin {
($pl:expr) => {
/// Called by Janus to create an instance of this plugin, using the provided callbacks to dispatch events.
#[no_mangle]
pub extern "C" fn create() -> *const $crate::Plugin { $pl }
}
}
/// Helper macro to produce a Janus event handler instance. Should be called with
/// a `LibraryMetadata` instance and a series of exported event handler callbacks.
#[macro_export]
macro_rules! build_eventhandler {
($md:expr, $mask:expr, $($cb:ident),*) => {{
extern "C" fn get_api_compatibility() -> c_int { $md.api_version }
extern "C" fn get_version() -> c_int { $md.version }
extern "C" fn get_version_string() -> *const c_char { $md.version_str.as_ptr() }
extern "C" fn get_description() -> *const c_char { $md.description.as_ptr() }
extern "C" fn get_name() -> *const c_char { $md.name.as_ptr() }
extern "C" fn get_author() -> *const c_char { $md.author.as_ptr() }
extern "C" fn get_package() -> *const c_char { $md.package.as_ptr() }
$crate::EventHandler {
events_mask: $mask,
get_api_compatibility,
get_version,
get_version_string,
get_description,
get_name,
get_author,
get_package,
$($cb,)*
}
}}
}
/// Macro to export a Janus event handler instance from this module.
#[macro_export]
macro_rules! export_eventhandler {
($evh:expr) => {
/// Called by Janus to create an instance of this event handler, using the provided callbacks to dispatch events.
#[no_mangle]
pub extern "C" fn create() -> *const $crate::EventHandler { $evh }
}
} | extern "C" fn get_version_string() -> *const c_char { $md.version_str.as_ptr() }
extern "C" fn get_description() -> *const c_char { $md.description.as_ptr() }
extern "C" fn get_name() -> *const c_char { $md.name.as_ptr() }
extern "C" fn get_author() -> *const c_char { $md.author.as_ptr() }
extern "C" fn get_package() -> *const c_char { $md.package.as_ptr() } | random_line_split |
events.rs | // Copyright 2013 The GLFW-RS Developers. For a full listing of the authors,
// refer to the AUTHORS file at the top-level directory of this distribution.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
extern crate native;
extern crate glfw;
use glfw::Context;
#[start]
fn start(argc: int, argv: *const *const u8) -> int {
native::start(argc, argv, main)
}
fn main() {
let glfw = glfw::init(glfw::FAIL_ON_ERRORS).unwrap();
glfw.window_hint(glfw::Resizable(true));
let (window, events) = glfw.create_window(800, 600, "Hello, I am a window.", glfw::Windowed)
.expect("Failed to create GLFW window.");
window.set_sticky_keys(true);
// Polling of events can be turned on and off by the specific event type
window.set_pos_polling(true);
window.set_all_polling(true);
window.set_size_polling(true);
window.set_close_polling(true);
window.set_refresh_polling(true);
window.set_focus_polling(true);
window.set_iconify_polling(true);
window.set_framebuffer_size_polling(true);
window.set_key_polling(true);
window.set_char_polling(true);
window.set_mouse_button_polling(true);
window.set_cursor_pos_polling(true);
window.set_cursor_enter_polling(true);
window.set_scroll_polling(true);
// Alternatively, all event types may be set to poll at once. Note that
// in this example, this call is redundant as all events have been set
// to poll in the above code.
window.set_all_polling(true);
window.make_current();
while!window.should_close() {
glfw.poll_events();
for event in glfw::flush_messages(&events) {
handle_window_event(&window, event);
}
}
}
fn | (window: &glfw::Window, (time, event): (f64, glfw::WindowEvent)) {
match event {
glfw::PosEvent(x, y) => window.set_title(format!("Time: {}, Window pos: ({}, {})", time, x, y).as_slice()),
glfw::SizeEvent(w, h) => window.set_title(format!("Time: {}, Window size: ({}, {})", time, w, h).as_slice()),
glfw::CloseEvent => println!("Time: {}, Window close requested.", time),
glfw::RefreshEvent => println!("Time: {}, Window refresh callback triggered.", time),
glfw::FocusEvent(true) => println!("Time: {}, Window focus gained.", time),
glfw::FocusEvent(false) => println!("Time: {}, Window focus lost.", time),
glfw::IconifyEvent(true) => println!("Time: {}, Window was minimised", time),
glfw::IconifyEvent(false) => println!("Time: {}, Window was maximised.", time),
glfw::FramebufferSizeEvent(w, h) => println!("Time: {}, Framebuffer size: ({}, {})", time, w, h),
glfw::CharEvent(character) => println!("Time: {}, Character: {}", time, character),
glfw::MouseButtonEvent(btn, action, mods) => println!("Time: {}, Button: {}, Action: {}, Modifiers: [{}]", time, glfw::ShowAliases(btn), action, mods),
glfw::CursorPosEvent(xpos, ypos) => window.set_title(format!("Time: {}, Cursor position: ({}, {})", time, xpos, ypos).as_slice()),
glfw::CursorEnterEvent(true) => println!("Time: {}, Cursor entered window.", time),
glfw::CursorEnterEvent(false) => println!("Time: {}, Cursor left window.", time),
glfw::ScrollEvent(x, y) => window.set_title(format!("Time: {}, Scroll offset: ({}, {})", time, x, y).as_slice()),
glfw::KeyEvent(key, scancode, action, mods) => {
println!("Time: {}, Key: {}, ScanCode: {}, Action: {}, Modifiers: [{}]", time, key, scancode, action, mods);
match (key, action) {
(glfw::KeyEscape, glfw::Press) => window.set_should_close(true),
(glfw::KeyR, glfw::Press) => {
// Resize should cause the window to "refresh"
let (window_width, window_height) = window.get_size();
window.set_size(window_width + 1, window_height);
window.set_size(window_width, window_height);
}
_ => {}
}
}
}
}
| handle_window_event | identifier_name |
events.rs | // Copyright 2013 The GLFW-RS Developers. For a full listing of the authors,
// refer to the AUTHORS file at the top-level directory of this distribution.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
extern crate native;
extern crate glfw;
use glfw::Context;
#[start]
fn start(argc: int, argv: *const *const u8) -> int {
native::start(argc, argv, main)
}
fn main() | window.set_char_polling(true);
window.set_mouse_button_polling(true);
window.set_cursor_pos_polling(true);
window.set_cursor_enter_polling(true);
window.set_scroll_polling(true);
// Alternatively, all event types may be set to poll at once. Note that
// in this example, this call is redundant as all events have been set
// to poll in the above code.
window.set_all_polling(true);
window.make_current();
while!window.should_close() {
glfw.poll_events();
for event in glfw::flush_messages(&events) {
handle_window_event(&window, event);
}
}
}
fn handle_window_event(window: &glfw::Window, (time, event): (f64, glfw::WindowEvent)) {
match event {
glfw::PosEvent(x, y) => window.set_title(format!("Time: {}, Window pos: ({}, {})", time, x, y).as_slice()),
glfw::SizeEvent(w, h) => window.set_title(format!("Time: {}, Window size: ({}, {})", time, w, h).as_slice()),
glfw::CloseEvent => println!("Time: {}, Window close requested.", time),
glfw::RefreshEvent => println!("Time: {}, Window refresh callback triggered.", time),
glfw::FocusEvent(true) => println!("Time: {}, Window focus gained.", time),
glfw::FocusEvent(false) => println!("Time: {}, Window focus lost.", time),
glfw::IconifyEvent(true) => println!("Time: {}, Window was minimised", time),
glfw::IconifyEvent(false) => println!("Time: {}, Window was maximised.", time),
glfw::FramebufferSizeEvent(w, h) => println!("Time: {}, Framebuffer size: ({}, {})", time, w, h),
glfw::CharEvent(character) => println!("Time: {}, Character: {}", time, character),
glfw::MouseButtonEvent(btn, action, mods) => println!("Time: {}, Button: {}, Action: {}, Modifiers: [{}]", time, glfw::ShowAliases(btn), action, mods),
glfw::CursorPosEvent(xpos, ypos) => window.set_title(format!("Time: {}, Cursor position: ({}, {})", time, xpos, ypos).as_slice()),
glfw::CursorEnterEvent(true) => println!("Time: {}, Cursor entered window.", time),
glfw::CursorEnterEvent(false) => println!("Time: {}, Cursor left window.", time),
glfw::ScrollEvent(x, y) => window.set_title(format!("Time: {}, Scroll offset: ({}, {})", time, x, y).as_slice()),
glfw::KeyEvent(key, scancode, action, mods) => {
println!("Time: {}, Key: {}, ScanCode: {}, Action: {}, Modifiers: [{}]", time, key, scancode, action, mods);
match (key, action) {
(glfw::KeyEscape, glfw::Press) => window.set_should_close(true),
(glfw::KeyR, glfw::Press) => {
// Resize should cause the window to "refresh"
let (window_width, window_height) = window.get_size();
window.set_size(window_width + 1, window_height);
window.set_size(window_width, window_height);
}
_ => {}
}
}
}
}
| {
let glfw = glfw::init(glfw::FAIL_ON_ERRORS).unwrap();
glfw.window_hint(glfw::Resizable(true));
let (window, events) = glfw.create_window(800, 600, "Hello, I am a window.", glfw::Windowed)
.expect("Failed to create GLFW window.");
window.set_sticky_keys(true);
// Polling of events can be turned on and off by the specific event type
window.set_pos_polling(true);
window.set_all_polling(true);
window.set_size_polling(true);
window.set_close_polling(true);
window.set_refresh_polling(true);
window.set_focus_polling(true);
window.set_iconify_polling(true);
window.set_framebuffer_size_polling(true);
window.set_key_polling(true); | identifier_body |
events.rs | // Copyright 2013 The GLFW-RS Developers. For a full listing of the authors,
// refer to the AUTHORS file at the top-level directory of this distribution.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
extern crate native;
extern crate glfw;
use glfw::Context;
#[start]
fn start(argc: int, argv: *const *const u8) -> int {
native::start(argc, argv, main)
} | glfw.window_hint(glfw::Resizable(true));
let (window, events) = glfw.create_window(800, 600, "Hello, I am a window.", glfw::Windowed)
.expect("Failed to create GLFW window.");
window.set_sticky_keys(true);
// Polling of events can be turned on and off by the specific event type
window.set_pos_polling(true);
window.set_all_polling(true);
window.set_size_polling(true);
window.set_close_polling(true);
window.set_refresh_polling(true);
window.set_focus_polling(true);
window.set_iconify_polling(true);
window.set_framebuffer_size_polling(true);
window.set_key_polling(true);
window.set_char_polling(true);
window.set_mouse_button_polling(true);
window.set_cursor_pos_polling(true);
window.set_cursor_enter_polling(true);
window.set_scroll_polling(true);
// Alternatively, all event types may be set to poll at once. Note that
// in this example, this call is redundant as all events have been set
// to poll in the above code.
window.set_all_polling(true);
window.make_current();
while!window.should_close() {
glfw.poll_events();
for event in glfw::flush_messages(&events) {
handle_window_event(&window, event);
}
}
}
fn handle_window_event(window: &glfw::Window, (time, event): (f64, glfw::WindowEvent)) {
match event {
glfw::PosEvent(x, y) => window.set_title(format!("Time: {}, Window pos: ({}, {})", time, x, y).as_slice()),
glfw::SizeEvent(w, h) => window.set_title(format!("Time: {}, Window size: ({}, {})", time, w, h).as_slice()),
glfw::CloseEvent => println!("Time: {}, Window close requested.", time),
glfw::RefreshEvent => println!("Time: {}, Window refresh callback triggered.", time),
glfw::FocusEvent(true) => println!("Time: {}, Window focus gained.", time),
glfw::FocusEvent(false) => println!("Time: {}, Window focus lost.", time),
glfw::IconifyEvent(true) => println!("Time: {}, Window was minimised", time),
glfw::IconifyEvent(false) => println!("Time: {}, Window was maximised.", time),
glfw::FramebufferSizeEvent(w, h) => println!("Time: {}, Framebuffer size: ({}, {})", time, w, h),
glfw::CharEvent(character) => println!("Time: {}, Character: {}", time, character),
glfw::MouseButtonEvent(btn, action, mods) => println!("Time: {}, Button: {}, Action: {}, Modifiers: [{}]", time, glfw::ShowAliases(btn), action, mods),
glfw::CursorPosEvent(xpos, ypos) => window.set_title(format!("Time: {}, Cursor position: ({}, {})", time, xpos, ypos).as_slice()),
glfw::CursorEnterEvent(true) => println!("Time: {}, Cursor entered window.", time),
glfw::CursorEnterEvent(false) => println!("Time: {}, Cursor left window.", time),
glfw::ScrollEvent(x, y) => window.set_title(format!("Time: {}, Scroll offset: ({}, {})", time, x, y).as_slice()),
glfw::KeyEvent(key, scancode, action, mods) => {
println!("Time: {}, Key: {}, ScanCode: {}, Action: {}, Modifiers: [{}]", time, key, scancode, action, mods);
match (key, action) {
(glfw::KeyEscape, glfw::Press) => window.set_should_close(true),
(glfw::KeyR, glfw::Press) => {
// Resize should cause the window to "refresh"
let (window_width, window_height) = window.get_size();
window.set_size(window_width + 1, window_height);
window.set_size(window_width, window_height);
}
_ => {}
}
}
}
} |
fn main() {
let glfw = glfw::init(glfw::FAIL_ON_ERRORS).unwrap();
| random_line_split |
second.rs | // Module containing functions for calculating second order greeks
use std::f64::consts::E;
use common::*;
/// Calculates the Gamma for an option
///
/// Gamma measures the rate of change in the delta with respect to the change in the underlying price.
///
/// # Arguments
/// * `s0` - The underlying price of the option
/// * `x` - The strike price of the option
/// * `t` - time to expiration as a percentage of the year
/// * `r` - continuously compounded risk-free interest rate
/// * `q` - continuously compounded divident yield
/// * `sigma` - volatility
pub fn gamma(s0: f64, x: f64, t: f64, r: f64, q: f64, sigma: f64) -> f64 {
let d1 = d1(s0, x, t, r, q, sigma);
return gamma_d1(s0, t, q, sigma, d1);
}
pub fn gamma_d1(s0: f64, t: f64, q: f64, sigma: f64, d1: f64) -> f64 {
let arg1 = E.powf(-(q * t)) / (s0 * sigma * (t.sqrt()));
let arg2 = one_over_sqrt_pi();
let arg3 = E.powf((-d1).powf(2.0)) / 2.0;
return arg1 * arg2 * arg3;
}
#[cfg(test)]
mod tests {
use greeks::*;
const UNDERLYING: f64 = 64.68;
const STRIKE: f64 = 65.00;
const VOL: f64 = 0.5051;
const INTEREST_RATE: f64 = 0.0150;
const DIV_YIELD: f64 = 0.0210;
const DAYS_PER_YEAR: f64 = 365.0;
const TIME_TO_EXPIRY: f64 = 23.0 / DAYS_PER_YEAR;
const E_GAMMA: f64 = 0.0243;
#[test]
fn | () {
let gamma = gamma(UNDERLYING,
STRIKE,
TIME_TO_EXPIRY,
INTEREST_RATE,
DIV_YIELD,
VOL);
let abs = (gamma - E_GAMMA).abs();
assert!(abs < 0.001);
}
} | test_gamma | identifier_name |
second.rs | // Module containing functions for calculating second order greeks
use std::f64::consts::E; |
use common::*;
/// Calculates the Gamma for an option
///
/// Gamma measures the rate of change in the delta with respect to the change in the underlying price.
///
/// # Arguments
/// * `s0` - The underlying price of the option
/// * `x` - The strike price of the option
/// * `t` - time to expiration as a percentage of the year
/// * `r` - continuously compounded risk-free interest rate
/// * `q` - continuously compounded divident yield
/// * `sigma` - volatility
pub fn gamma(s0: f64, x: f64, t: f64, r: f64, q: f64, sigma: f64) -> f64 {
let d1 = d1(s0, x, t, r, q, sigma);
return gamma_d1(s0, t, q, sigma, d1);
}
pub fn gamma_d1(s0: f64, t: f64, q: f64, sigma: f64, d1: f64) -> f64 {
let arg1 = E.powf(-(q * t)) / (s0 * sigma * (t.sqrt()));
let arg2 = one_over_sqrt_pi();
let arg3 = E.powf((-d1).powf(2.0)) / 2.0;
return arg1 * arg2 * arg3;
}
#[cfg(test)]
mod tests {
use greeks::*;
const UNDERLYING: f64 = 64.68;
const STRIKE: f64 = 65.00;
const VOL: f64 = 0.5051;
const INTEREST_RATE: f64 = 0.0150;
const DIV_YIELD: f64 = 0.0210;
const DAYS_PER_YEAR: f64 = 365.0;
const TIME_TO_EXPIRY: f64 = 23.0 / DAYS_PER_YEAR;
const E_GAMMA: f64 = 0.0243;
#[test]
fn test_gamma() {
let gamma = gamma(UNDERLYING,
STRIKE,
TIME_TO_EXPIRY,
INTEREST_RATE,
DIV_YIELD,
VOL);
let abs = (gamma - E_GAMMA).abs();
assert!(abs < 0.001);
}
} | random_line_split |
|
second.rs | // Module containing functions for calculating second order greeks
use std::f64::consts::E;
use common::*;
/// Calculates the Gamma for an option
///
/// Gamma measures the rate of change in the delta with respect to the change in the underlying price.
///
/// # Arguments
/// * `s0` - The underlying price of the option
/// * `x` - The strike price of the option
/// * `t` - time to expiration as a percentage of the year
/// * `r` - continuously compounded risk-free interest rate
/// * `q` - continuously compounded divident yield
/// * `sigma` - volatility
pub fn gamma(s0: f64, x: f64, t: f64, r: f64, q: f64, sigma: f64) -> f64 {
let d1 = d1(s0, x, t, r, q, sigma);
return gamma_d1(s0, t, q, sigma, d1);
}
pub fn gamma_d1(s0: f64, t: f64, q: f64, sigma: f64, d1: f64) -> f64 |
#[cfg(test)]
mod tests {
use greeks::*;
const UNDERLYING: f64 = 64.68;
const STRIKE: f64 = 65.00;
const VOL: f64 = 0.5051;
const INTEREST_RATE: f64 = 0.0150;
const DIV_YIELD: f64 = 0.0210;
const DAYS_PER_YEAR: f64 = 365.0;
const TIME_TO_EXPIRY: f64 = 23.0 / DAYS_PER_YEAR;
const E_GAMMA: f64 = 0.0243;
#[test]
fn test_gamma() {
let gamma = gamma(UNDERLYING,
STRIKE,
TIME_TO_EXPIRY,
INTEREST_RATE,
DIV_YIELD,
VOL);
let abs = (gamma - E_GAMMA).abs();
assert!(abs < 0.001);
}
} | {
let arg1 = E.powf(-(q * t)) / (s0 * sigma * (t.sqrt()));
let arg2 = one_over_sqrt_pi();
let arg3 = E.powf((-d1).powf(2.0)) / 2.0;
return arg1 * arg2 * arg3;
} | identifier_body |
state.rs | use std::fmt::{Debug, Formatter, Result};
use std::clone::Clone;
pub enum State {
Unknown,
Unsupported,
Unauthorized,
PoweredOff,
PoweredOn,
}
impl State {
fn id(&self) -> usize {
match *self {
State::Unknown => 1,
State::Unsupported => 3,
State::Unauthorized => 4,
State::PoweredOff => 5,
State::PoweredOn => 6,
}
}
}
impl PartialEq for State {
fn eq(&self, other: &State) -> bool |
}
impl Debug for State {
fn fmt(&self, f: &mut Formatter) -> Result {
write!(f, "State::{}", match *self {
State::Unknown => "Unknown",
State::Unsupported => "Unsupported",
State::Unauthorized => "Unauthorized",
State::PoweredOff => "PoweredOff",
State::PoweredOn => "PoweredOn",
})
}
}
impl Clone for State {
fn clone(&self) -> State {
match *self {
State::Unknown => State::Unknown,
State::Unsupported => State::Unsupported,
State::Unauthorized => State::Unauthorized,
State::PoweredOff => State::PoweredOff,
State::PoweredOn => State::PoweredOn,
}
}
}
| {
self.id() == other.id()
} | identifier_body |
state.rs | use std::fmt::{Debug, Formatter, Result};
use std::clone::Clone;
pub enum State {
Unknown,
Unsupported,
Unauthorized,
PoweredOff,
PoweredOn,
}
impl State {
fn id(&self) -> usize {
match *self {
State::Unknown => 1,
State::Unsupported => 3,
State::Unauthorized => 4,
State::PoweredOff => 5,
State::PoweredOn => 6,
}
}
}
impl PartialEq for State {
fn eq(&self, other: &State) -> bool {
self.id() == other.id()
}
}
impl Debug for State {
fn | (&self, f: &mut Formatter) -> Result {
write!(f, "State::{}", match *self {
State::Unknown => "Unknown",
State::Unsupported => "Unsupported",
State::Unauthorized => "Unauthorized",
State::PoweredOff => "PoweredOff",
State::PoweredOn => "PoweredOn",
})
}
}
impl Clone for State {
fn clone(&self) -> State {
match *self {
State::Unknown => State::Unknown,
State::Unsupported => State::Unsupported,
State::Unauthorized => State::Unauthorized,
State::PoweredOff => State::PoweredOff,
State::PoweredOn => State::PoweredOn,
}
}
}
| fmt | identifier_name |
state.rs | use std::fmt::{Debug, Formatter, Result};
use std::clone::Clone;
pub enum State {
Unknown,
Unsupported,
Unauthorized,
PoweredOff,
PoweredOn,
}
impl State {
fn id(&self) -> usize {
match *self {
State::Unknown => 1,
State::Unsupported => 3,
State::Unauthorized => 4,
State::PoweredOff => 5,
State::PoweredOn => 6,
} | }
impl PartialEq for State {
fn eq(&self, other: &State) -> bool {
self.id() == other.id()
}
}
impl Debug for State {
fn fmt(&self, f: &mut Formatter) -> Result {
write!(f, "State::{}", match *self {
State::Unknown => "Unknown",
State::Unsupported => "Unsupported",
State::Unauthorized => "Unauthorized",
State::PoweredOff => "PoweredOff",
State::PoweredOn => "PoweredOn",
})
}
}
impl Clone for State {
fn clone(&self) -> State {
match *self {
State::Unknown => State::Unknown,
State::Unsupported => State::Unsupported,
State::Unauthorized => State::Unauthorized,
State::PoweredOff => State::PoweredOff,
State::PoweredOn => State::PoweredOn,
}
}
} | } | random_line_split |
build.rs | use std::{
env,
fs::File,
io::{BufRead, BufReader, Write},
path::Path,
};
use quote::ToTokens;
use syn::{parse_quote, visit::Visit, visit_mut::VisitMut};
struct FilterSwigAttrs;
impl VisitMut for FilterSwigAttrs {
fn visit_attribute_mut(&mut self, i: &mut syn::Attribute) {
if i.path
.clone()
.into_token_stream()
.to_string()
.starts_with("swig_")
{
*i = parse_quote! { #[doc = "swig_ replace"] };
}
}
}
mod file_cache {
include!("src/file_cache.rs");
}
mod jni_find_cache {
include!("src/java_jni/find_cache.rs");
}
fn main() {
let out_dir = env::var("OUT_DIR").unwrap();
for include_path in &[
Path::new("src/java_jni/jni-include.rs"),
Path::new("src/cpp/cpp-include.rs"),
] {
let src_cnt_tail = std::fs::read_to_string(include_path)
.unwrap_or_else(|err| panic!("Error during read {}: {}", include_path.display(), err));
let mut src_cnt = r#"
macro_rules! foreign_typemap {
($($tree:tt)*) => {};
}
"#
.to_string();
src_cnt.push_str(&src_cnt_tail);
let mut file = syn::parse_file(&src_cnt)
.unwrap_or_else(|err| panic!("Error during parse {}: {}", include_path.display(), err));
let mut filter_swig_attrs = FilterSwigAttrs;
filter_swig_attrs.visit_file_mut(&mut file);
let mut jni_cache_macro_cache = jni_find_cache::JniCacheMacroCalls::default();
let mut visitor = jni_find_cache::JniCacheMacroCallsVisitor {
inner: &mut jni_cache_macro_cache,
errors: vec![],
};
visitor.visit_file(&file);
if!visitor.errors.is_empty() |
let mut jni_global_vars = jni_cache_macro_cache.global_vars();
file.items.append(&mut jni_global_vars);
let out_path = Path::new(&out_dir).join(include_path.file_name().expect("No file name"));
let mut cache =
file_cache::FileWriteCache::new(&out_path, &mut file_cache::NoNeedFsOpsRegistration);
let write_err_msg = format!("Error during write to file {}", out_path.display());
write!(&mut cache, "{}", file.into_token_stream().to_string()).expect(&write_err_msg);
cache.update_file_if_necessary().expect(&write_err_msg);
println!("cargo:rerun-if-changed={}", include_path.display());
}
println!("cargo:rerun-if-changed=tests/test_includes_syntax.rs");
let exp_tests_list_path = Path::new("tests").join("expectations").join("tests.list");
let expectation_tests = File::open(&exp_tests_list_path)
.unwrap_or_else(|err| panic!("Can not open {}: {}", exp_tests_list_path.display(), err));
let expectation_tests = BufReader::new(&expectation_tests);
let exp_code_path = Path::new(&out_dir).join("test_expectations.rs");
let mut exp_code =
file_cache::FileWriteCache::new(&exp_code_path, &mut file_cache::NoNeedFsOpsRegistration);
for name in expectation_tests.lines() {
let name = name.unwrap_or_else(|err| {
panic!("Can not read {}: {}", exp_tests_list_path.display(), err)
});
write!(
&mut exp_code,
r##"
#[test]
fn test_expectation_{test_name}() {{
let _ = env_logger::try_init();
let test_case = Path::new("tests").join("expectations").join("{test_name}.rs");
let base_name = test_case.file_stem().expect("name without extenstion");
let test_name = base_name.to_string_lossy();
let mut test_something = false;
for lang in &[ForeignLang::Cpp, ForeignLang::Java] {{
if check_expectation(&test_name, &test_case, *lang) {{
test_something = true;
}}
}}
assert!(test_something, "empty test");
}}
"##,
test_name = name,
)
.unwrap();
}
exp_code
.update_file_if_necessary()
.unwrap_or_else(|err| panic!("Can not write to {}: {}", exp_code_path.display(), err));
println!("cargo:rerun-if-changed={}", exp_tests_list_path.display());
}
| {
panic!("jni cache macros visiting failed: {}", visitor.errors[0]);
} | conditional_block |
build.rs | use std::{
env,
fs::File,
io::{BufRead, BufReader, Write},
path::Path,
};
use quote::ToTokens;
use syn::{parse_quote, visit::Visit, visit_mut::VisitMut};
struct FilterSwigAttrs;
impl VisitMut for FilterSwigAttrs {
fn visit_attribute_mut(&mut self, i: &mut syn::Attribute) {
if i.path
.clone()
.into_token_stream()
.to_string()
.starts_with("swig_")
{
*i = parse_quote! { #[doc = "swig_ replace"] };
}
}
}
mod file_cache {
include!("src/file_cache.rs");
}
mod jni_find_cache {
include!("src/java_jni/find_cache.rs");
}
fn main() {
let out_dir = env::var("OUT_DIR").unwrap();
for include_path in &[
Path::new("src/java_jni/jni-include.rs"),
Path::new("src/cpp/cpp-include.rs"),
] {
let src_cnt_tail = std::fs::read_to_string(include_path)
.unwrap_or_else(|err| panic!("Error during read {}: {}", include_path.display(), err));
let mut src_cnt = r#"
macro_rules! foreign_typemap {
($($tree:tt)*) => {};
}
"#
.to_string();
src_cnt.push_str(&src_cnt_tail);
let mut file = syn::parse_file(&src_cnt)
.unwrap_or_else(|err| panic!("Error during parse {}: {}", include_path.display(), err));
let mut filter_swig_attrs = FilterSwigAttrs;
filter_swig_attrs.visit_file_mut(&mut file);
let mut jni_cache_macro_cache = jni_find_cache::JniCacheMacroCalls::default();
let mut visitor = jni_find_cache::JniCacheMacroCallsVisitor {
inner: &mut jni_cache_macro_cache,
errors: vec![],
};
visitor.visit_file(&file);
if!visitor.errors.is_empty() {
panic!("jni cache macros visiting failed: {}", visitor.errors[0]);
}
let mut jni_global_vars = jni_cache_macro_cache.global_vars();
file.items.append(&mut jni_global_vars);
let out_path = Path::new(&out_dir).join(include_path.file_name().expect("No file name"));
let mut cache =
file_cache::FileWriteCache::new(&out_path, &mut file_cache::NoNeedFsOpsRegistration);
let write_err_msg = format!("Error during write to file {}", out_path.display());
write!(&mut cache, "{}", file.into_token_stream().to_string()).expect(&write_err_msg);
cache.update_file_if_necessary().expect(&write_err_msg);
println!("cargo:rerun-if-changed={}", include_path.display());
}
println!("cargo:rerun-if-changed=tests/test_includes_syntax.rs");
let exp_tests_list_path = Path::new("tests").join("expectations").join("tests.list");
let expectation_tests = File::open(&exp_tests_list_path)
.unwrap_or_else(|err| panic!("Can not open {}: {}", exp_tests_list_path.display(), err));
let expectation_tests = BufReader::new(&expectation_tests);
let exp_code_path = Path::new(&out_dir).join("test_expectations.rs");
let mut exp_code =
file_cache::FileWriteCache::new(&exp_code_path, &mut file_cache::NoNeedFsOpsRegistration);
for name in expectation_tests.lines() {
let name = name.unwrap_or_else(|err| {
panic!("Can not read {}: {}", exp_tests_list_path.display(), err)
});
write!(
&mut exp_code,
r##"
#[test]
fn test_expectation_{test_name}() {{
let _ = env_logger::try_init();
let test_case = Path::new("tests").join("expectations").join("{test_name}.rs");
let base_name = test_case.file_stem().expect("name without extenstion");
let test_name = base_name.to_string_lossy();
let mut test_something = false;
for lang in &[ForeignLang::Cpp, ForeignLang::Java] {{
if check_expectation(&test_name, &test_case, *lang) {{
test_something = true;
}}
}}
assert!(test_something, "empty test");
}}
"##,
test_name = name,
) | .unwrap();
}
exp_code
.update_file_if_necessary()
.unwrap_or_else(|err| panic!("Can not write to {}: {}", exp_code_path.display(), err));
println!("cargo:rerun-if-changed={}", exp_tests_list_path.display());
} | random_line_split |
|
build.rs | use std::{
env,
fs::File,
io::{BufRead, BufReader, Write},
path::Path,
};
use quote::ToTokens;
use syn::{parse_quote, visit::Visit, visit_mut::VisitMut};
struct FilterSwigAttrs;
impl VisitMut for FilterSwigAttrs {
fn visit_attribute_mut(&mut self, i: &mut syn::Attribute) {
if i.path
.clone()
.into_token_stream()
.to_string()
.starts_with("swig_")
{
*i = parse_quote! { #[doc = "swig_ replace"] };
}
}
}
mod file_cache {
include!("src/file_cache.rs");
}
mod jni_find_cache {
include!("src/java_jni/find_cache.rs");
}
fn | () {
let out_dir = env::var("OUT_DIR").unwrap();
for include_path in &[
Path::new("src/java_jni/jni-include.rs"),
Path::new("src/cpp/cpp-include.rs"),
] {
let src_cnt_tail = std::fs::read_to_string(include_path)
.unwrap_or_else(|err| panic!("Error during read {}: {}", include_path.display(), err));
let mut src_cnt = r#"
macro_rules! foreign_typemap {
($($tree:tt)*) => {};
}
"#
.to_string();
src_cnt.push_str(&src_cnt_tail);
let mut file = syn::parse_file(&src_cnt)
.unwrap_or_else(|err| panic!("Error during parse {}: {}", include_path.display(), err));
let mut filter_swig_attrs = FilterSwigAttrs;
filter_swig_attrs.visit_file_mut(&mut file);
let mut jni_cache_macro_cache = jni_find_cache::JniCacheMacroCalls::default();
let mut visitor = jni_find_cache::JniCacheMacroCallsVisitor {
inner: &mut jni_cache_macro_cache,
errors: vec![],
};
visitor.visit_file(&file);
if!visitor.errors.is_empty() {
panic!("jni cache macros visiting failed: {}", visitor.errors[0]);
}
let mut jni_global_vars = jni_cache_macro_cache.global_vars();
file.items.append(&mut jni_global_vars);
let out_path = Path::new(&out_dir).join(include_path.file_name().expect("No file name"));
let mut cache =
file_cache::FileWriteCache::new(&out_path, &mut file_cache::NoNeedFsOpsRegistration);
let write_err_msg = format!("Error during write to file {}", out_path.display());
write!(&mut cache, "{}", file.into_token_stream().to_string()).expect(&write_err_msg);
cache.update_file_if_necessary().expect(&write_err_msg);
println!("cargo:rerun-if-changed={}", include_path.display());
}
println!("cargo:rerun-if-changed=tests/test_includes_syntax.rs");
let exp_tests_list_path = Path::new("tests").join("expectations").join("tests.list");
let expectation_tests = File::open(&exp_tests_list_path)
.unwrap_or_else(|err| panic!("Can not open {}: {}", exp_tests_list_path.display(), err));
let expectation_tests = BufReader::new(&expectation_tests);
let exp_code_path = Path::new(&out_dir).join("test_expectations.rs");
let mut exp_code =
file_cache::FileWriteCache::new(&exp_code_path, &mut file_cache::NoNeedFsOpsRegistration);
for name in expectation_tests.lines() {
let name = name.unwrap_or_else(|err| {
panic!("Can not read {}: {}", exp_tests_list_path.display(), err)
});
write!(
&mut exp_code,
r##"
#[test]
fn test_expectation_{test_name}() {{
let _ = env_logger::try_init();
let test_case = Path::new("tests").join("expectations").join("{test_name}.rs");
let base_name = test_case.file_stem().expect("name without extenstion");
let test_name = base_name.to_string_lossy();
let mut test_something = false;
for lang in &[ForeignLang::Cpp, ForeignLang::Java] {{
if check_expectation(&test_name, &test_case, *lang) {{
test_something = true;
}}
}}
assert!(test_something, "empty test");
}}
"##,
test_name = name,
)
.unwrap();
}
exp_code
.update_file_if_necessary()
.unwrap_or_else(|err| panic!("Can not write to {}: {}", exp_code_path.display(), err));
println!("cargo:rerun-if-changed={}", exp_tests_list_path.display());
}
| main | identifier_name |
build.rs | use std::{
env,
fs::File,
io::{BufRead, BufReader, Write},
path::Path,
};
use quote::ToTokens;
use syn::{parse_quote, visit::Visit, visit_mut::VisitMut};
struct FilterSwigAttrs;
impl VisitMut for FilterSwigAttrs {
fn visit_attribute_mut(&mut self, i: &mut syn::Attribute) |
}
mod file_cache {
include!("src/file_cache.rs");
}
mod jni_find_cache {
include!("src/java_jni/find_cache.rs");
}
fn main() {
let out_dir = env::var("OUT_DIR").unwrap();
for include_path in &[
Path::new("src/java_jni/jni-include.rs"),
Path::new("src/cpp/cpp-include.rs"),
] {
let src_cnt_tail = std::fs::read_to_string(include_path)
.unwrap_or_else(|err| panic!("Error during read {}: {}", include_path.display(), err));
let mut src_cnt = r#"
macro_rules! foreign_typemap {
($($tree:tt)*) => {};
}
"#
.to_string();
src_cnt.push_str(&src_cnt_tail);
let mut file = syn::parse_file(&src_cnt)
.unwrap_or_else(|err| panic!("Error during parse {}: {}", include_path.display(), err));
let mut filter_swig_attrs = FilterSwigAttrs;
filter_swig_attrs.visit_file_mut(&mut file);
let mut jni_cache_macro_cache = jni_find_cache::JniCacheMacroCalls::default();
let mut visitor = jni_find_cache::JniCacheMacroCallsVisitor {
inner: &mut jni_cache_macro_cache,
errors: vec![],
};
visitor.visit_file(&file);
if!visitor.errors.is_empty() {
panic!("jni cache macros visiting failed: {}", visitor.errors[0]);
}
let mut jni_global_vars = jni_cache_macro_cache.global_vars();
file.items.append(&mut jni_global_vars);
let out_path = Path::new(&out_dir).join(include_path.file_name().expect("No file name"));
let mut cache =
file_cache::FileWriteCache::new(&out_path, &mut file_cache::NoNeedFsOpsRegistration);
let write_err_msg = format!("Error during write to file {}", out_path.display());
write!(&mut cache, "{}", file.into_token_stream().to_string()).expect(&write_err_msg);
cache.update_file_if_necessary().expect(&write_err_msg);
println!("cargo:rerun-if-changed={}", include_path.display());
}
println!("cargo:rerun-if-changed=tests/test_includes_syntax.rs");
let exp_tests_list_path = Path::new("tests").join("expectations").join("tests.list");
let expectation_tests = File::open(&exp_tests_list_path)
.unwrap_or_else(|err| panic!("Can not open {}: {}", exp_tests_list_path.display(), err));
let expectation_tests = BufReader::new(&expectation_tests);
let exp_code_path = Path::new(&out_dir).join("test_expectations.rs");
let mut exp_code =
file_cache::FileWriteCache::new(&exp_code_path, &mut file_cache::NoNeedFsOpsRegistration);
for name in expectation_tests.lines() {
let name = name.unwrap_or_else(|err| {
panic!("Can not read {}: {}", exp_tests_list_path.display(), err)
});
write!(
&mut exp_code,
r##"
#[test]
fn test_expectation_{test_name}() {{
let _ = env_logger::try_init();
let test_case = Path::new("tests").join("expectations").join("{test_name}.rs");
let base_name = test_case.file_stem().expect("name without extenstion");
let test_name = base_name.to_string_lossy();
let mut test_something = false;
for lang in &[ForeignLang::Cpp, ForeignLang::Java] {{
if check_expectation(&test_name, &test_case, *lang) {{
test_something = true;
}}
}}
assert!(test_something, "empty test");
}}
"##,
test_name = name,
)
.unwrap();
}
exp_code
.update_file_if_necessary()
.unwrap_or_else(|err| panic!("Can not write to {}: {}", exp_code_path.display(), err));
println!("cargo:rerun-if-changed={}", exp_tests_list_path.display());
}
| {
if i.path
.clone()
.into_token_stream()
.to_string()
.starts_with("swig_")
{
*i = parse_quote! { #[doc = "swig_ replace"] };
}
} | identifier_body |
common.rs | // Copyright 2012 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
use core::prelude::*;
use syntax::ast;
use syntax::codemap::{span};
use syntax::visit;
use core::hashmap::linear::LinearSet;
use core::str;
use std;
pub fn time<T>(do_it: bool, what: ~str, thunk: &fn() -> T) -> T {
if!do_it { return thunk(); }
let start = std::time::precise_time_s();
let rv = thunk();
let end = std::time::precise_time_s();
io::println(fmt!("time: %3.3f s\t%s", end - start, what));
rv
}
pub fn indent<R>(op: &fn() -> R) -> R {
// Use in conjunction with the log post-processor like `src/etc/indenter`
// to make debug output more readable.
debug!(">>");
let r = op();
debug!("<< (Result = %?)", r);
r
}
pub struct _indenter {
_i: (),
}
impl Drop for _indenter {
fn finalize(&self) { debug!("<<"); }
}
pub fn _indenter(_i: ()) -> _indenter |
pub fn indenter() -> _indenter {
debug!(">>");
_indenter(())
}
pub fn field_expr(f: ast::field) -> @ast::expr { return f.node.expr; }
pub fn field_exprs(fields: ~[ast::field]) -> ~[@ast::expr] {
fields.map(|f| f.node.expr)
}
// Takes a predicate p, returns true iff p is true for any subexpressions
// of b -- skipping any inner loops (loop, while, loop_body)
pub fn loop_query(b: &ast::blk, p: @fn(ast::expr_) -> bool) -> bool {
let rs = @mut false;
let visit_expr: @fn(@ast::expr,
&&flag: @mut bool,
v: visit::vt<@mut bool>) = |e, &&flag, v| {
*flag |= p(e.node);
match e.node {
// Skip inner loops, since a break in the inner loop isn't a
// break inside the outer loop
ast::expr_loop(*) | ast::expr_while(*)
| ast::expr_loop_body(*) => {}
_ => visit::visit_expr(e, flag, v)
}
};
let v = visit::mk_vt(@visit::Visitor {
visit_expr: visit_expr,
.. *visit::default_visitor()});
visit::visit_block(b, rs, v);
return *rs;
}
// Takes a predicate p, returns true iff p is true for any subexpressions
// of b -- skipping any inner loops (loop, while, loop_body)
pub fn block_query(b: &ast::blk, p: @fn(@ast::expr) -> bool) -> bool {
let rs = @mut false;
let visit_expr: @fn(@ast::expr,
&&flag: @mut bool,
v: visit::vt<@mut bool>) = |e, &&flag, v| {
*flag |= p(e);
visit::visit_expr(e, flag, v)
};
let v = visit::mk_vt(@visit::Visitor{
visit_expr: visit_expr,
.. *visit::default_visitor()});
visit::visit_block(b, rs, v);
return *rs;
}
pub fn local_rhs_span(l: @ast::local, def: span) -> span {
match l.node.init {
Some(i) => return i.span,
_ => return def
}
}
pub fn pluralize(n: uint, +s: ~str) -> ~str {
if n == 1 { s }
else { str::concat([s, ~"s"]) }
}
// A set of node IDs (used to keep track of which node IDs are for statements)
pub type stmt_set = @mut LinearSet<ast::node_id>;
//
// Local Variables:
// mode: rust
// fill-column: 78;
// indent-tabs-mode: nil
// c-basic-offset: 4
// buffer-file-coding-system: utf-8-unix
// End:
//
| {
_indenter {
_i: ()
}
} | identifier_body |
common.rs | // Copyright 2012 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
use core::prelude::*;
use syntax::ast;
use syntax::codemap::{span};
use syntax::visit;
use core::hashmap::linear::LinearSet;
use core::str;
use std;
pub fn | <T>(do_it: bool, what: ~str, thunk: &fn() -> T) -> T {
if!do_it { return thunk(); }
let start = std::time::precise_time_s();
let rv = thunk();
let end = std::time::precise_time_s();
io::println(fmt!("time: %3.3f s\t%s", end - start, what));
rv
}
pub fn indent<R>(op: &fn() -> R) -> R {
// Use in conjunction with the log post-processor like `src/etc/indenter`
// to make debug output more readable.
debug!(">>");
let r = op();
debug!("<< (Result = %?)", r);
r
}
pub struct _indenter {
_i: (),
}
impl Drop for _indenter {
fn finalize(&self) { debug!("<<"); }
}
pub fn _indenter(_i: ()) -> _indenter {
_indenter {
_i: ()
}
}
pub fn indenter() -> _indenter {
debug!(">>");
_indenter(())
}
pub fn field_expr(f: ast::field) -> @ast::expr { return f.node.expr; }
pub fn field_exprs(fields: ~[ast::field]) -> ~[@ast::expr] {
fields.map(|f| f.node.expr)
}
// Takes a predicate p, returns true iff p is true for any subexpressions
// of b -- skipping any inner loops (loop, while, loop_body)
pub fn loop_query(b: &ast::blk, p: @fn(ast::expr_) -> bool) -> bool {
let rs = @mut false;
let visit_expr: @fn(@ast::expr,
&&flag: @mut bool,
v: visit::vt<@mut bool>) = |e, &&flag, v| {
*flag |= p(e.node);
match e.node {
// Skip inner loops, since a break in the inner loop isn't a
// break inside the outer loop
ast::expr_loop(*) | ast::expr_while(*)
| ast::expr_loop_body(*) => {}
_ => visit::visit_expr(e, flag, v)
}
};
let v = visit::mk_vt(@visit::Visitor {
visit_expr: visit_expr,
.. *visit::default_visitor()});
visit::visit_block(b, rs, v);
return *rs;
}
// Takes a predicate p, returns true iff p is true for any subexpressions
// of b -- skipping any inner loops (loop, while, loop_body)
pub fn block_query(b: &ast::blk, p: @fn(@ast::expr) -> bool) -> bool {
let rs = @mut false;
let visit_expr: @fn(@ast::expr,
&&flag: @mut bool,
v: visit::vt<@mut bool>) = |e, &&flag, v| {
*flag |= p(e);
visit::visit_expr(e, flag, v)
};
let v = visit::mk_vt(@visit::Visitor{
visit_expr: visit_expr,
.. *visit::default_visitor()});
visit::visit_block(b, rs, v);
return *rs;
}
pub fn local_rhs_span(l: @ast::local, def: span) -> span {
match l.node.init {
Some(i) => return i.span,
_ => return def
}
}
pub fn pluralize(n: uint, +s: ~str) -> ~str {
if n == 1 { s }
else { str::concat([s, ~"s"]) }
}
// A set of node IDs (used to keep track of which node IDs are for statements)
pub type stmt_set = @mut LinearSet<ast::node_id>;
//
// Local Variables:
// mode: rust
// fill-column: 78;
// indent-tabs-mode: nil
// c-basic-offset: 4
// buffer-file-coding-system: utf-8-unix
// End:
//
| time | identifier_name |
common.rs | // Copyright 2012 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
use core::prelude::*;
use syntax::ast;
use syntax::codemap::{span};
use syntax::visit;
use core::hashmap::linear::LinearSet;
use core::str;
use std;
pub fn time<T>(do_it: bool, what: ~str, thunk: &fn() -> T) -> T {
if!do_it { return thunk(); }
let start = std::time::precise_time_s();
let rv = thunk();
let end = std::time::precise_time_s();
io::println(fmt!("time: %3.3f s\t%s", end - start, what));
rv
} | debug!(">>");
let r = op();
debug!("<< (Result = %?)", r);
r
}
pub struct _indenter {
_i: (),
}
impl Drop for _indenter {
fn finalize(&self) { debug!("<<"); }
}
pub fn _indenter(_i: ()) -> _indenter {
_indenter {
_i: ()
}
}
pub fn indenter() -> _indenter {
debug!(">>");
_indenter(())
}
pub fn field_expr(f: ast::field) -> @ast::expr { return f.node.expr; }
pub fn field_exprs(fields: ~[ast::field]) -> ~[@ast::expr] {
fields.map(|f| f.node.expr)
}
// Takes a predicate p, returns true iff p is true for any subexpressions
// of b -- skipping any inner loops (loop, while, loop_body)
pub fn loop_query(b: &ast::blk, p: @fn(ast::expr_) -> bool) -> bool {
let rs = @mut false;
let visit_expr: @fn(@ast::expr,
&&flag: @mut bool,
v: visit::vt<@mut bool>) = |e, &&flag, v| {
*flag |= p(e.node);
match e.node {
// Skip inner loops, since a break in the inner loop isn't a
// break inside the outer loop
ast::expr_loop(*) | ast::expr_while(*)
| ast::expr_loop_body(*) => {}
_ => visit::visit_expr(e, flag, v)
}
};
let v = visit::mk_vt(@visit::Visitor {
visit_expr: visit_expr,
.. *visit::default_visitor()});
visit::visit_block(b, rs, v);
return *rs;
}
// Takes a predicate p, returns true iff p is true for any subexpressions
// of b -- skipping any inner loops (loop, while, loop_body)
pub fn block_query(b: &ast::blk, p: @fn(@ast::expr) -> bool) -> bool {
let rs = @mut false;
let visit_expr: @fn(@ast::expr,
&&flag: @mut bool,
v: visit::vt<@mut bool>) = |e, &&flag, v| {
*flag |= p(e);
visit::visit_expr(e, flag, v)
};
let v = visit::mk_vt(@visit::Visitor{
visit_expr: visit_expr,
.. *visit::default_visitor()});
visit::visit_block(b, rs, v);
return *rs;
}
pub fn local_rhs_span(l: @ast::local, def: span) -> span {
match l.node.init {
Some(i) => return i.span,
_ => return def
}
}
pub fn pluralize(n: uint, +s: ~str) -> ~str {
if n == 1 { s }
else { str::concat([s, ~"s"]) }
}
// A set of node IDs (used to keep track of which node IDs are for statements)
pub type stmt_set = @mut LinearSet<ast::node_id>;
//
// Local Variables:
// mode: rust
// fill-column: 78;
// indent-tabs-mode: nil
// c-basic-offset: 4
// buffer-file-coding-system: utf-8-unix
// End:
// |
pub fn indent<R>(op: &fn() -> R) -> R {
// Use in conjunction with the log post-processor like `src/etc/indenter`
// to make debug output more readable. | random_line_split |
vr_event.rs | use {VRDisplayData, VRGamepadData, VRGamepadState};
#[derive(Debug, Clone)]
#[cfg_attr(feature = "serde-serialization", derive(Deserialize, Serialize))]
pub enum VREvent {
Display(VRDisplayEvent),
Gamepad(VRGamepadEvent),
}
#[derive(Debug, Clone, Copy)]
#[cfg_attr(feature = "serde-serialization", derive(Deserialize, Serialize))]
pub enum VRDisplayEventReason {
Navigation,
/// The VRDisplay has detected that the user has put it on.
Mounted,
/// The VRDisplay has detected that the user has taken it off.
Unmounted
}
#[derive(Debug, Clone)]
#[cfg_attr(feature = "serde-serialization", derive(Deserialize, Serialize))]
pub enum VRDisplayEvent {
/// Indicates that a VRDisplay has been connected.
Connect(VRDisplayData),
/// Indicates that a VRDisplay has been disconnected.
/// param: display_id
Disconnect(u32),
/// Indicates that something has occured which suggests the VRDisplay should be presented to
Activate(VRDisplayData, VRDisplayEventReason),
/// Indicates that something has occured which suggests the VRDisplay should exit presentation
Deactivate(VRDisplayData, VRDisplayEventReason),
/// Indicates that some of the VRDisplay's data has changed (eye parameters, tracking data, chaperone, ipd, etc.)
Change(VRDisplayData),
/// Indicates that presentation to the display by the page is paused by the user agent, OS, or VR hardware
Blur(VRDisplayData),
/// Indicates that presentation to the display by the page has resumed after being blurred.
Focus(VRDisplayData),
/// Indicates that a VRDisplay has begun or ended VR presentation
PresentChange(VRDisplayData, bool),
/// Indicates that VRDisplay presentation loop must be paused (i.e Android app goes to background)
Pause(u32),
/// Indicates that VRDisplay presentation loop must be resumed (i.e Android app goes to foreground)
Resume(u32),
/// Indicates that user has exited VRDisplay presentation (i.e. User clicked back key on android)
Exit(u32)
}
impl Into<VREvent> for VRDisplayEvent {
fn | (self) -> VREvent {
VREvent::Display(self)
}
}
#[derive(Debug, Clone)]
#[cfg_attr(feature = "serde-serialization", derive(Deserialize, Serialize))]
pub enum VRGamepadEvent {
/// Indicates that a VRGamepad has been connected.
/// params: name, displa_id, state
Connect(VRGamepadData, VRGamepadState),
/// Indicates that a VRGamepad has been disconnected.
/// param: gamepad_id
Disconnect(u32)
}
impl Into<VREvent> for VRGamepadEvent {
fn into(self) -> VREvent {
VREvent::Gamepad(self)
}
}
| into | identifier_name |
vr_event.rs | use {VRDisplayData, VRGamepadData, VRGamepadState};
#[derive(Debug, Clone)]
#[cfg_attr(feature = "serde-serialization", derive(Deserialize, Serialize))]
pub enum VREvent {
Display(VRDisplayEvent),
Gamepad(VRGamepadEvent),
}
#[derive(Debug, Clone, Copy)]
#[cfg_attr(feature = "serde-serialization", derive(Deserialize, Serialize))]
pub enum VRDisplayEventReason {
Navigation,
/// The VRDisplay has detected that the user has put it on.
Mounted,
/// The VRDisplay has detected that the user has taken it off.
Unmounted
}
#[derive(Debug, Clone)]
#[cfg_attr(feature = "serde-serialization", derive(Deserialize, Serialize))]
pub enum VRDisplayEvent {
/// Indicates that a VRDisplay has been connected.
Connect(VRDisplayData),
/// Indicates that a VRDisplay has been disconnected.
/// param: display_id
Disconnect(u32),
/// Indicates that something has occured which suggests the VRDisplay should be presented to
Activate(VRDisplayData, VRDisplayEventReason),
/// Indicates that something has occured which suggests the VRDisplay should exit presentation
Deactivate(VRDisplayData, VRDisplayEventReason),
/// Indicates that some of the VRDisplay's data has changed (eye parameters, tracking data, chaperone, ipd, etc.)
Change(VRDisplayData),
/// Indicates that presentation to the display by the page is paused by the user agent, OS, or VR hardware
Blur(VRDisplayData),
/// Indicates that presentation to the display by the page has resumed after being blurred.
Focus(VRDisplayData),
/// Indicates that a VRDisplay has begun or ended VR presentation | Pause(u32),
/// Indicates that VRDisplay presentation loop must be resumed (i.e Android app goes to foreground)
Resume(u32),
/// Indicates that user has exited VRDisplay presentation (i.e. User clicked back key on android)
Exit(u32)
}
impl Into<VREvent> for VRDisplayEvent {
fn into(self) -> VREvent {
VREvent::Display(self)
}
}
#[derive(Debug, Clone)]
#[cfg_attr(feature = "serde-serialization", derive(Deserialize, Serialize))]
pub enum VRGamepadEvent {
/// Indicates that a VRGamepad has been connected.
/// params: name, displa_id, state
Connect(VRGamepadData, VRGamepadState),
/// Indicates that a VRGamepad has been disconnected.
/// param: gamepad_id
Disconnect(u32)
}
impl Into<VREvent> for VRGamepadEvent {
fn into(self) -> VREvent {
VREvent::Gamepad(self)
}
} | PresentChange(VRDisplayData, bool),
/// Indicates that VRDisplay presentation loop must be paused (i.e Android app goes to background) | random_line_split |
finally.rs | // Copyright 2013 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
/*!
The Finally trait provides a method, `finally` on
stack closures that emulates Java-style try/finally blocks.
Using the `finally` method is sometimes convenient, but the type rules
prohibit any shared, mutable state between the "try" case and the
"finally" case. For advanced cases, the `try_finally` function can
also be used. See that function for more details.
# Example
```
use std::unstable::finally::Finally;
(|| {
//...
}).finally(|| {
// this code is always run
})
```
*/
#![experimental]
use ops::Drop;
/// A trait for executing a destructor unconditionally after a block of code,
/// regardless of whether the blocked fails.
pub trait Finally<T> {
/// Executes this object, unconditionally running `dtor` after this block of
/// code has run.
fn finally(&mut self, dtor: ||) -> T;
}
impl<'a,T> Finally<T> for ||: 'a -> T {
fn finally(&mut self, dtor: ||) -> T {
try_finally(&mut (), self,
|_, f| (*f)(),
|_| dtor())
}
}
impl<T> Finally<T> for fn() -> T {
fn finally(&mut self, dtor: ||) -> T {
try_finally(&mut (), (),
|_, _| (*self)(),
|_| dtor())
}
}
/**
* The most general form of the `finally` functions. The function
* `try_fn` will be invoked first; whether or not it fails, the
* function `finally_fn` will be invoked next. The two parameters
* `mutate` and `drop` are used to thread state through the two
* closures. `mutate` is used for any shared, mutable state that both
* closures require access to; `drop` is used for any state that the
* `try_fn` requires ownership of.
*
* **WARNING:** While shared, mutable state between the try and finally
* function is often necessary, one must be very careful; the `try`
* function could have failed at any point, so the values of the shared
* state may be inconsistent.
*
* # Example
*
* ```
* use std::unstable::finally::try_finally;
*
* struct State<'a> { buffer: &'a mut [u8], len: uint }
* # let mut buf = [];
* let mut state = State { buffer: buf, len: 0 };
* try_finally(
* &mut state, (),
* |state, ()| {
* // use state.buffer, state.len
* },
* |state| {
* // use state.buffer, state.len to cleanup
* })
* ```
*/
pub fn try_finally<T,U,R>(mutate: &mut T,
drop: U,
try_fn: |&mut T, U| -> R,
finally_fn: |&mut T|)
-> R {
let f = Finallyalizer {
mutate: mutate,
dtor: finally_fn,
};
try_fn(&mut *f.mutate, drop)
}
struct Finallyalizer<'a,A> {
mutate: &'a mut A,
dtor: |&mut A|: 'a
}
#[unsafe_destructor]
impl<'a,A> Drop for Finallyalizer<'a,A> {
#[inline]
fn drop(&mut self) |
}
#[cfg(test)]
mod test {
use super::{try_finally, Finally};
use realstd::task::failing;
#[test]
fn test_success() {
let mut i = 0;
try_finally(
&mut i, (),
|i, ()| {
*i = 10;
},
|i| {
assert!(!failing());
assert_eq!(*i, 10);
*i = 20;
});
assert_eq!(i, 20);
}
#[test]
#[should_fail]
fn test_fail() {
let mut i = 0;
try_finally(
&mut i, (),
|i, ()| {
*i = 10;
fail!();
},
|i| {
assert!(failing());
assert_eq!(*i, 10);
})
}
#[test]
fn test_retval() {
let mut closure: || -> int = || 10;
let i = closure.finally(|| { });
assert_eq!(i, 10);
}
#[test]
fn test_compact() {
fn do_some_fallible_work() {}
fn but_always_run_this_function() { }
let mut f = do_some_fallible_work;
f.finally(but_always_run_this_function);
}
}
| {
(self.dtor)(self.mutate);
} | identifier_body |
finally.rs | // Copyright 2013 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
/*! | "finally" case. For advanced cases, the `try_finally` function can
also be used. See that function for more details.
# Example
```
use std::unstable::finally::Finally;
(|| {
//...
}).finally(|| {
// this code is always run
})
```
*/
#![experimental]
use ops::Drop;
/// A trait for executing a destructor unconditionally after a block of code,
/// regardless of whether the blocked fails.
pub trait Finally<T> {
/// Executes this object, unconditionally running `dtor` after this block of
/// code has run.
fn finally(&mut self, dtor: ||) -> T;
}
impl<'a,T> Finally<T> for ||: 'a -> T {
fn finally(&mut self, dtor: ||) -> T {
try_finally(&mut (), self,
|_, f| (*f)(),
|_| dtor())
}
}
impl<T> Finally<T> for fn() -> T {
fn finally(&mut self, dtor: ||) -> T {
try_finally(&mut (), (),
|_, _| (*self)(),
|_| dtor())
}
}
/**
* The most general form of the `finally` functions. The function
* `try_fn` will be invoked first; whether or not it fails, the
* function `finally_fn` will be invoked next. The two parameters
* `mutate` and `drop` are used to thread state through the two
* closures. `mutate` is used for any shared, mutable state that both
* closures require access to; `drop` is used for any state that the
* `try_fn` requires ownership of.
*
* **WARNING:** While shared, mutable state between the try and finally
* function is often necessary, one must be very careful; the `try`
* function could have failed at any point, so the values of the shared
* state may be inconsistent.
*
* # Example
*
* ```
* use std::unstable::finally::try_finally;
*
* struct State<'a> { buffer: &'a mut [u8], len: uint }
* # let mut buf = [];
* let mut state = State { buffer: buf, len: 0 };
* try_finally(
* &mut state, (),
* |state, ()| {
* // use state.buffer, state.len
* },
* |state| {
* // use state.buffer, state.len to cleanup
* })
* ```
*/
pub fn try_finally<T,U,R>(mutate: &mut T,
drop: U,
try_fn: |&mut T, U| -> R,
finally_fn: |&mut T|)
-> R {
let f = Finallyalizer {
mutate: mutate,
dtor: finally_fn,
};
try_fn(&mut *f.mutate, drop)
}
struct Finallyalizer<'a,A> {
mutate: &'a mut A,
dtor: |&mut A|: 'a
}
#[unsafe_destructor]
impl<'a,A> Drop for Finallyalizer<'a,A> {
#[inline]
fn drop(&mut self) {
(self.dtor)(self.mutate);
}
}
#[cfg(test)]
mod test {
use super::{try_finally, Finally};
use realstd::task::failing;
#[test]
fn test_success() {
let mut i = 0;
try_finally(
&mut i, (),
|i, ()| {
*i = 10;
},
|i| {
assert!(!failing());
assert_eq!(*i, 10);
*i = 20;
});
assert_eq!(i, 20);
}
#[test]
#[should_fail]
fn test_fail() {
let mut i = 0;
try_finally(
&mut i, (),
|i, ()| {
*i = 10;
fail!();
},
|i| {
assert!(failing());
assert_eq!(*i, 10);
})
}
#[test]
fn test_retval() {
let mut closure: || -> int = || 10;
let i = closure.finally(|| { });
assert_eq!(i, 10);
}
#[test]
fn test_compact() {
fn do_some_fallible_work() {}
fn but_always_run_this_function() { }
let mut f = do_some_fallible_work;
f.finally(but_always_run_this_function);
}
} | The Finally trait provides a method, `finally` on
stack closures that emulates Java-style try/finally blocks.
Using the `finally` method is sometimes convenient, but the type rules
prohibit any shared, mutable state between the "try" case and the | random_line_split |
finally.rs | // Copyright 2013 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
/*!
The Finally trait provides a method, `finally` on
stack closures that emulates Java-style try/finally blocks.
Using the `finally` method is sometimes convenient, but the type rules
prohibit any shared, mutable state between the "try" case and the
"finally" case. For advanced cases, the `try_finally` function can
also be used. See that function for more details.
# Example
```
use std::unstable::finally::Finally;
(|| {
//...
}).finally(|| {
// this code is always run
})
```
*/
#![experimental]
use ops::Drop;
/// A trait for executing a destructor unconditionally after a block of code,
/// regardless of whether the blocked fails.
pub trait Finally<T> {
/// Executes this object, unconditionally running `dtor` after this block of
/// code has run.
fn finally(&mut self, dtor: ||) -> T;
}
impl<'a,T> Finally<T> for ||: 'a -> T {
fn finally(&mut self, dtor: ||) -> T {
try_finally(&mut (), self,
|_, f| (*f)(),
|_| dtor())
}
}
impl<T> Finally<T> for fn() -> T {
fn finally(&mut self, dtor: ||) -> T {
try_finally(&mut (), (),
|_, _| (*self)(),
|_| dtor())
}
}
/**
* The most general form of the `finally` functions. The function
* `try_fn` will be invoked first; whether or not it fails, the
* function `finally_fn` will be invoked next. The two parameters
* `mutate` and `drop` are used to thread state through the two
* closures. `mutate` is used for any shared, mutable state that both
* closures require access to; `drop` is used for any state that the
* `try_fn` requires ownership of.
*
* **WARNING:** While shared, mutable state between the try and finally
* function is often necessary, one must be very careful; the `try`
* function could have failed at any point, so the values of the shared
* state may be inconsistent.
*
* # Example
*
* ```
* use std::unstable::finally::try_finally;
*
* struct State<'a> { buffer: &'a mut [u8], len: uint }
* # let mut buf = [];
* let mut state = State { buffer: buf, len: 0 };
* try_finally(
* &mut state, (),
* |state, ()| {
* // use state.buffer, state.len
* },
* |state| {
* // use state.buffer, state.len to cleanup
* })
* ```
*/
pub fn try_finally<T,U,R>(mutate: &mut T,
drop: U,
try_fn: |&mut T, U| -> R,
finally_fn: |&mut T|)
-> R {
let f = Finallyalizer {
mutate: mutate,
dtor: finally_fn,
};
try_fn(&mut *f.mutate, drop)
}
struct Finallyalizer<'a,A> {
mutate: &'a mut A,
dtor: |&mut A|: 'a
}
#[unsafe_destructor]
impl<'a,A> Drop for Finallyalizer<'a,A> {
#[inline]
fn drop(&mut self) {
(self.dtor)(self.mutate);
}
}
#[cfg(test)]
mod test {
use super::{try_finally, Finally};
use realstd::task::failing;
#[test]
fn test_success() {
let mut i = 0;
try_finally(
&mut i, (),
|i, ()| {
*i = 10;
},
|i| {
assert!(!failing());
assert_eq!(*i, 10);
*i = 20;
});
assert_eq!(i, 20);
}
#[test]
#[should_fail]
fn test_fail() {
let mut i = 0;
try_finally(
&mut i, (),
|i, ()| {
*i = 10;
fail!();
},
|i| {
assert!(failing());
assert_eq!(*i, 10);
})
}
#[test]
fn test_retval() {
let mut closure: || -> int = || 10;
let i = closure.finally(|| { });
assert_eq!(i, 10);
}
#[test]
fn test_compact() {
fn | () {}
fn but_always_run_this_function() { }
let mut f = do_some_fallible_work;
f.finally(but_always_run_this_function);
}
}
| do_some_fallible_work | identifier_name |
errors.rs | use attaca::marshal::ObjectHash;
| types { Error, ErrorKind, ResultExt, Result; }
links {
Attaca(::attaca::Error, ::attaca::ErrorKind);
}
foreign_links {
Clap(::clap::Error);
Fmt(::std::fmt::Error);
GlobSet(::globset::Error);
Nul(::std::ffi::NulError);
Io(::std::io::Error);
}
errors {
FsckFailure(expected: ObjectHash, actual: ObjectHash) {
description("an object did not hash to the expected value"),
display("an object {} did not hash to the expected value {}", actual, expected)
}
InvalidUsage {
description("invalid usage"),
display("invalid usage"),
}
NotACommit(hash: ObjectHash) {
description("not a commit hash"),
display("{} is not a commit hash", hash),
}
}
} | error_chain! { | random_line_split |
mod.rs | // Copyright 2015-2017 Intecture Developers.
//
// Licensed under the Mozilla Public License 2.0 <LICENSE or
// https://www.tldrlegal.com/l/mpl-2.0>. This file may not be copied,
// modified, or distributed except according to those terms.
//! OS abstractions for `Telemetry`.
mod centos;
mod debian;
mod fedora;
mod freebsd;
mod macos;
mod nixos;
mod ubuntu;
pub use self::centos::Centos;
pub use self::debian::Debian;
pub use self::fedora::Fedora;
pub use self::freebsd::Freebsd;
pub use self::macos::Macos;
pub use self::nixos::Nixos;
pub use self::ubuntu::Ubuntu;
use errors::*;
use futures::Future;
use super::Telemetry;
pub trait TelemetryProvider {
fn available() -> bool where Self: Sized;
fn load(&self) -> Box<Future<Item = Telemetry, Error = Error>>;
}
#[doc(hidden)]
pub fn | () -> Result<Box<TelemetryProvider>> {
if Centos::available() {
Ok(Box::new(Centos))
}
else if Debian::available() {
Ok(Box::new(Debian))
}
else if Fedora::available() {
Ok(Box::new(Fedora))
}
else if Freebsd::available() {
Ok(Box::new(Freebsd))
}
else if Macos::available() {
Ok(Box::new(Macos))
}
else if Nixos::available() {
Ok(Box::new(Nixos))
}
else if Ubuntu::available() {
Ok(Box::new(Ubuntu))
} else {
Err(ErrorKind::ProviderUnavailable("Telemetry").into())
}
}
| factory | identifier_name |
mod.rs | // Copyright 2015-2017 Intecture Developers.
//
// Licensed under the Mozilla Public License 2.0 <LICENSE or
// https://www.tldrlegal.com/l/mpl-2.0>. This file may not be copied,
// modified, or distributed except according to those terms.
//! OS abstractions for `Telemetry`.
mod centos;
mod debian;
mod fedora;
mod freebsd;
mod macos;
mod nixos;
mod ubuntu;
pub use self::centos::Centos;
pub use self::debian::Debian;
pub use self::fedora::Fedora;
pub use self::freebsd::Freebsd;
pub use self::macos::Macos;
pub use self::nixos::Nixos;
pub use self::ubuntu::Ubuntu;
use errors::*;
use futures::Future;
use super::Telemetry;
pub trait TelemetryProvider {
fn available() -> bool where Self: Sized;
fn load(&self) -> Box<Future<Item = Telemetry, Error = Error>>; | if Centos::available() {
Ok(Box::new(Centos))
}
else if Debian::available() {
Ok(Box::new(Debian))
}
else if Fedora::available() {
Ok(Box::new(Fedora))
}
else if Freebsd::available() {
Ok(Box::new(Freebsd))
}
else if Macos::available() {
Ok(Box::new(Macos))
}
else if Nixos::available() {
Ok(Box::new(Nixos))
}
else if Ubuntu::available() {
Ok(Box::new(Ubuntu))
} else {
Err(ErrorKind::ProviderUnavailable("Telemetry").into())
}
} | }
#[doc(hidden)]
pub fn factory() -> Result<Box<TelemetryProvider>> { | random_line_split |
mod.rs | // Copyright 2015-2017 Intecture Developers.
//
// Licensed under the Mozilla Public License 2.0 <LICENSE or
// https://www.tldrlegal.com/l/mpl-2.0>. This file may not be copied,
// modified, or distributed except according to those terms.
//! OS abstractions for `Telemetry`.
mod centos;
mod debian;
mod fedora;
mod freebsd;
mod macos;
mod nixos;
mod ubuntu;
pub use self::centos::Centos;
pub use self::debian::Debian;
pub use self::fedora::Fedora;
pub use self::freebsd::Freebsd;
pub use self::macos::Macos;
pub use self::nixos::Nixos;
pub use self::ubuntu::Ubuntu;
use errors::*;
use futures::Future;
use super::Telemetry;
pub trait TelemetryProvider {
fn available() -> bool where Self: Sized;
fn load(&self) -> Box<Future<Item = Telemetry, Error = Error>>;
}
#[doc(hidden)]
pub fn factory() -> Result<Box<TelemetryProvider>> | Ok(Box::new(Ubuntu))
} else {
Err(ErrorKind::ProviderUnavailable("Telemetry").into())
}
}
| {
if Centos::available() {
Ok(Box::new(Centos))
}
else if Debian::available() {
Ok(Box::new(Debian))
}
else if Fedora::available() {
Ok(Box::new(Fedora))
}
else if Freebsd::available() {
Ok(Box::new(Freebsd))
}
else if Macos::available() {
Ok(Box::new(Macos))
}
else if Nixos::available() {
Ok(Box::new(Nixos))
}
else if Ubuntu::available() { | identifier_body |
regions-mock-tcx.rs | // Copyright 2012 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
// xfail-fast `use` standards don't resolve
// Test a sample usage pattern for regions. Makes use of the
// following features:
//
// - Multiple lifetime parameters
// - Arenas
extern mod extra;
use extra::arena;
use extra::arena::Arena;
use std::hashmap::HashMap;
use std::cast;
use std::libc;
use std::mem;
type Type<'tcx> = &'tcx TypeStructure<'tcx>;
#[deriving(Eq)]
enum TypeStructure<'tcx> {
TypeInt,
TypeFunction(Type<'tcx>, Type<'tcx>),
}
struct TypeContext<'tcx, 'ast> {
ty_arena: &'tcx Arena,
types: ~[Type<'tcx>],
type_table: HashMap<NodeId, Type<'tcx>>,
ast_arena: &'ast Arena,
ast_counter: uint,
}
impl<'tcx,'ast> TypeContext<'tcx, 'ast> {
fn | (ty_arena: &'tcx Arena, ast_arena: &'ast Arena)
-> TypeContext<'tcx, 'ast> {
TypeContext { ty_arena: ty_arena,
types: ~[],
type_table: HashMap::new(),
ast_arena: ast_arena,
ast_counter: 0 }
}
fn add_type(&mut self, s: TypeStructure<'tcx>) -> Type<'tcx> {
for &ty in self.types.iter() {
if *ty == s {
return ty;
}
}
let ty = self.ty_arena.alloc(|| s);
self.types.push(ty);
ty
}
fn set_type(&mut self, id: NodeId, ty: Type<'tcx>) -> Type<'tcx> {
self.type_table.insert(id, ty);
ty
}
fn ast(&mut self, a: AstKind<'ast>) -> Ast<'ast> {
let id = self.ast_counter;
self.ast_counter += 1;
self.ast_arena.alloc(|| AstStructure { id: NodeId {id:id}, kind: a })
}
}
#[deriving(Eq, IterBytes)]
struct NodeId {
id: uint
}
type Ast<'ast> = &'ast AstStructure<'ast>;
struct AstStructure<'ast> {
id: NodeId,
kind: AstKind<'ast>
}
enum AstKind<'ast> {
ExprInt,
ExprVar(uint),
ExprLambda(Ast<'ast>),
}
fn compute_types<'tcx,'ast>(tcx: &mut TypeContext<'tcx,'ast>,
ast: Ast<'ast>) -> Type<'tcx>
{
match ast.kind {
ExprInt | ExprVar(_) => {
let ty = tcx.add_type(TypeInt);
tcx.set_type(ast.id, ty)
}
ExprLambda(ast) => {
let arg_ty = tcx.add_type(TypeInt);
let body_ty = compute_types(tcx, ast);
let lambda_ty = tcx.add_type(TypeFunction(arg_ty, body_ty));
tcx.set_type(ast.id, lambda_ty)
}
}
}
pub fn main() {
let ty_arena = arena::Arena::new();
let ast_arena = arena::Arena::new();
let mut tcx = TypeContext::new(&ty_arena, &ast_arena);
let ast = tcx.ast(ExprInt);
let ty = compute_types(&mut tcx, ast);
assert_eq!(*ty, TypeInt);
}
| new | identifier_name |
regions-mock-tcx.rs | // Copyright 2012 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
// xfail-fast `use` standards don't resolve
// Test a sample usage pattern for regions. Makes use of the
// following features:
//
// - Multiple lifetime parameters
// - Arenas
extern mod extra;
use extra::arena;
use extra::arena::Arena;
use std::hashmap::HashMap;
use std::cast;
use std::libc;
use std::mem;
type Type<'tcx> = &'tcx TypeStructure<'tcx>;
#[deriving(Eq)]
enum TypeStructure<'tcx> {
TypeInt,
TypeFunction(Type<'tcx>, Type<'tcx>),
}
struct TypeContext<'tcx, 'ast> {
ty_arena: &'tcx Arena,
types: ~[Type<'tcx>],
type_table: HashMap<NodeId, Type<'tcx>>,
ast_arena: &'ast Arena,
ast_counter: uint,
}
impl<'tcx,'ast> TypeContext<'tcx, 'ast> {
fn new(ty_arena: &'tcx Arena, ast_arena: &'ast Arena)
-> TypeContext<'tcx, 'ast> {
TypeContext { ty_arena: ty_arena,
types: ~[],
type_table: HashMap::new(),
ast_arena: ast_arena,
ast_counter: 0 }
}
fn add_type(&mut self, s: TypeStructure<'tcx>) -> Type<'tcx> {
for &ty in self.types.iter() {
if *ty == s {
return ty;
}
}
let ty = self.ty_arena.alloc(|| s);
self.types.push(ty);
ty
}
fn set_type(&mut self, id: NodeId, ty: Type<'tcx>) -> Type<'tcx> {
self.type_table.insert(id, ty);
ty
}
fn ast(&mut self, a: AstKind<'ast>) -> Ast<'ast> {
let id = self.ast_counter;
self.ast_counter += 1;
self.ast_arena.alloc(|| AstStructure { id: NodeId {id:id}, kind: a })
}
}
#[deriving(Eq, IterBytes)]
struct NodeId {
id: uint
}
type Ast<'ast> = &'ast AstStructure<'ast>;
struct AstStructure<'ast> {
id: NodeId,
kind: AstKind<'ast>
}
enum AstKind<'ast> {
ExprInt,
ExprVar(uint),
ExprLambda(Ast<'ast>),
}
fn compute_types<'tcx,'ast>(tcx: &mut TypeContext<'tcx,'ast>,
ast: Ast<'ast>) -> Type<'tcx>
{
match ast.kind {
ExprInt | ExprVar(_) => {
let ty = tcx.add_type(TypeInt);
tcx.set_type(ast.id, ty)
}
ExprLambda(ast) => {
let arg_ty = tcx.add_type(TypeInt);
let body_ty = compute_types(tcx, ast);
let lambda_ty = tcx.add_type(TypeFunction(arg_ty, body_ty));
tcx.set_type(ast.id, lambda_ty)
} | }
pub fn main() {
let ty_arena = arena::Arena::new();
let ast_arena = arena::Arena::new();
let mut tcx = TypeContext::new(&ty_arena, &ast_arena);
let ast = tcx.ast(ExprInt);
let ty = compute_types(&mut tcx, ast);
assert_eq!(*ty, TypeInt);
} | } | random_line_split |
regions-mock-tcx.rs | // Copyright 2012 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
// xfail-fast `use` standards don't resolve
// Test a sample usage pattern for regions. Makes use of the
// following features:
//
// - Multiple lifetime parameters
// - Arenas
extern mod extra;
use extra::arena;
use extra::arena::Arena;
use std::hashmap::HashMap;
use std::cast;
use std::libc;
use std::mem;
type Type<'tcx> = &'tcx TypeStructure<'tcx>;
#[deriving(Eq)]
enum TypeStructure<'tcx> {
TypeInt,
TypeFunction(Type<'tcx>, Type<'tcx>),
}
struct TypeContext<'tcx, 'ast> {
ty_arena: &'tcx Arena,
types: ~[Type<'tcx>],
type_table: HashMap<NodeId, Type<'tcx>>,
ast_arena: &'ast Arena,
ast_counter: uint,
}
impl<'tcx,'ast> TypeContext<'tcx, 'ast> {
fn new(ty_arena: &'tcx Arena, ast_arena: &'ast Arena)
-> TypeContext<'tcx, 'ast> {
TypeContext { ty_arena: ty_arena,
types: ~[],
type_table: HashMap::new(),
ast_arena: ast_arena,
ast_counter: 0 }
}
fn add_type(&mut self, s: TypeStructure<'tcx>) -> Type<'tcx> {
for &ty in self.types.iter() {
if *ty == s {
return ty;
}
}
let ty = self.ty_arena.alloc(|| s);
self.types.push(ty);
ty
}
fn set_type(&mut self, id: NodeId, ty: Type<'tcx>) -> Type<'tcx> {
self.type_table.insert(id, ty);
ty
}
fn ast(&mut self, a: AstKind<'ast>) -> Ast<'ast> {
let id = self.ast_counter;
self.ast_counter += 1;
self.ast_arena.alloc(|| AstStructure { id: NodeId {id:id}, kind: a })
}
}
#[deriving(Eq, IterBytes)]
struct NodeId {
id: uint
}
type Ast<'ast> = &'ast AstStructure<'ast>;
struct AstStructure<'ast> {
id: NodeId,
kind: AstKind<'ast>
}
enum AstKind<'ast> {
ExprInt,
ExprVar(uint),
ExprLambda(Ast<'ast>),
}
fn compute_types<'tcx,'ast>(tcx: &mut TypeContext<'tcx,'ast>,
ast: Ast<'ast>) -> Type<'tcx>
{
match ast.kind {
ExprInt | ExprVar(_) => |
ExprLambda(ast) => {
let arg_ty = tcx.add_type(TypeInt);
let body_ty = compute_types(tcx, ast);
let lambda_ty = tcx.add_type(TypeFunction(arg_ty, body_ty));
tcx.set_type(ast.id, lambda_ty)
}
}
}
pub fn main() {
let ty_arena = arena::Arena::new();
let ast_arena = arena::Arena::new();
let mut tcx = TypeContext::new(&ty_arena, &ast_arena);
let ast = tcx.ast(ExprInt);
let ty = compute_types(&mut tcx, ast);
assert_eq!(*ty, TypeInt);
}
| {
let ty = tcx.add_type(TypeInt);
tcx.set_type(ast.id, ty)
} | conditional_block |
unix.rs | use super::RW;
use super::evented::{Evented, EventedImpl, MioAdapter};
use std::io;
use std::path::Path;
use std::os::unix::io::RawFd;
use mio_orig;
/// Unix pipe reader
pub type PipeReader = MioAdapter<mio_orig::unix::PipeReader>;
/// Unix pipe writer
pub type PipeWriter = MioAdapter<mio_orig::unix::PipeWriter>;
/// Unix listener
pub type UnixListener = MioAdapter<mio_orig::unix::UnixListener>;
impl UnixListener {
/// Bind to a port
pub fn bind<P: AsRef<Path> +?Sized>(addr: &P) -> io::Result<Self> |
/// Try cloning the socket descriptor.
pub fn try_clone(&self) -> io::Result<Self> {
self.shared().io_ref().try_clone().map(MioAdapter::new)
}
}
/// Unix socket
pub type UnixSocket = MioAdapter<mio_orig::unix::UnixSocket>;
impl UnixSocket {
/// Returns a new, unbound, Unix domain socket
pub fn stream() -> io::Result<UnixSocket> {
mio_orig::unix::UnixSocket::stream().map(MioAdapter::new)
}
/// Connect the socket to the specified address
pub fn connect<P: AsRef<Path> +?Sized>(self, addr: &P) -> io::Result<(UnixStream, bool)> {
self.shared()
.io_ref()
.try_clone()
.and_then(|t| mio_orig::unix::UnixSocket::connect(t, addr))
.map(|(t, b)| (MioAdapter::new(t), b))
}
/// Bind the socket to the specified address
pub fn bind<P: AsRef<Path> +?Sized>(&self, addr: &P) -> io::Result<()> {
self.shared().io_ref().bind(addr)
}
/// Clone
pub fn try_clone(&self) -> io::Result<Self> {
self.shared().io_ref().try_clone().map(MioAdapter::new)
}
}
/// Unix stream
pub type UnixStream = MioAdapter<mio_orig::unix::UnixStream>;
impl UnixStream {
/// Connect UnixStream to `path`
pub fn connect<P: AsRef<Path> +?Sized>(path: &P) -> io::Result<UnixStream> {
mio_orig::unix::UnixStream::connect(path).map(MioAdapter::new)
}
/// Clone
pub fn try_clone(&self) -> io::Result<Self> {
self.shared().io_ref().try_clone().map(MioAdapter::new)
}
/// Try reading data into a buffer.
///
/// This will not block.
pub fn try_read_recv_fd(&mut self,
buf: &mut [u8])
-> io::Result<Option<(usize, Option<RawFd>)>> {
self.shared().io_mut().try_read_recv_fd(buf)
}
/// Block on read.
pub fn read_recv_fd(&mut self, buf: &mut [u8]) -> io::Result<(usize, Option<RawFd>)> {
loop {
let res = self.try_read_recv_fd(buf);
match res {
Ok(None) => self.block_on(RW::read()),
Ok(Some(r)) => {
return Ok(r);
}
Err(e) => return Err(e),
}
}
}
/// Try writing a data from the buffer.
///
/// This will not block.
pub fn try_write_send_fd(&self, buf: &[u8], fd: RawFd) -> io::Result<Option<usize>> {
self.shared().io_mut().try_write_send_fd(buf, fd)
}
/// Block on write
pub fn write_send_fd(&mut self, buf: &[u8], fd: RawFd) -> io::Result<usize> {
loop {
let res = self.try_write_send_fd(buf, fd);
match res {
Ok(None) => self.block_on(RW::write()),
Ok(Some(r)) => {
return Ok(r);
}
Err(e) => return Err(e),
}
}
}
}
/// Create a pair of unix pipe (reader and writer)
pub fn pipe() -> io::Result<(PipeReader, PipeWriter)> {
let (raw_reader, raw_writer) = try!(mio_orig::unix::pipe());
Ok((MioAdapter::new(raw_reader), MioAdapter::new(raw_writer)))
}
| {
mio_orig::unix::UnixListener::bind(addr).map(MioAdapter::new)
} | identifier_body |
unix.rs | use super::RW;
use super::evented::{Evented, EventedImpl, MioAdapter};
use std::io;
use std::path::Path;
use std::os::unix::io::RawFd;
use mio_orig;
/// Unix pipe reader
pub type PipeReader = MioAdapter<mio_orig::unix::PipeReader>;
/// Unix pipe writer
pub type PipeWriter = MioAdapter<mio_orig::unix::PipeWriter>;
/// Unix listener
pub type UnixListener = MioAdapter<mio_orig::unix::UnixListener>;
impl UnixListener {
/// Bind to a port
pub fn bind<P: AsRef<Path> +?Sized>(addr: &P) -> io::Result<Self> {
mio_orig::unix::UnixListener::bind(addr).map(MioAdapter::new)
}
/// Try cloning the socket descriptor.
pub fn try_clone(&self) -> io::Result<Self> {
self.shared().io_ref().try_clone().map(MioAdapter::new)
}
}
/// Unix socket
pub type UnixSocket = MioAdapter<mio_orig::unix::UnixSocket>;
impl UnixSocket {
/// Returns a new, unbound, Unix domain socket
pub fn stream() -> io::Result<UnixSocket> {
mio_orig::unix::UnixSocket::stream().map(MioAdapter::new)
}
/// Connect the socket to the specified address
pub fn | <P: AsRef<Path> +?Sized>(self, addr: &P) -> io::Result<(UnixStream, bool)> {
self.shared()
.io_ref()
.try_clone()
.and_then(|t| mio_orig::unix::UnixSocket::connect(t, addr))
.map(|(t, b)| (MioAdapter::new(t), b))
}
/// Bind the socket to the specified address
pub fn bind<P: AsRef<Path> +?Sized>(&self, addr: &P) -> io::Result<()> {
self.shared().io_ref().bind(addr)
}
/// Clone
pub fn try_clone(&self) -> io::Result<Self> {
self.shared().io_ref().try_clone().map(MioAdapter::new)
}
}
/// Unix stream
pub type UnixStream = MioAdapter<mio_orig::unix::UnixStream>;
impl UnixStream {
/// Connect UnixStream to `path`
pub fn connect<P: AsRef<Path> +?Sized>(path: &P) -> io::Result<UnixStream> {
mio_orig::unix::UnixStream::connect(path).map(MioAdapter::new)
}
/// Clone
pub fn try_clone(&self) -> io::Result<Self> {
self.shared().io_ref().try_clone().map(MioAdapter::new)
}
/// Try reading data into a buffer.
///
/// This will not block.
pub fn try_read_recv_fd(&mut self,
buf: &mut [u8])
-> io::Result<Option<(usize, Option<RawFd>)>> {
self.shared().io_mut().try_read_recv_fd(buf)
}
/// Block on read.
pub fn read_recv_fd(&mut self, buf: &mut [u8]) -> io::Result<(usize, Option<RawFd>)> {
loop {
let res = self.try_read_recv_fd(buf);
match res {
Ok(None) => self.block_on(RW::read()),
Ok(Some(r)) => {
return Ok(r);
}
Err(e) => return Err(e),
}
}
}
/// Try writing a data from the buffer.
///
/// This will not block.
pub fn try_write_send_fd(&self, buf: &[u8], fd: RawFd) -> io::Result<Option<usize>> {
self.shared().io_mut().try_write_send_fd(buf, fd)
}
/// Block on write
pub fn write_send_fd(&mut self, buf: &[u8], fd: RawFd) -> io::Result<usize> {
loop {
let res = self.try_write_send_fd(buf, fd);
match res {
Ok(None) => self.block_on(RW::write()),
Ok(Some(r)) => {
return Ok(r);
}
Err(e) => return Err(e),
}
}
}
}
/// Create a pair of unix pipe (reader and writer)
pub fn pipe() -> io::Result<(PipeReader, PipeWriter)> {
let (raw_reader, raw_writer) = try!(mio_orig::unix::pipe());
Ok((MioAdapter::new(raw_reader), MioAdapter::new(raw_writer)))
}
| connect | identifier_name |
unix.rs | use super::RW;
use super::evented::{Evented, EventedImpl, MioAdapter};
use std::io;
use std::path::Path;
use std::os::unix::io::RawFd;
use mio_orig;
/// Unix pipe reader
pub type PipeReader = MioAdapter<mio_orig::unix::PipeReader>;
/// Unix pipe writer
pub type PipeWriter = MioAdapter<mio_orig::unix::PipeWriter>;
/// Unix listener
pub type UnixListener = MioAdapter<mio_orig::unix::UnixListener>;
impl UnixListener {
/// Bind to a port
pub fn bind<P: AsRef<Path> +?Sized>(addr: &P) -> io::Result<Self> {
mio_orig::unix::UnixListener::bind(addr).map(MioAdapter::new)
}
/// Try cloning the socket descriptor.
pub fn try_clone(&self) -> io::Result<Self> {
self.shared().io_ref().try_clone().map(MioAdapter::new)
}
}
/// Unix socket
pub type UnixSocket = MioAdapter<mio_orig::unix::UnixSocket>;
impl UnixSocket {
/// Returns a new, unbound, Unix domain socket
pub fn stream() -> io::Result<UnixSocket> {
mio_orig::unix::UnixSocket::stream().map(MioAdapter::new)
}
/// Connect the socket to the specified address
pub fn connect<P: AsRef<Path> +?Sized>(self, addr: &P) -> io::Result<(UnixStream, bool)> {
self.shared()
.io_ref()
.try_clone()
.and_then(|t| mio_orig::unix::UnixSocket::connect(t, addr))
.map(|(t, b)| (MioAdapter::new(t), b))
}
/// Bind the socket to the specified address
pub fn bind<P: AsRef<Path> +?Sized>(&self, addr: &P) -> io::Result<()> {
self.shared().io_ref().bind(addr)
}
/// Clone
pub fn try_clone(&self) -> io::Result<Self> {
self.shared().io_ref().try_clone().map(MioAdapter::new)
}
}
/// Unix stream
pub type UnixStream = MioAdapter<mio_orig::unix::UnixStream>;
| pub fn connect<P: AsRef<Path> +?Sized>(path: &P) -> io::Result<UnixStream> {
mio_orig::unix::UnixStream::connect(path).map(MioAdapter::new)
}
/// Clone
pub fn try_clone(&self) -> io::Result<Self> {
self.shared().io_ref().try_clone().map(MioAdapter::new)
}
/// Try reading data into a buffer.
///
/// This will not block.
pub fn try_read_recv_fd(&mut self,
buf: &mut [u8])
-> io::Result<Option<(usize, Option<RawFd>)>> {
self.shared().io_mut().try_read_recv_fd(buf)
}
/// Block on read.
pub fn read_recv_fd(&mut self, buf: &mut [u8]) -> io::Result<(usize, Option<RawFd>)> {
loop {
let res = self.try_read_recv_fd(buf);
match res {
Ok(None) => self.block_on(RW::read()),
Ok(Some(r)) => {
return Ok(r);
}
Err(e) => return Err(e),
}
}
}
/// Try writing a data from the buffer.
///
/// This will not block.
pub fn try_write_send_fd(&self, buf: &[u8], fd: RawFd) -> io::Result<Option<usize>> {
self.shared().io_mut().try_write_send_fd(buf, fd)
}
/// Block on write
pub fn write_send_fd(&mut self, buf: &[u8], fd: RawFd) -> io::Result<usize> {
loop {
let res = self.try_write_send_fd(buf, fd);
match res {
Ok(None) => self.block_on(RW::write()),
Ok(Some(r)) => {
return Ok(r);
}
Err(e) => return Err(e),
}
}
}
}
/// Create a pair of unix pipe (reader and writer)
pub fn pipe() -> io::Result<(PipeReader, PipeWriter)> {
let (raw_reader, raw_writer) = try!(mio_orig::unix::pipe());
Ok((MioAdapter::new(raw_reader), MioAdapter::new(raw_writer)))
} |
impl UnixStream {
/// Connect UnixStream to `path` | random_line_split |
matching.rs | in CSS rules changes, we
// need to try to update all CSS animations on the element if the
// element has or will have CSS animation style regardless of whether
// the animation is running or not.
//
// TODO: We should check which @keyframes were added/changed/deleted and
// update only animations corresponding to those @keyframes.
if keyframes_could_have_changed &&
(has_new_animation_style || self.has_css_animations())
{
return true;
}
// If the animations changed, well...
if!old_box_style.animations_equals(new_box_style) {
return true;
}
let old_display = old_box_style.clone_display();
let new_display = new_box_style.clone_display();
// If we were display: none, we may need to trigger animations.
if old_display == Display::None && new_display!= Display::None {
return has_new_animation_style;
}
// If we are becoming display: none, we may need to stop animations.
if old_display!= Display::None && new_display == Display::None {
return self.has_css_animations();
}
false
}
/// Create a SequentialTask for resolving descendants in a SMIL display property
/// animation if the display property changed from none.
#[cfg(feature = "gecko")]
fn handle_display_change_for_smil_if_needed(
&self,
context: &mut StyleContext<Self>,
old_values: Option<&ComputedValues>,
new_values: &ComputedValues,
restyle_hints: RestyleHint
) {
use context::PostAnimationTasks;
if!restyle_hints.intersects(RestyleHint::RESTYLE_SMIL) {
return;
}
if new_values.is_display_property_changed_from_none(old_values) {
// When display value is changed from none to other, we need to
// traverse descendant elements in a subsequent normal
// traversal (we can't traverse them in this animation-only restyle
// since we have no way to know whether the decendants
// need to be traversed at the beginning of the animation-only
// restyle).
let task = ::context::SequentialTask::process_post_animation(
*self,
PostAnimationTasks::DISPLAY_CHANGED_FROM_NONE_FOR_SMIL,
);
context.thread_local.tasks.push(task);
}
}
#[cfg(feature = "gecko")]
fn process_animations(
&self,
context: &mut StyleContext<Self>,
old_values: &mut Option<Arc<ComputedValues>>,
new_values: &mut Arc<ComputedValues>,
restyle_hint: RestyleHint,
important_rules_changed: bool,
) {
use context::UpdateAnimationsTasks;
if context.shared.traversal_flags.for_animation_only() {
self.handle_display_change_for_smil_if_needed(
context,
old_values.as_ref().map(|v| &**v),
new_values,
restyle_hint,
);
return;
}
// Bug 868975: These steps should examine and update the visited styles
// in addition to the unvisited styles.
let mut tasks = UpdateAnimationsTasks::empty();
if self.needs_animations_update(context, old_values.as_ref().map(|s| &**s), new_values) {
tasks.insert(UpdateAnimationsTasks::CSS_ANIMATIONS);
}
let before_change_style = if self.might_need_transitions_update(old_values.as_ref().map(|s| &**s),
new_values) {
let after_change_style = if self.has_css_transitions() {
self.after_change_style(context, new_values)
} else {
None
};
// In order to avoid creating a SequentialTask for transitions which
// may not be updated, we check it per property to make sure Gecko
// side will really update transition.
let needs_transitions_update = {
// We borrow new_values here, so need to add a scope to make
// sure we release it before assigning a new value to it.
let after_change_style_ref =
after_change_style.as_ref().unwrap_or(&new_values);
self.needs_transitions_update(
old_values.as_ref().unwrap(),
after_change_style_ref,
)
};
if needs_transitions_update {
if let Some(values_without_transitions) = after_change_style {
*new_values = values_without_transitions;
}
tasks.insert(UpdateAnimationsTasks::CSS_TRANSITIONS);
// We need to clone old_values into SequentialTask, so we can
// use it later.
old_values.clone()
} else {
None
}
} else {
None
};
if self.has_animations() {
tasks.insert(UpdateAnimationsTasks::EFFECT_PROPERTIES);
if important_rules_changed {
tasks.insert(UpdateAnimationsTasks::CASCADE_RESULTS);
}
if new_values.is_display_property_changed_from_none(old_values.as_ref().map(|s| &**s)) {
tasks.insert(UpdateAnimationsTasks::DISPLAY_CHANGED_FROM_NONE);
}
}
if!tasks.is_empty() {
let task = ::context::SequentialTask::update_animations(*self,
before_change_style,
tasks);
context.thread_local.tasks.push(task);
}
}
#[cfg(feature = "servo")]
fn process_animations(
&self,
context: &mut StyleContext<Self>,
old_values: &mut Option<Arc<ComputedValues>>,
new_values: &mut Arc<ComputedValues>,
_restyle_hint: RestyleHint,
_important_rules_changed: bool,
) {
use animation;
use dom::TNode;
let mut possibly_expired_animations = vec![];
let shared_context = context.shared;
if let Some(ref mut old) = *old_values {
// FIXME(emilio, #20116): This makes no sense.
self.update_animations_for_cascade(
shared_context,
old,
&mut possibly_expired_animations,
&context.thread_local.font_metrics_provider,
);
}
let new_animations_sender = &context.thread_local.new_animations_sender;
let this_opaque = self.as_node().opaque();
// Trigger any present animations if necessary.
animation::maybe_start_animations(
&shared_context,
new_animations_sender,
this_opaque,
&new_values,
);
// Trigger transitions if necessary. This will reset `new_values` back
// to its old value if it did trigger a transition.
if let Some(ref values) = *old_values {
animation::start_transitions_if_applicable(
new_animations_sender,
this_opaque,
&values,
new_values,
&shared_context.timer,
&possibly_expired_animations,
);
}
}
/// Computes and applies non-redundant damage.
fn accumulate_damage_for(
&self,
shared_context: &SharedStyleContext,
damage: &mut RestyleDamage,
old_values: &ComputedValues,
new_values: &ComputedValues,
pseudo: Option<&PseudoElement>,
) -> ChildCascadeRequirement {
debug!("accumulate_damage_for: {:?}", self);
debug_assert!(!shared_context.traversal_flags.contains(TraversalFlags::Forgetful));
let difference =
self.compute_style_difference(old_values, new_values, pseudo);
*damage |= difference.damage;
debug!(" > style difference: {:?}", difference);
// We need to cascade the children in order to ensure the correct
// propagation of inherited computed value flags.
if old_values.flags.maybe_inherited()!= new_values.flags.maybe_inherited() {
debug!(" > flags changed: {:?}!= {:?}", old_values.flags, new_values.flags);
return ChildCascadeRequirement::MustCascadeChildren;
}
match difference.change {
StyleChange::Unchanged => {
return ChildCascadeRequirement::CanSkipCascade
},
StyleChange::Changed { reset_only } => {
// If inherited properties changed, the best we can do is
// cascade the children.
if!reset_only {
return ChildCascadeRequirement::MustCascadeChildren
}
}
}
let old_display = old_values.get_box().clone_display();
let new_display = new_values.get_box().clone_display();
// If we used to be a display: none element, and no longer are,
// our children need to be restyled because they're unstyled.
//
// NOTE(emilio): Gecko has the special-case of -moz-binding, but
// that gets handled on the frame constructor when processing
// the reframe, so no need to handle that here.
if old_display == Display::None && old_display!= new_display {
return ChildCascadeRequirement::MustCascadeChildren
}
// Blockification of children may depend on our display value,
// so we need to actually do the recascade. We could potentially
// do better, but it doesn't seem worth it.
if old_display.is_item_container()!= new_display.is_item_container() {
return ChildCascadeRequirement::MustCascadeChildren
}
// Line break suppression may also be affected if the display
// type changes from ruby to non-ruby.
#[cfg(feature = "gecko")]
{
if old_display.is_ruby_type()!= new_display.is_ruby_type() {
return ChildCascadeRequirement::MustCascadeChildren
}
}
// Children with justify-items: auto may depend on our
// justify-items property value.
//
// Similarly, we could potentially do better, but this really
// seems not common enough to care about.
#[cfg(feature = "gecko")]
{
use values::specified::align::AlignFlags;
let old_justify_items =
old_values.get_position().clone_justify_items();
let new_justify_items =
new_values.get_position().clone_justify_items();
let was_legacy_justify_items =
old_justify_items.computed.0.contains(AlignFlags::LEGACY);
let is_legacy_justify_items =
new_justify_items.computed.0.contains(AlignFlags::LEGACY);
if is_legacy_justify_items!= was_legacy_justify_items {
return ChildCascadeRequirement::MustCascadeChildren;
}
if was_legacy_justify_items &&
old_justify_items.computed!= new_justify_items.computed {
return ChildCascadeRequirement::MustCascadeChildren;
}
}
#[cfg(feature = "servo")]
{
// We may need to set or propagate the CAN_BE_FRAGMENTED bit
// on our children.
if old_values.is_multicol()!= new_values.is_multicol() {
return ChildCascadeRequirement::MustCascadeChildren;
}
}
// We could prove that, if our children don't inherit reset
// properties, we can stop the cascade.
ChildCascadeRequirement::MustCascadeChildrenIfInheritResetStyle
}
// FIXME(emilio, #20116): It's not clear to me that the name of this method
// represents anything of what it does.
//
// Also, this function gets the old style, for some reason I don't really
// get, but the functions called (mainly update_style_for_animation) expects
// the new style, wtf?
#[cfg(feature = "servo")]
fn update_animations_for_cascade(
&self,
context: &SharedStyleContext,
style: &mut Arc<ComputedValues>,
possibly_expired_animations: &mut Vec<::animation::PropertyAnimation>,
font_metrics: &::font_metrics::FontMetricsProvider,
) {
use animation::{self, Animation};
use dom::TNode;
// Finish any expired transitions.
let this_opaque = self.as_node().opaque();
animation::complete_expired_transitions(this_opaque, style, context);
// Merge any running animations into the current style, and cancel them.
let had_running_animations =
context.running_animations.read().get(&this_opaque).is_some();
if!had_running_animations {
return;
}
let mut all_running_animations = context.running_animations.write();
for running_animation in all_running_animations.get_mut(&this_opaque).unwrap() {
// This shouldn't happen frequently, but under some circumstances
// mainly huge load or debug builds, the constellation might be
// delayed in sending the `TickAllAnimations` message to layout.
//
// Thus, we can't assume all the animations have been already
// updated by layout, because other restyle due to script might be
// triggered by layout before the animation tick.
//
// See #12171 and the associated PR for an example where this
// happened while debugging other release panic.
if running_animation.is_expired() {
continue;
}
animation::update_style_for_animation::<Self>(
context,
running_animation,
style,
font_metrics,
);
if let Animation::Transition(_, _, ref frame, _) = *running_animation {
possibly_expired_animations.push(frame.property_animation.clone())
}
}
}
}
impl<E: TElement> PrivateMatchMethods for E {}
/// The public API that elements expose for selector matching.
pub trait MatchMethods : TElement {
/// Returns the closest parent element that doesn't have a display: contents
/// style (and thus generates a box).
///
/// This is needed to correctly handle blockification of flex and grid
/// items.
///
/// Returns itself if the element has no parent. In practice this doesn't
/// happen because the root element is blockified per spec, but it could
/// happen if we decide to not blockify for roots of disconnected subtrees,
/// which is a kind of dubious behavior.
fn layout_parent(&self) -> Self {
let mut current = self.clone();
loop {
current = match current.traversal_parent() {
Some(el) => el,
None => return current,
};
let is_display_contents =
current.borrow_data().unwrap().styles.primary().is_display_contents();
if!is_display_contents {
return current;
}
}
}
/// Updates the styles with the new ones, diffs them, and stores the restyle
/// damage.
fn finish_restyle(
&self,
context: &mut StyleContext<Self>,
data: &mut ElementData,
mut new_styles: ResolvedElementStyles,
important_rules_changed: bool,
) -> ChildCascadeRequirement {
use std::cmp;
self.process_animations(
context,
&mut data.styles.primary,
&mut new_styles.primary.style.0,
data.hint,
important_rules_changed,
);
// First of all, update the styles.
let old_styles = data.set_styles(new_styles);
let new_primary_style = data.styles.primary.as_ref().unwrap();
let mut cascade_requirement = ChildCascadeRequirement::CanSkipCascade;
if self.is_root() &&!self.is_native_anonymous() {
let device = context.shared.stylist.device();
let new_font_size = new_primary_style.get_font().clone_font_size();
if old_styles.primary.as_ref().map_or(true, |s| s.get_font().clone_font_size()!= new_font_size) {
debug_assert!(self.owner_doc_matches_for_testing(device));
device.set_root_font_size(new_font_size.size());
// If the root font-size changed since last time, and something
// in the document did use rem units, ensure we recascade the
// entire tree.
if device.used_root_font_size() {
cascade_requirement = ChildCascadeRequirement::MustCascadeDescendants;
}
}
}
if context.shared.stylist.quirks_mode() == QuirksMode::Quirks {
if self.is_html_document_body_element() {
// NOTE(emilio): We _could_ handle dynamic changes to it if it
// changes and before we reach our children the cascade stops,
// but we don't track right now whether we use the document body
// color, and nobody else handles that properly anyway.
let device = context.shared.stylist.device();
// Needed for the "inherit from body" quirk.
let text_color = new_primary_style.get_color().clone_color();
device.set_body_text_color(text_color);
}
}
// Don't accumulate damage if we're in a forgetful traversal.
if context.shared.traversal_flags.contains(TraversalFlags::Forgetful) {
return ChildCascadeRequirement::MustCascadeChildren;
}
// Also, don't do anything if there was no style.
let old_primary_style = match old_styles.primary {
Some(s) => s,
None => return ChildCascadeRequirement::MustCascadeChildren,
};
cascade_requirement = cmp::max(
cascade_requirement,
self.accumulate_damage_for(
context.shared,
&mut data.damage,
&old_primary_style,
new_primary_style,
None,
)
);
if data.styles.pseudos.is_empty() && old_styles.pseudos.is_empty() {
// This is the common case; no need to examine pseudos here.
return cascade_requirement; | } | random_line_split |
|
matching.rs | if replacements.contains(RestyleHint::RESTYLE_STYLE_ATTRIBUTE) {
let style_attribute = self.style_attribute();
result |= replace_rule_node(
CascadeLevel::StyleAttributeNormal,
style_attribute,
primary_rules,
);
result |= replace_rule_node(
CascadeLevel::StyleAttributeImportant,
style_attribute,
primary_rules,
);
// FIXME(emilio): Still a hack!
self.unset_dirty_style_attribute();
}
return result;
}
// Animation restyle hints are processed prior to other restyle
// hints in the animation-only traversal.
//
// Non-animation restyle hints will be processed in a subsequent
// normal traversal.
if replacements.intersects(RestyleHint::for_animations()) {
debug_assert!(context.shared.traversal_flags.for_animation_only());
if replacements.contains(RestyleHint::RESTYLE_SMIL) {
replace_rule_node(
CascadeLevel::SMILOverride,
self.smil_override(),
primary_rules,
);
}
if replacements.contains(RestyleHint::RESTYLE_CSS_TRANSITIONS) {
replace_rule_node(
CascadeLevel::Transitions,
self.transition_rule().as_ref().map(|a| a.borrow_arc()),
primary_rules,
);
}
if replacements.contains(RestyleHint::RESTYLE_CSS_ANIMATIONS) {
replace_rule_node(
CascadeLevel::Animations,
self.animation_rule().as_ref().map(|a| a.borrow_arc()),
primary_rules,
);
}
}
false
}
/// If there is no transition rule in the ComputedValues, it returns None.
#[cfg(feature = "gecko")]
fn after_change_style(
&self,
context: &mut StyleContext<Self>,
primary_style: &Arc<ComputedValues>
) -> Option<Arc<ComputedValues>> {
use context::CascadeInputs;
use style_resolver::{PseudoElementResolution, StyleResolverForElement};
use stylist::RuleInclusion;
let rule_node = primary_style.rules();
let without_transition_rules =
context.shared.stylist.rule_tree().remove_transition_rule_if_applicable(rule_node);
if without_transition_rules == *rule_node {
// We don't have transition rule in this case, so return None to let
// the caller use the original ComputedValues.
return None;
}
// FIXME(bug 868975): We probably need to transition visited style as
// well.
let inputs =
CascadeInputs {
rules: Some(without_transition_rules),
visited_rules: primary_style.visited_rules().cloned()
};
// Actually `PseudoElementResolution` doesn't really matter.
let style =
StyleResolverForElement::new(*self, context, RuleInclusion::All, PseudoElementResolution::IfApplicable)
.cascade_style_and_visited_with_default_parents(inputs);
Some(style.0)
}
#[cfg(feature = "gecko")]
fn needs_animations_update(
&self,
context: &mut StyleContext<Self>,
old_values: Option<&ComputedValues>,
new_values: &ComputedValues,
) -> bool {
let new_box_style = new_values.get_box();
let has_new_animation_style = new_box_style.specifies_animations();
let old = match old_values {
Some(old) => old,
None => return has_new_animation_style,
};
let old_box_style = old.get_box();
let keyframes_could_have_changed =
context.shared.traversal_flags.contains(TraversalFlags::ForCSSRuleChanges);
// If the traversal is triggered due to changes in CSS rules changes, we
// need to try to update all CSS animations on the element if the
// element has or will have CSS animation style regardless of whether
// the animation is running or not.
//
// TODO: We should check which @keyframes were added/changed/deleted and
// update only animations corresponding to those @keyframes.
if keyframes_could_have_changed &&
(has_new_animation_style || self.has_css_animations())
{
return true;
}
// If the animations changed, well...
if!old_box_style.animations_equals(new_box_style) {
return true;
}
let old_display = old_box_style.clone_display();
let new_display = new_box_style.clone_display();
// If we were display: none, we may need to trigger animations.
if old_display == Display::None && new_display!= Display::None {
return has_new_animation_style;
}
// If we are becoming display: none, we may need to stop animations.
if old_display!= Display::None && new_display == Display::None {
return self.has_css_animations();
}
false
}
/// Create a SequentialTask for resolving descendants in a SMIL display property
/// animation if the display property changed from none.
#[cfg(feature = "gecko")]
fn handle_display_change_for_smil_if_needed(
&self,
context: &mut StyleContext<Self>,
old_values: Option<&ComputedValues>,
new_values: &ComputedValues,
restyle_hints: RestyleHint
) {
use context::PostAnimationTasks;
if!restyle_hints.intersects(RestyleHint::RESTYLE_SMIL) {
return;
}
if new_values.is_display_property_changed_from_none(old_values) {
// When display value is changed from none to other, we need to
// traverse descendant elements in a subsequent normal
// traversal (we can't traverse them in this animation-only restyle
// since we have no way to know whether the decendants
// need to be traversed at the beginning of the animation-only
// restyle).
let task = ::context::SequentialTask::process_post_animation(
*self,
PostAnimationTasks::DISPLAY_CHANGED_FROM_NONE_FOR_SMIL,
);
context.thread_local.tasks.push(task);
}
}
#[cfg(feature = "gecko")]
fn process_animations(
&self,
context: &mut StyleContext<Self>,
old_values: &mut Option<Arc<ComputedValues>>,
new_values: &mut Arc<ComputedValues>,
restyle_hint: RestyleHint,
important_rules_changed: bool,
) {
use context::UpdateAnimationsTasks;
if context.shared.traversal_flags.for_animation_only() {
self.handle_display_change_for_smil_if_needed(
context,
old_values.as_ref().map(|v| &**v),
new_values,
restyle_hint,
);
return;
}
// Bug 868975: These steps should examine and update the visited styles
// in addition to the unvisited styles.
let mut tasks = UpdateAnimationsTasks::empty();
if self.needs_animations_update(context, old_values.as_ref().map(|s| &**s), new_values) {
tasks.insert(UpdateAnimationsTasks::CSS_ANIMATIONS);
}
let before_change_style = if self.might_need_transitions_update(old_values.as_ref().map(|s| &**s),
new_values) {
let after_change_style = if self.has_css_transitions() {
self.after_change_style(context, new_values)
} else {
None
};
// In order to avoid creating a SequentialTask for transitions which
// may not be updated, we check it per property to make sure Gecko
// side will really update transition.
let needs_transitions_update = {
// We borrow new_values here, so need to add a scope to make
// sure we release it before assigning a new value to it.
let after_change_style_ref =
after_change_style.as_ref().unwrap_or(&new_values);
self.needs_transitions_update(
old_values.as_ref().unwrap(),
after_change_style_ref,
)
};
if needs_transitions_update {
if let Some(values_without_transitions) = after_change_style {
*new_values = values_without_transitions;
}
tasks.insert(UpdateAnimationsTasks::CSS_TRANSITIONS);
// We need to clone old_values into SequentialTask, so we can
// use it later.
old_values.clone()
} else {
None
}
} else {
None
};
if self.has_animations() {
tasks.insert(UpdateAnimationsTasks::EFFECT_PROPERTIES);
if important_rules_changed {
tasks.insert(UpdateAnimationsTasks::CASCADE_RESULTS);
}
if new_values.is_display_property_changed_from_none(old_values.as_ref().map(|s| &**s)) {
tasks.insert(UpdateAnimationsTasks::DISPLAY_CHANGED_FROM_NONE);
}
}
if!tasks.is_empty() {
let task = ::context::SequentialTask::update_animations(*self,
before_change_style,
tasks);
context.thread_local.tasks.push(task);
}
}
#[cfg(feature = "servo")]
fn process_animations(
&self,
context: &mut StyleContext<Self>,
old_values: &mut Option<Arc<ComputedValues>>,
new_values: &mut Arc<ComputedValues>,
_restyle_hint: RestyleHint,
_important_rules_changed: bool,
) {
use animation;
use dom::TNode;
let mut possibly_expired_animations = vec![];
let shared_context = context.shared;
if let Some(ref mut old) = *old_values {
// FIXME(emilio, #20116): This makes no sense.
self.update_animations_for_cascade(
shared_context,
old,
&mut possibly_expired_animations,
&context.thread_local.font_metrics_provider,
);
}
let new_animations_sender = &context.thread_local.new_animations_sender;
let this_opaque = self.as_node().opaque();
// Trigger any present animations if necessary.
animation::maybe_start_animations(
&shared_context,
new_animations_sender,
this_opaque,
&new_values,
);
// Trigger transitions if necessary. This will reset `new_values` back
// to its old value if it did trigger a transition.
if let Some(ref values) = *old_values {
animation::start_transitions_if_applicable(
new_animations_sender,
this_opaque,
&values,
new_values,
&shared_context.timer,
&possibly_expired_animations,
);
}
}
/// Computes and applies non-redundant damage.
fn accumulate_damage_for(
&self,
shared_context: &SharedStyleContext,
damage: &mut RestyleDamage,
old_values: &ComputedValues,
new_values: &ComputedValues,
pseudo: Option<&PseudoElement>,
) -> ChildCascadeRequirement {
debug!("accumulate_damage_for: {:?}", self);
debug_assert!(!shared_context.traversal_flags.contains(TraversalFlags::Forgetful));
let difference =
self.compute_style_difference(old_values, new_values, pseudo);
*damage |= difference.damage;
debug!(" > style difference: {:?}", difference);
// We need to cascade the children in order to ensure the correct
// propagation of inherited computed value flags.
if old_values.flags.maybe_inherited()!= new_values.flags.maybe_inherited() {
debug!(" > flags changed: {:?}!= {:?}", old_values.flags, new_values.flags);
return ChildCascadeRequirement::MustCascadeChildren;
}
match difference.change {
StyleChange::Unchanged => {
return ChildCascadeRequirement::CanSkipCascade
},
StyleChange::Changed { reset_only } => {
// If inherited properties changed, the best we can do is
// cascade the children.
if!reset_only {
return ChildCascadeRequirement::MustCascadeChildren
}
}
}
let old_display = old_values.get_box().clone_display();
let new_display = new_values.get_box().clone_display();
// If we used to be a display: none element, and no longer are,
// our children need to be restyled because they're unstyled.
//
// NOTE(emilio): Gecko has the special-case of -moz-binding, but
// that gets handled on the frame constructor when processing
// the reframe, so no need to handle that here.
if old_display == Display::None && old_display!= new_display {
return ChildCascadeRequirement::MustCascadeChildren
}
// Blockification of children may depend on our display value,
// so we need to actually do the recascade. We could potentially
// do better, but it doesn't seem worth it.
if old_display.is_item_container()!= new_display.is_item_container() {
return ChildCascadeRequirement::MustCascadeChildren
}
// Line break suppression may also be affected if the display
// type changes from ruby to non-ruby.
#[cfg(feature = "gecko")]
{
if old_display.is_ruby_type()!= new_display.is_ruby_type() {
return ChildCascadeRequirement::MustCascadeChildren
}
}
// Children with justify-items: auto may depend on our
// justify-items property value.
//
// Similarly, we could potentially do better, but this really
// seems not common enough to care about.
#[cfg(feature = "gecko")]
{
use values::specified::align::AlignFlags;
let old_justify_items =
old_values.get_position().clone_justify_items();
let new_justify_items =
new_values.get_position().clone_justify_items();
let was_legacy_justify_items =
old_justify_items.computed.0.contains(AlignFlags::LEGACY);
let is_legacy_justify_items =
new_justify_items.computed.0.contains(AlignFlags::LEGACY);
if is_legacy_justify_items!= was_legacy_justify_items {
return ChildCascadeRequirement::MustCascadeChildren;
}
if was_legacy_justify_items &&
old_justify_items.computed!= new_justify_items.computed {
return ChildCascadeRequirement::MustCascadeChildren;
}
}
#[cfg(feature = "servo")]
{
// We may need to set or propagate the CAN_BE_FRAGMENTED bit
// on our children.
if old_values.is_multicol()!= new_values.is_multicol() {
return ChildCascadeRequirement::MustCascadeChildren;
}
}
// We could prove that, if our children don't inherit reset
// properties, we can stop the cascade.
ChildCascadeRequirement::MustCascadeChildrenIfInheritResetStyle
}
// FIXME(emilio, #20116): It's not clear to me that the name of this method
// represents anything of what it does.
//
// Also, this function gets the old style, for some reason I don't really
// get, but the functions called (mainly update_style_for_animation) expects
// the new style, wtf?
#[cfg(feature = "servo")]
fn update_animations_for_cascade(
&self,
context: &SharedStyleContext,
style: &mut Arc<ComputedValues>,
possibly_expired_animations: &mut Vec<::animation::PropertyAnimation>,
font_metrics: &::font_metrics::FontMetricsProvider,
) | //
// Thus, we can't assume all the animations have been already
// updated by layout, because other restyle due to script might be
// triggered by layout before the animation tick.
//
// See #12171 and the associated PR for an example where this
// happened while debugging other release panic.
if running_animation.is_expired() {
continue;
}
animation::update_style_for_animation::<Self>(
context,
running_animation,
style,
font_metrics,
);
if let Animation::Transition(_, _, ref frame, _) = *running_animation {
possibly_expired_animations.push(frame.property_animation.clone())
}
}
}
}
| {
use animation::{self, Animation};
use dom::TNode;
// Finish any expired transitions.
let this_opaque = self.as_node().opaque();
animation::complete_expired_transitions(this_opaque, style, context);
// Merge any running animations into the current style, and cancel them.
let had_running_animations =
context.running_animations.read().get(&this_opaque).is_some();
if !had_running_animations {
return;
}
let mut all_running_animations = context.running_animations.write();
for running_animation in all_running_animations.get_mut(&this_opaque).unwrap() {
// This shouldn't happen frequently, but under some circumstances
// mainly huge load or debug builds, the constellation might be
// delayed in sending the `TickAllAnimations` message to layout. | identifier_body |
matching.rs | if replacements.contains(RestyleHint::RESTYLE_STYLE_ATTRIBUTE) {
let style_attribute = self.style_attribute();
result |= replace_rule_node(
CascadeLevel::StyleAttributeNormal,
style_attribute,
primary_rules,
);
result |= replace_rule_node(
CascadeLevel::StyleAttributeImportant,
style_attribute,
primary_rules,
);
// FIXME(emilio): Still a hack!
self.unset_dirty_style_attribute();
}
return result;
}
// Animation restyle hints are processed prior to other restyle
// hints in the animation-only traversal.
//
// Non-animation restyle hints will be processed in a subsequent
// normal traversal.
if replacements.intersects(RestyleHint::for_animations()) {
debug_assert!(context.shared.traversal_flags.for_animation_only());
if replacements.contains(RestyleHint::RESTYLE_SMIL) {
replace_rule_node(
CascadeLevel::SMILOverride,
self.smil_override(),
primary_rules,
);
}
if replacements.contains(RestyleHint::RESTYLE_CSS_TRANSITIONS) {
replace_rule_node(
CascadeLevel::Transitions,
self.transition_rule().as_ref().map(|a| a.borrow_arc()),
primary_rules,
);
}
if replacements.contains(RestyleHint::RESTYLE_CSS_ANIMATIONS) {
replace_rule_node(
CascadeLevel::Animations,
self.animation_rule().as_ref().map(|a| a.borrow_arc()),
primary_rules,
);
}
}
false
}
/// If there is no transition rule in the ComputedValues, it returns None.
#[cfg(feature = "gecko")]
fn after_change_style(
&self,
context: &mut StyleContext<Self>,
primary_style: &Arc<ComputedValues>
) -> Option<Arc<ComputedValues>> {
use context::CascadeInputs;
use style_resolver::{PseudoElementResolution, StyleResolverForElement};
use stylist::RuleInclusion;
let rule_node = primary_style.rules();
let without_transition_rules =
context.shared.stylist.rule_tree().remove_transition_rule_if_applicable(rule_node);
if without_transition_rules == *rule_node {
// We don't have transition rule in this case, so return None to let
// the caller use the original ComputedValues.
return None;
}
// FIXME(bug 868975): We probably need to transition visited style as
// well.
let inputs =
CascadeInputs {
rules: Some(without_transition_rules),
visited_rules: primary_style.visited_rules().cloned()
};
// Actually `PseudoElementResolution` doesn't really matter.
let style =
StyleResolverForElement::new(*self, context, RuleInclusion::All, PseudoElementResolution::IfApplicable)
.cascade_style_and_visited_with_default_parents(inputs);
Some(style.0)
}
#[cfg(feature = "gecko")]
fn needs_animations_update(
&self,
context: &mut StyleContext<Self>,
old_values: Option<&ComputedValues>,
new_values: &ComputedValues,
) -> bool {
let new_box_style = new_values.get_box();
let has_new_animation_style = new_box_style.specifies_animations();
let old = match old_values {
Some(old) => old,
None => return has_new_animation_style,
};
let old_box_style = old.get_box();
let keyframes_could_have_changed =
context.shared.traversal_flags.contains(TraversalFlags::ForCSSRuleChanges);
// If the traversal is triggered due to changes in CSS rules changes, we
// need to try to update all CSS animations on the element if the
// element has or will have CSS animation style regardless of whether
// the animation is running or not.
//
// TODO: We should check which @keyframes were added/changed/deleted and
// update only animations corresponding to those @keyframes.
if keyframes_could_have_changed &&
(has_new_animation_style || self.has_css_animations())
{
return true;
}
// If the animations changed, well...
if!old_box_style.animations_equals(new_box_style) {
return true;
}
let old_display = old_box_style.clone_display();
let new_display = new_box_style.clone_display();
// If we were display: none, we may need to trigger animations.
if old_display == Display::None && new_display!= Display::None {
return has_new_animation_style;
}
// If we are becoming display: none, we may need to stop animations.
if old_display!= Display::None && new_display == Display::None {
return self.has_css_animations();
}
false
}
/// Create a SequentialTask for resolving descendants in a SMIL display property
/// animation if the display property changed from none.
#[cfg(feature = "gecko")]
fn handle_display_change_for_smil_if_needed(
&self,
context: &mut StyleContext<Self>,
old_values: Option<&ComputedValues>,
new_values: &ComputedValues,
restyle_hints: RestyleHint
) {
use context::PostAnimationTasks;
if!restyle_hints.intersects(RestyleHint::RESTYLE_SMIL) {
return;
}
if new_values.is_display_property_changed_from_none(old_values) {
// When display value is changed from none to other, we need to
// traverse descendant elements in a subsequent normal
// traversal (we can't traverse them in this animation-only restyle
// since we have no way to know whether the decendants
// need to be traversed at the beginning of the animation-only
// restyle).
let task = ::context::SequentialTask::process_post_animation(
*self,
PostAnimationTasks::DISPLAY_CHANGED_FROM_NONE_FOR_SMIL,
);
context.thread_local.tasks.push(task);
}
}
#[cfg(feature = "gecko")]
fn | (
&self,
context: &mut StyleContext<Self>,
old_values: &mut Option<Arc<ComputedValues>>,
new_values: &mut Arc<ComputedValues>,
restyle_hint: RestyleHint,
important_rules_changed: bool,
) {
use context::UpdateAnimationsTasks;
if context.shared.traversal_flags.for_animation_only() {
self.handle_display_change_for_smil_if_needed(
context,
old_values.as_ref().map(|v| &**v),
new_values,
restyle_hint,
);
return;
}
// Bug 868975: These steps should examine and update the visited styles
// in addition to the unvisited styles.
let mut tasks = UpdateAnimationsTasks::empty();
if self.needs_animations_update(context, old_values.as_ref().map(|s| &**s), new_values) {
tasks.insert(UpdateAnimationsTasks::CSS_ANIMATIONS);
}
let before_change_style = if self.might_need_transitions_update(old_values.as_ref().map(|s| &**s),
new_values) {
let after_change_style = if self.has_css_transitions() {
self.after_change_style(context, new_values)
} else {
None
};
// In order to avoid creating a SequentialTask for transitions which
// may not be updated, we check it per property to make sure Gecko
// side will really update transition.
let needs_transitions_update = {
// We borrow new_values here, so need to add a scope to make
// sure we release it before assigning a new value to it.
let after_change_style_ref =
after_change_style.as_ref().unwrap_or(&new_values);
self.needs_transitions_update(
old_values.as_ref().unwrap(),
after_change_style_ref,
)
};
if needs_transitions_update {
if let Some(values_without_transitions) = after_change_style {
*new_values = values_without_transitions;
}
tasks.insert(UpdateAnimationsTasks::CSS_TRANSITIONS);
// We need to clone old_values into SequentialTask, so we can
// use it later.
old_values.clone()
} else {
None
}
} else {
None
};
if self.has_animations() {
tasks.insert(UpdateAnimationsTasks::EFFECT_PROPERTIES);
if important_rules_changed {
tasks.insert(UpdateAnimationsTasks::CASCADE_RESULTS);
}
if new_values.is_display_property_changed_from_none(old_values.as_ref().map(|s| &**s)) {
tasks.insert(UpdateAnimationsTasks::DISPLAY_CHANGED_FROM_NONE);
}
}
if!tasks.is_empty() {
let task = ::context::SequentialTask::update_animations(*self,
before_change_style,
tasks);
context.thread_local.tasks.push(task);
}
}
#[cfg(feature = "servo")]
fn process_animations(
&self,
context: &mut StyleContext<Self>,
old_values: &mut Option<Arc<ComputedValues>>,
new_values: &mut Arc<ComputedValues>,
_restyle_hint: RestyleHint,
_important_rules_changed: bool,
) {
use animation;
use dom::TNode;
let mut possibly_expired_animations = vec![];
let shared_context = context.shared;
if let Some(ref mut old) = *old_values {
// FIXME(emilio, #20116): This makes no sense.
self.update_animations_for_cascade(
shared_context,
old,
&mut possibly_expired_animations,
&context.thread_local.font_metrics_provider,
);
}
let new_animations_sender = &context.thread_local.new_animations_sender;
let this_opaque = self.as_node().opaque();
// Trigger any present animations if necessary.
animation::maybe_start_animations(
&shared_context,
new_animations_sender,
this_opaque,
&new_values,
);
// Trigger transitions if necessary. This will reset `new_values` back
// to its old value if it did trigger a transition.
if let Some(ref values) = *old_values {
animation::start_transitions_if_applicable(
new_animations_sender,
this_opaque,
&values,
new_values,
&shared_context.timer,
&possibly_expired_animations,
);
}
}
/// Computes and applies non-redundant damage.
fn accumulate_damage_for(
&self,
shared_context: &SharedStyleContext,
damage: &mut RestyleDamage,
old_values: &ComputedValues,
new_values: &ComputedValues,
pseudo: Option<&PseudoElement>,
) -> ChildCascadeRequirement {
debug!("accumulate_damage_for: {:?}", self);
debug_assert!(!shared_context.traversal_flags.contains(TraversalFlags::Forgetful));
let difference =
self.compute_style_difference(old_values, new_values, pseudo);
*damage |= difference.damage;
debug!(" > style difference: {:?}", difference);
// We need to cascade the children in order to ensure the correct
// propagation of inherited computed value flags.
if old_values.flags.maybe_inherited()!= new_values.flags.maybe_inherited() {
debug!(" > flags changed: {:?}!= {:?}", old_values.flags, new_values.flags);
return ChildCascadeRequirement::MustCascadeChildren;
}
match difference.change {
StyleChange::Unchanged => {
return ChildCascadeRequirement::CanSkipCascade
},
StyleChange::Changed { reset_only } => {
// If inherited properties changed, the best we can do is
// cascade the children.
if!reset_only {
return ChildCascadeRequirement::MustCascadeChildren
}
}
}
let old_display = old_values.get_box().clone_display();
let new_display = new_values.get_box().clone_display();
// If we used to be a display: none element, and no longer are,
// our children need to be restyled because they're unstyled.
//
// NOTE(emilio): Gecko has the special-case of -moz-binding, but
// that gets handled on the frame constructor when processing
// the reframe, so no need to handle that here.
if old_display == Display::None && old_display!= new_display {
return ChildCascadeRequirement::MustCascadeChildren
}
// Blockification of children may depend on our display value,
// so we need to actually do the recascade. We could potentially
// do better, but it doesn't seem worth it.
if old_display.is_item_container()!= new_display.is_item_container() {
return ChildCascadeRequirement::MustCascadeChildren
}
// Line break suppression may also be affected if the display
// type changes from ruby to non-ruby.
#[cfg(feature = "gecko")]
{
if old_display.is_ruby_type()!= new_display.is_ruby_type() {
return ChildCascadeRequirement::MustCascadeChildren
}
}
// Children with justify-items: auto may depend on our
// justify-items property value.
//
// Similarly, we could potentially do better, but this really
// seems not common enough to care about.
#[cfg(feature = "gecko")]
{
use values::specified::align::AlignFlags;
let old_justify_items =
old_values.get_position().clone_justify_items();
let new_justify_items =
new_values.get_position().clone_justify_items();
let was_legacy_justify_items =
old_justify_items.computed.0.contains(AlignFlags::LEGACY);
let is_legacy_justify_items =
new_justify_items.computed.0.contains(AlignFlags::LEGACY);
if is_legacy_justify_items!= was_legacy_justify_items {
return ChildCascadeRequirement::MustCascadeChildren;
}
if was_legacy_justify_items &&
old_justify_items.computed!= new_justify_items.computed {
return ChildCascadeRequirement::MustCascadeChildren;
}
}
#[cfg(feature = "servo")]
{
// We may need to set or propagate the CAN_BE_FRAGMENTED bit
// on our children.
if old_values.is_multicol()!= new_values.is_multicol() {
return ChildCascadeRequirement::MustCascadeChildren;
}
}
// We could prove that, if our children don't inherit reset
// properties, we can stop the cascade.
ChildCascadeRequirement::MustCascadeChildrenIfInheritResetStyle
}
// FIXME(emilio, #20116): It's not clear to me that the name of this method
// represents anything of what it does.
//
// Also, this function gets the old style, for some reason I don't really
// get, but the functions called (mainly update_style_for_animation) expects
// the new style, wtf?
#[cfg(feature = "servo")]
fn update_animations_for_cascade(
&self,
context: &SharedStyleContext,
style: &mut Arc<ComputedValues>,
possibly_expired_animations: &mut Vec<::animation::PropertyAnimation>,
font_metrics: &::font_metrics::FontMetricsProvider,
) {
use animation::{self, Animation};
use dom::TNode;
// Finish any expired transitions.
let this_opaque = self.as_node().opaque();
animation::complete_expired_transitions(this_opaque, style, context);
// Merge any running animations into the current style, and cancel them.
let had_running_animations =
context.running_animations.read().get(&this_opaque).is_some();
if!had_running_animations {
return;
}
let mut all_running_animations = context.running_animations.write();
for running_animation in all_running_animations.get_mut(&this_opaque).unwrap() {
// This shouldn't happen frequently, but under some circumstances
// mainly huge load or debug builds, the constellation might be
// delayed in sending the `TickAllAnimations` message to layout.
//
// Thus, we can't assume all the animations have been already
// updated by layout, because other restyle due to script might be
// triggered by layout before the animation tick.
//
// See #12171 and the associated PR for an example where this
// happened while debugging other release panic.
if running_animation.is_expired() {
continue;
}
animation::update_style_for_animation::<Self>(
context,
running_animation,
style,
font_metrics,
);
if let Animation::Transition(_, _, ref frame, _) = *running_animation {
possibly_expired_animations.push(frame.property_animation.clone())
}
}
}
}
| process_animations | identifier_name |
mod.rs | // we try to parse these as windows keycodes
mod keys;
pub use self::keys::Keys as Key;
mod linux;
mod qcode;
#[repr(u32)]
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
pub enum Modifier {
Alt = 0x0001,
Ctrl = 0x0002,
Shift = 0x0004,
Win = 0x0008,
}
const NOREPEAT: u32 = 0x4000;
impl Key {
fn modifier(&self) -> Option<Modifier> {
Some(match *self {
Key::LMenu | Key::RMenu => Modifier::Alt,
Key::LControlKey | Key::RControlKey => Modifier::Ctrl,
Key::LShiftKey | Key::RShiftKey => Modifier::Shift,
Key::LWin | Key::RWin => Modifier::Win,
_ => return None,
})
}
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct KeyBinding {
modifiers: Vec<Modifier>,
no_repeat: bool, // FIXME: implement this
key: Key,
}
impl KeyBinding {
pub fn new(modifiers: Vec<Modifier>, key: Key, no_repeat: bool) -> KeyBinding {
KeyBinding { modifiers, no_repeat, key }
}
pub fn matches(&self, modifiers: &[Modifier], key: Key) -> bool {
key == self.key && self.modifiers.iter().all(|x| modifiers.contains(x))
}
pub fn to_windows(&self) -> (u32, u32) {
let base = if self.no_repeat { NOREPEAT } else { 0 };
(self.modifiers.iter().fold(base, |sum, &x| (sum | (x as u32))), self.key as u32)
}
}
pub struct KeyResolution {
pub hotkeys: Vec<usize>,
pub qcode: Option<&'static str>,
}
pub struct KeyboardState<'a> {
modifiers: Vec<Modifier>,
bindings: &'a [KeyBinding],
}
impl<'a> KeyboardState<'a> {
pub fn new(bindings: &'a [KeyBinding]) -> KeyboardState {
KeyboardState {
modifiers: Vec::new(),
bindings,
}
}
pub fn input_linux(&mut self, code: u32, down: bool) -> Option<KeyResolution> {
linux::key_convert(code).map(|k| {
let mut bindings = Vec::new();
if let Some(m) = k.modifier() {
if down | else {
if let Some(i) = self.modifiers.iter().position(|&x| x == m) {
self.modifiers.swap_remove(i);
}
}
} else if down {
bindings.extend(self.bindings.iter().enumerate()
.filter(|&(_, b)| b.matches(&self.modifiers, k))
.map(|(i, _)| i));
}
KeyResolution {
hotkeys: bindings,
qcode: qcode::key_convert(k),
}
})
}
}
| {
if !self.modifiers.contains(&m) {
self.modifiers.push(m);
}
} | conditional_block |
mod.rs | // we try to parse these as windows keycodes
mod keys;
pub use self::keys::Keys as Key;
mod linux;
mod qcode;
#[repr(u32)]
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
pub enum Modifier {
Alt = 0x0001,
Ctrl = 0x0002,
Shift = 0x0004,
Win = 0x0008,
}
const NOREPEAT: u32 = 0x4000;
impl Key {
fn modifier(&self) -> Option<Modifier> {
Some(match *self {
Key::LMenu | Key::RMenu => Modifier::Alt,
Key::LControlKey | Key::RControlKey => Modifier::Ctrl,
Key::LShiftKey | Key::RShiftKey => Modifier::Shift,
Key::LWin | Key::RWin => Modifier::Win,
_ => return None,
})
}
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct KeyBinding {
modifiers: Vec<Modifier>,
no_repeat: bool, // FIXME: implement this
key: Key,
}
impl KeyBinding {
pub fn new(modifiers: Vec<Modifier>, key: Key, no_repeat: bool) -> KeyBinding {
KeyBinding { modifiers, no_repeat, key }
}
pub fn matches(&self, modifiers: &[Modifier], key: Key) -> bool {
key == self.key && self.modifiers.iter().all(|x| modifiers.contains(x))
}
pub fn to_windows(&self) -> (u32, u32) {
let base = if self.no_repeat { NOREPEAT } else { 0 };
(self.modifiers.iter().fold(base, |sum, &x| (sum | (x as u32))), self.key as u32)
}
}
pub struct KeyResolution {
pub hotkeys: Vec<usize>,
pub qcode: Option<&'static str>,
}
pub struct KeyboardState<'a> {
modifiers: Vec<Modifier>,
bindings: &'a [KeyBinding],
}
impl<'a> KeyboardState<'a> {
pub fn new(bindings: &'a [KeyBinding]) -> KeyboardState {
KeyboardState {
modifiers: Vec::new(),
bindings,
}
}
pub fn input_linux(&mut self, code: u32, down: bool) -> Option<KeyResolution> {
linux::key_convert(code).map(|k| {
let mut bindings = Vec::new();
if let Some(m) = k.modifier() {
if down {
if!self.modifiers.contains(&m) {
self.modifiers.push(m);
}
} else {
if let Some(i) = self.modifiers.iter().position(|&x| x == m) {
self.modifiers.swap_remove(i);
} | }
} else if down {
bindings.extend(self.bindings.iter().enumerate()
.filter(|&(_, b)| b.matches(&self.modifiers, k))
.map(|(i, _)| i));
}
KeyResolution {
hotkeys: bindings,
qcode: qcode::key_convert(k),
}
})
}
} | random_line_split |
|
mod.rs | // we try to parse these as windows keycodes
mod keys;
pub use self::keys::Keys as Key;
mod linux;
mod qcode;
#[repr(u32)]
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
pub enum Modifier {
Alt = 0x0001,
Ctrl = 0x0002,
Shift = 0x0004,
Win = 0x0008,
}
const NOREPEAT: u32 = 0x4000;
impl Key {
fn modifier(&self) -> Option<Modifier> {
Some(match *self {
Key::LMenu | Key::RMenu => Modifier::Alt,
Key::LControlKey | Key::RControlKey => Modifier::Ctrl,
Key::LShiftKey | Key::RShiftKey => Modifier::Shift,
Key::LWin | Key::RWin => Modifier::Win,
_ => return None,
})
}
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct KeyBinding {
modifiers: Vec<Modifier>,
no_repeat: bool, // FIXME: implement this
key: Key,
}
impl KeyBinding {
pub fn new(modifiers: Vec<Modifier>, key: Key, no_repeat: bool) -> KeyBinding {
KeyBinding { modifiers, no_repeat, key }
}
pub fn matches(&self, modifiers: &[Modifier], key: Key) -> bool {
key == self.key && self.modifiers.iter().all(|x| modifiers.contains(x))
}
pub fn to_windows(&self) -> (u32, u32) {
let base = if self.no_repeat { NOREPEAT } else { 0 };
(self.modifiers.iter().fold(base, |sum, &x| (sum | (x as u32))), self.key as u32)
}
}
pub struct KeyResolution {
pub hotkeys: Vec<usize>,
pub qcode: Option<&'static str>,
}
pub struct KeyboardState<'a> {
modifiers: Vec<Modifier>,
bindings: &'a [KeyBinding],
}
impl<'a> KeyboardState<'a> {
pub fn | (bindings: &'a [KeyBinding]) -> KeyboardState {
KeyboardState {
modifiers: Vec::new(),
bindings,
}
}
pub fn input_linux(&mut self, code: u32, down: bool) -> Option<KeyResolution> {
linux::key_convert(code).map(|k| {
let mut bindings = Vec::new();
if let Some(m) = k.modifier() {
if down {
if!self.modifiers.contains(&m) {
self.modifiers.push(m);
}
} else {
if let Some(i) = self.modifiers.iter().position(|&x| x == m) {
self.modifiers.swap_remove(i);
}
}
} else if down {
bindings.extend(self.bindings.iter().enumerate()
.filter(|&(_, b)| b.matches(&self.modifiers, k))
.map(|(i, _)| i));
}
KeyResolution {
hotkeys: bindings,
qcode: qcode::key_convert(k),
}
})
}
}
| new | identifier_name |
lib.rs | // Copyright 2016 Google Inc. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#![feature(plugin_registrar)]
#![feature(slice_patterns, box_syntax, rustc_private)]
#[macro_use(walk_list)]
extern crate syntax;
extern crate rustc_serialize;
// Load rustc as a plugin to get macros.
#[macro_use]
extern crate rustc;
extern crate rustc_plugin;
#[macro_use]
extern crate log;
mod kythe;
mod pass;
mod visitor;
use kythe::writer::JsonEntryWriter;
use rustc_plugin::Registry;
use rustc::lint::LateLintPassObject;
// Informs the compiler of the existence and implementation of our plugin.
#[plugin_registrar]
pub fn | (reg: &mut Registry) {
let pass = box pass::KytheLintPass::new(box JsonEntryWriter);
reg.register_late_lint_pass(pass as LateLintPassObject);
}
| plugin_registrar | identifier_name |
lib.rs | // Copyright 2016 Google Inc. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#![feature(plugin_registrar)]
#![feature(slice_patterns, box_syntax, rustc_private)]
#[macro_use(walk_list)]
extern crate syntax; |
// Load rustc as a plugin to get macros.
#[macro_use]
extern crate rustc;
extern crate rustc_plugin;
#[macro_use]
extern crate log;
mod kythe;
mod pass;
mod visitor;
use kythe::writer::JsonEntryWriter;
use rustc_plugin::Registry;
use rustc::lint::LateLintPassObject;
// Informs the compiler of the existence and implementation of our plugin.
#[plugin_registrar]
pub fn plugin_registrar(reg: &mut Registry) {
let pass = box pass::KytheLintPass::new(box JsonEntryWriter);
reg.register_late_lint_pass(pass as LateLintPassObject);
} | extern crate rustc_serialize; | random_line_split |
lib.rs | // Copyright 2016 Google Inc. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#![feature(plugin_registrar)]
#![feature(slice_patterns, box_syntax, rustc_private)]
#[macro_use(walk_list)]
extern crate syntax;
extern crate rustc_serialize;
// Load rustc as a plugin to get macros.
#[macro_use]
extern crate rustc;
extern crate rustc_plugin;
#[macro_use]
extern crate log;
mod kythe;
mod pass;
mod visitor;
use kythe::writer::JsonEntryWriter;
use rustc_plugin::Registry;
use rustc::lint::LateLintPassObject;
// Informs the compiler of the existence and implementation of our plugin.
#[plugin_registrar]
pub fn plugin_registrar(reg: &mut Registry) | {
let pass = box pass::KytheLintPass::new(box JsonEntryWriter);
reg.register_late_lint_pass(pass as LateLintPassObject);
} | identifier_body |
|
issue-24081.rs | // Copyright 2015 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
use std::ops::Add;
use std::ops::Sub;
use std::ops::Mul;
use std::ops::Div;
use std::ops::Rem;
type Add = bool; //~ ERROR the name `Add` is defined multiple times
//~| `Add` redefined here
struct Sub { x: f32 } //~ ERROR the name `Sub` is defined multiple times
//~| `Sub` redefined here
enum Mul { A, B } //~ ERROR the name `Mul` is defined multiple times
//~| `Mul` redefined here
mod Div { } //~ ERROR the name `Div` is defined multiple times
//~| `Div` redefined here
trait Rem { } //~ ERROR the name `Rem` is defined multiple times
//~| `Rem` redefined here
fn | () {}
| main | identifier_name |
issue-24081.rs | // Copyright 2015 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
| use std::ops::Mul;
use std::ops::Div;
use std::ops::Rem;
type Add = bool; //~ ERROR the name `Add` is defined multiple times
//~| `Add` redefined here
struct Sub { x: f32 } //~ ERROR the name `Sub` is defined multiple times
//~| `Sub` redefined here
enum Mul { A, B } //~ ERROR the name `Mul` is defined multiple times
//~| `Mul` redefined here
mod Div { } //~ ERROR the name `Div` is defined multiple times
//~| `Div` redefined here
trait Rem { } //~ ERROR the name `Rem` is defined multiple times
//~| `Rem` redefined here
fn main() {} | use std::ops::Add;
use std::ops::Sub; | random_line_split |
nullable-pointer-size.rs | // Copyright 2013 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
#![feature(macro_rules)]
use std::mem;
use std::gc::Gc;
enum E<T> { Thing(int, T), Nothing((), ((), ()), [i8,..0]) }
struct S<T>(int, T);
// These are macros so we get useful assert messages.
macro_rules! check_option {
($T:ty) => {
assert_eq!(mem::size_of::<Option<$T>>(), mem::size_of::<$T>());
}
}
macro_rules! check_fancy {
($T:ty) => {
assert_eq!(mem::size_of::<E<$T>>(), mem::size_of::<S<$T>>());
}
}
macro_rules! check_type { | check_option!($T);
check_fancy!($T);
}}
}
pub fn main() {
check_type!(&'static int);
check_type!(Box<int>);
check_type!(Gc<int>);
check_type!(extern fn());
} | ($T:ty) => {{ | random_line_split |
nullable-pointer-size.rs | // Copyright 2013 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
#![feature(macro_rules)]
use std::mem;
use std::gc::Gc;
enum E<T> { Thing(int, T), Nothing((), ((), ()), [i8,..0]) }
struct S<T>(int, T);
// These are macros so we get useful assert messages.
macro_rules! check_option {
($T:ty) => {
assert_eq!(mem::size_of::<Option<$T>>(), mem::size_of::<$T>());
}
}
macro_rules! check_fancy {
($T:ty) => {
assert_eq!(mem::size_of::<E<$T>>(), mem::size_of::<S<$T>>());
}
}
macro_rules! check_type {
($T:ty) => {{
check_option!($T);
check_fancy!($T);
}}
}
pub fn | () {
check_type!(&'static int);
check_type!(Box<int>);
check_type!(Gc<int>);
check_type!(extern fn());
}
| main | identifier_name |
unboxed-closures-call-sugar-autoderef.rs | // Copyright 2012 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
// Test that the call operator autoderefs when calling a bounded type parameter.
#![feature(unboxed_closures)]
use std::ops::FnMut;
fn call_with_2<F>(x: &mut F) -> isize
where F : FnMut(isize) -> isize
|
pub fn main() {
let z = call_with_2(&mut |x| x - 22);
assert_eq!(z, -20);
}
| {
x(2) // look ma, no `*`
} | identifier_body |
unboxed-closures-call-sugar-autoderef.rs | // Copyright 2012 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
// Test that the call operator autoderefs when calling a bounded type parameter.
#![feature(unboxed_closures)]
use std::ops::FnMut;
fn call_with_2<F>(x: &mut F) -> isize
where F : FnMut(isize) -> isize
{
x(2) // look ma, no `*`
}
pub fn | () {
let z = call_with_2(&mut |x| x - 22);
assert_eq!(z, -20);
}
| main | identifier_name |
unboxed-closures-call-sugar-autoderef.rs | // Copyright 2012 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
// Test that the call operator autoderefs when calling a bounded type parameter.
#![feature(unboxed_closures)]
use std::ops::FnMut;
fn call_with_2<F>(x: &mut F) -> isize
where F : FnMut(isize) -> isize
{
x(2) // look ma, no `*`
} | } |
pub fn main() {
let z = call_with_2(&mut |x| x - 22);
assert_eq!(z, -20); | random_line_split |
aarch64.rs | use dynasmrt::{dynasm, DynasmApi, DynasmLabelApi};
use std::{io, slice, mem};
use std::io::Write;
fn main() {
let mut ops = dynasmrt::aarch64::Assembler::new().unwrap();
let string = "Hello World!";
dynasm!(ops
;.arch aarch64
; ->hello:
;.bytes string.as_bytes()
;.align 4
; ->print:
;.qword print as _
);
let hello = ops.offset();
dynasm!(ops
;.arch aarch64
; adr x0, ->hello
; movz x1, string.len() as u32
; ldr x9, ->print
; str x30, [sp, #-16]!
; blr x9
; ldr x30, [sp], #16
; ret
);
let buf = ops.finalize().unwrap();
let hello_fn: extern "C" fn() -> bool = unsafe { mem::transmute(buf.ptr(hello)) };
assert!(hello_fn());
}
pub extern "C" fn print(buffer: *const u8, length: u64) -> bool | {
io::stdout()
.write_all(unsafe { slice::from_raw_parts(buffer, length as usize) })
.is_ok()
} | identifier_body |
|
aarch64.rs | use dynasmrt::{dynasm, DynasmApi, DynasmLabelApi};
use std::{io, slice, mem};
use std::io::Write;
fn main() {
let mut ops = dynasmrt::aarch64::Assembler::new().unwrap();
let string = "Hello World!";
dynasm!(ops
;.arch aarch64
; ->hello:
;.bytes string.as_bytes()
;.align 4
; ->print:
;.qword print as _
);
let hello = ops.offset();
dynasm!(ops
;.arch aarch64
; adr x0, ->hello
; movz x1, string.len() as u32
; ldr x9, ->print
; str x30, [sp, #-16]!
; blr x9
; ldr x30, [sp], #16
; ret
);
let buf = ops.finalize().unwrap();
let hello_fn: extern "C" fn() -> bool = unsafe { mem::transmute(buf.ptr(hello)) };
assert!(hello_fn());
}
pub extern "C" fn | (buffer: *const u8, length: u64) -> bool {
io::stdout()
.write_all(unsafe { slice::from_raw_parts(buffer, length as usize) })
.is_ok()
}
| print | identifier_name |
aarch64.rs | use dynasmrt::{dynasm, DynasmApi, DynasmLabelApi};
use std::{io, slice, mem};
use std::io::Write;
fn main() {
let mut ops = dynasmrt::aarch64::Assembler::new().unwrap();
let string = "Hello World!";
dynasm!(ops
;.arch aarch64
; ->hello:
;.bytes string.as_bytes()
;.align 4
; ->print:
;.qword print as _
);
let hello = ops.offset();
dynasm!(ops
;.arch aarch64
; adr x0, ->hello
; movz x1, string.len() as u32
; ldr x9, ->print
; str x30, [sp, #-16]!
; blr x9
; ldr x30, [sp], #16
; ret
);
| }
pub extern "C" fn print(buffer: *const u8, length: u64) -> bool {
io::stdout()
.write_all(unsafe { slice::from_raw_parts(buffer, length as usize) })
.is_ok()
} | let buf = ops.finalize().unwrap();
let hello_fn: extern "C" fn() -> bool = unsafe { mem::transmute(buf.ptr(hello)) };
assert!(hello_fn()); | random_line_split |
store.rs | pub struct StoreStats {
pub num_keys: u64,
pub total_memory_in_bytes: u64,
}
impl StoreStats {
pub fn new() -> StoreStats {
StoreStats {
num_keys: 0,
total_memory_in_bytes: 0,
}
}
}
pub trait ValueStore<K, V> {
fn get(&self, key: &K) -> Option<&V>;
fn set(&mut self, key: K, value: V);
fn delete(&mut self, key: &K) -> bool;
fn delete_many(&mut self, keys: &Vec<K>);
fn clear(&mut self);
fn stats(&self) -> &StoreStats;
}
pub trait EvictionPolicy<K, V> {
// Metadata management
fn update_metadata_on_get(&mut self, key: K);
fn update_metadata_on_set(&mut self, key: K, value: V);
fn delete_metadata(&mut self, keys: &Vec<K>);
fn clear_metadata(&mut self);
// Eviction polict logic
fn should_evict_keys(&self, store_stats: &StoreStats) -> bool;
fn choose_keys_to_evict(&self) -> Vec<K>;
}
pub struct Store<K: Clone,
V: Clone,
KVStore: ValueStore<K, V>,
EvPolicy: EvictionPolicy<K, V>>
{
value_store: KVStore,
eviction_policy: EvPolicy,
// Hack to allow this struct to take the ValueStore and EvictionPolicy
// traits and constrain them to having the same types for the keys (K) and
// the values (V).
// TODO: find a better way to achieve this
__hack1: Option<K>,
__hack2: Option<V>,
}
impl<K: Clone,
V: Clone,
KVStore: ValueStore<K, V>,
EvPolicy: EvictionPolicy<K, V>>
Store<K, V, KVStore, EvPolicy>
{
pub fn new(value_store: KVStore,
eviction_policy: EvPolicy) -> Store<K, V, KVStore, EvPolicy>
{
Store {
value_store: value_store,
eviction_policy: eviction_policy,
__hack1: None,
__hack2: None,
}
}
pub fn get(&mut self, key: &K) -> Option<&V> |
pub fn set(&mut self, key: K, value: V) {
self.evict_keys_if_necessary();
self.eviction_policy.update_metadata_on_set(key.clone(), value.clone());
self.value_store.set(key, value);
}
fn evict_keys_if_necessary(&mut self) {
let should_evict = self.eviction_policy.should_evict_keys(
self.value_store.stats());
if should_evict {
let keys_to_evict = self.eviction_policy.choose_keys_to_evict();
self.value_store.delete_many(&keys_to_evict);
self.eviction_policy.delete_metadata(&keys_to_evict);
}
}
}
| {
self.evict_keys_if_necessary();
self.eviction_policy.update_metadata_on_get(key.clone());
self.value_store.get(key)
} | identifier_body |
store.rs | pub struct StoreStats {
pub num_keys: u64,
pub total_memory_in_bytes: u64,
}
impl StoreStats {
pub fn new() -> StoreStats {
StoreStats {
num_keys: 0,
total_memory_in_bytes: 0,
}
}
}
pub trait ValueStore<K, V> {
fn get(&self, key: &K) -> Option<&V>;
fn set(&mut self, key: K, value: V);
fn delete(&mut self, key: &K) -> bool;
fn delete_many(&mut self, keys: &Vec<K>);
fn clear(&mut self);
fn stats(&self) -> &StoreStats;
}
pub trait EvictionPolicy<K, V> {
// Metadata management
fn update_metadata_on_get(&mut self, key: K);
fn update_metadata_on_set(&mut self, key: K, value: V);
fn delete_metadata(&mut self, keys: &Vec<K>);
fn clear_metadata(&mut self);
// Eviction polict logic
fn should_evict_keys(&self, store_stats: &StoreStats) -> bool;
fn choose_keys_to_evict(&self) -> Vec<K>;
}
pub struct Store<K: Clone,
V: Clone,
KVStore: ValueStore<K, V>,
EvPolicy: EvictionPolicy<K, V>>
{
value_store: KVStore,
eviction_policy: EvPolicy,
// Hack to allow this struct to take the ValueStore and EvictionPolicy
// traits and constrain them to having the same types for the keys (K) and
// the values (V).
// TODO: find a better way to achieve this
__hack1: Option<K>,
__hack2: Option<V>,
}
impl<K: Clone,
V: Clone,
KVStore: ValueStore<K, V>,
EvPolicy: EvictionPolicy<K, V>>
Store<K, V, KVStore, EvPolicy>
{
pub fn new(value_store: KVStore,
eviction_policy: EvPolicy) -> Store<K, V, KVStore, EvPolicy>
{
Store {
value_store: value_store,
eviction_policy: eviction_policy,
__hack1: None,
__hack2: None,
}
}
pub fn get(&mut self, key: &K) -> Option<&V> {
self.evict_keys_if_necessary();
self.eviction_policy.update_metadata_on_get(key.clone());
self.value_store.get(key)
}
pub fn set(&mut self, key: K, value: V) {
self.evict_keys_if_necessary();
self.eviction_policy.update_metadata_on_set(key.clone(), value.clone());
self.value_store.set(key, value);
}
fn evict_keys_if_necessary(&mut self) {
let should_evict = self.eviction_policy.should_evict_keys(
self.value_store.stats());
if should_evict |
}
}
| {
let keys_to_evict = self.eviction_policy.choose_keys_to_evict();
self.value_store.delete_many(&keys_to_evict);
self.eviction_policy.delete_metadata(&keys_to_evict);
} | conditional_block |
store.rs | pub struct StoreStats {
pub num_keys: u64,
pub total_memory_in_bytes: u64,
}
impl StoreStats {
pub fn new() -> StoreStats {
StoreStats {
num_keys: 0,
total_memory_in_bytes: 0,
}
} | fn set(&mut self, key: K, value: V);
fn delete(&mut self, key: &K) -> bool;
fn delete_many(&mut self, keys: &Vec<K>);
fn clear(&mut self);
fn stats(&self) -> &StoreStats;
}
pub trait EvictionPolicy<K, V> {
// Metadata management
fn update_metadata_on_get(&mut self, key: K);
fn update_metadata_on_set(&mut self, key: K, value: V);
fn delete_metadata(&mut self, keys: &Vec<K>);
fn clear_metadata(&mut self);
// Eviction polict logic
fn should_evict_keys(&self, store_stats: &StoreStats) -> bool;
fn choose_keys_to_evict(&self) -> Vec<K>;
}
pub struct Store<K: Clone,
V: Clone,
KVStore: ValueStore<K, V>,
EvPolicy: EvictionPolicy<K, V>>
{
value_store: KVStore,
eviction_policy: EvPolicy,
// Hack to allow this struct to take the ValueStore and EvictionPolicy
// traits and constrain them to having the same types for the keys (K) and
// the values (V).
// TODO: find a better way to achieve this
__hack1: Option<K>,
__hack2: Option<V>,
}
impl<K: Clone,
V: Clone,
KVStore: ValueStore<K, V>,
EvPolicy: EvictionPolicy<K, V>>
Store<K, V, KVStore, EvPolicy>
{
pub fn new(value_store: KVStore,
eviction_policy: EvPolicy) -> Store<K, V, KVStore, EvPolicy>
{
Store {
value_store: value_store,
eviction_policy: eviction_policy,
__hack1: None,
__hack2: None,
}
}
pub fn get(&mut self, key: &K) -> Option<&V> {
self.evict_keys_if_necessary();
self.eviction_policy.update_metadata_on_get(key.clone());
self.value_store.get(key)
}
pub fn set(&mut self, key: K, value: V) {
self.evict_keys_if_necessary();
self.eviction_policy.update_metadata_on_set(key.clone(), value.clone());
self.value_store.set(key, value);
}
fn evict_keys_if_necessary(&mut self) {
let should_evict = self.eviction_policy.should_evict_keys(
self.value_store.stats());
if should_evict {
let keys_to_evict = self.eviction_policy.choose_keys_to_evict();
self.value_store.delete_many(&keys_to_evict);
self.eviction_policy.delete_metadata(&keys_to_evict);
}
}
} | }
pub trait ValueStore<K, V> {
fn get(&self, key: &K) -> Option<&V>; | random_line_split |
store.rs | pub struct StoreStats {
pub num_keys: u64,
pub total_memory_in_bytes: u64,
}
impl StoreStats {
pub fn new() -> StoreStats {
StoreStats {
num_keys: 0,
total_memory_in_bytes: 0,
}
}
}
pub trait ValueStore<K, V> {
fn get(&self, key: &K) -> Option<&V>;
fn set(&mut self, key: K, value: V);
fn delete(&mut self, key: &K) -> bool;
fn delete_many(&mut self, keys: &Vec<K>);
fn clear(&mut self);
fn stats(&self) -> &StoreStats;
}
pub trait EvictionPolicy<K, V> {
// Metadata management
fn update_metadata_on_get(&mut self, key: K);
fn update_metadata_on_set(&mut self, key: K, value: V);
fn delete_metadata(&mut self, keys: &Vec<K>);
fn clear_metadata(&mut self);
// Eviction polict logic
fn should_evict_keys(&self, store_stats: &StoreStats) -> bool;
fn choose_keys_to_evict(&self) -> Vec<K>;
}
pub struct Store<K: Clone,
V: Clone,
KVStore: ValueStore<K, V>,
EvPolicy: EvictionPolicy<K, V>>
{
value_store: KVStore,
eviction_policy: EvPolicy,
// Hack to allow this struct to take the ValueStore and EvictionPolicy
// traits and constrain them to having the same types for the keys (K) and
// the values (V).
// TODO: find a better way to achieve this
__hack1: Option<K>,
__hack2: Option<V>,
}
impl<K: Clone,
V: Clone,
KVStore: ValueStore<K, V>,
EvPolicy: EvictionPolicy<K, V>>
Store<K, V, KVStore, EvPolicy>
{
pub fn new(value_store: KVStore,
eviction_policy: EvPolicy) -> Store<K, V, KVStore, EvPolicy>
{
Store {
value_store: value_store,
eviction_policy: eviction_policy,
__hack1: None,
__hack2: None,
}
}
pub fn | (&mut self, key: &K) -> Option<&V> {
self.evict_keys_if_necessary();
self.eviction_policy.update_metadata_on_get(key.clone());
self.value_store.get(key)
}
pub fn set(&mut self, key: K, value: V) {
self.evict_keys_if_necessary();
self.eviction_policy.update_metadata_on_set(key.clone(), value.clone());
self.value_store.set(key, value);
}
fn evict_keys_if_necessary(&mut self) {
let should_evict = self.eviction_policy.should_evict_keys(
self.value_store.stats());
if should_evict {
let keys_to_evict = self.eviction_policy.choose_keys_to_evict();
self.value_store.delete_many(&keys_to_evict);
self.eviction_policy.delete_metadata(&keys_to_evict);
}
}
}
| get | identifier_name |
ddraw.rs | // Licensed under the Apache License, Version 2.0
// <LICENSE-APACHE or http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your option.
// All files in the project carrying such notice may not be copied, modified, or distributed
// except according to those terms.
DEFINE_GUID!{CLSID_DirectDraw,
0xd7b70ee0, 0x4340, 0x11cf, 0xb0, 0x63, 0x00, 0x20, 0xaf, 0xc2, 0xcd, 0x35}
DEFINE_GUID!{CLSID_DirectDraw7,
0x3c305196, 0x50db, 0x11d3, 0x9c, 0xfe, 0x00, 0xc0, 0x4f, 0xd9, 0x30, 0xc5}
DEFINE_GUID!{CLSID_DirectDrawClipper,
0x593817a0, 0x7db3, 0x11cf, 0xa2, 0xde, 0x00, 0xaa, 0x00, 0xb9, 0x33, 0x56}
DEFINE_GUID!{IID_IDirectDraw,
0x6c14db80, 0xa733, 0x11ce, 0xa5, 0x21, 0x00, 0x20, 0xaf, 0x0b, 0xe5, 0x60}
DEFINE_GUID!{IID_IDirectDraw2,
0xb3a6f3e0, 0x2b43, 0x11cf, 0xa2, 0xde, 0x00, 0xaa, 0x00, 0xb9, 0x33, 0x56}
DEFINE_GUID!{IID_IDirectDraw4,
0x9c59509a, 0x39bd, 0x11d1, 0x8c, 0x4a, 0x00, 0xc0, 0x4f, 0xd9, 0x30, 0xc5}
DEFINE_GUID!{IID_IDirectDraw7,
0x15e65ec0, 0x3b9c, 0x11d2, 0xb9, 0x2f, 0x00, 0x60, 0x97, 0x97, 0xea, 0x5b}
DEFINE_GUID!{IID_IDirectDrawSurface,
0x6c14db81, 0xa733, 0x11ce, 0xa5, 0x21, 0x00, 0x20, 0xaf, 0x0b, 0xe5, 0x60} | 0xda044e00, 0x69b2, 0x11d0, 0xa1, 0xd5, 0x00, 0xaa, 0x00, 0xb8, 0xdf, 0xbb}
DEFINE_GUID!{IID_IDirectDrawSurface4,
0x0b2b8630, 0xad35, 0x11d0, 0x8e, 0xa6, 0x00, 0x60, 0x97, 0x97, 0xea, 0x5b}
DEFINE_GUID!{IID_IDirectDrawSurface7,
0x06675a80, 0x3b9b, 0x11d2, 0xb9, 0x2f, 0x00, 0x60, 0x97, 0x97, 0xea, 0x5b}
DEFINE_GUID!{IID_IDirectDrawPalette,
0x6c14db84, 0xa733, 0x11ce, 0xa5, 0x21, 0x00, 0x20, 0xaf, 0x0b, 0xe5, 0x60}
DEFINE_GUID!{IID_IDirectDrawClipper,
0x6c14db85, 0xa733, 0x11ce, 0xa5, 0x21, 0x00, 0x20, 0xaf, 0x0b, 0xe5, 0x60}
DEFINE_GUID!{IID_IDirectDrawColorControl,
0x4b9f0ee0, 0x0d7e, 0x11d0, 0x9b, 0x06, 0x00, 0xa0, 0xc9, 0x03, 0xa3, 0xb8}
DEFINE_GUID!{IID_IDirectDrawGammaControl,
0x69c11c3e, 0xb46b, 0x11d1, 0xad, 0x7a, 0x00, 0xc0, 0x4f, 0xc2, 0x9b, 0x4e} | DEFINE_GUID!{IID_IDirectDrawSurface2,
0x57805885, 0x6eec, 0x11cf, 0x94, 0x41, 0xa8, 0x23, 0x03, 0xc1, 0x0e, 0x27}
DEFINE_GUID!{IID_IDirectDrawSurface3, | random_line_split |
mod.rs | // Copyright 2013-2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
//! Collection types.
//!
//! Rust's standard collection library provides efficient implementations of the most common
//! general purpose programming data structures. By using the standard implementations,
//! it should be possible for two libraries to communicate without significant data conversion.
//!
//! To get this out of the way: you should probably just use `Vec` or `HashMap`. These two
//! collections cover most use cases for generic data storage and processing. They are
//! exceptionally good at doing what they do. All the other collections in the standard
//! library have specific use cases where they are the optimal choice, but these cases are
//! borderline *niche* in comparison. Even when `Vec` and `HashMap` are technically suboptimal,
//! they're probably a good enough choice to get started.
//!
//! Rust's collections can be grouped into four major categories:
//!
//! * Sequences: `Vec`, `VecDeque`, `LinkedList`, `BitVec`
//! * Maps: `HashMap`, `BTreeMap`, `VecMap`
//! * Sets: `HashSet`, `BTreeSet`, `BitSet`
//! * Misc: `BinaryHeap`
//!
//! # When Should You Use Which Collection?
//!
//! These are fairly high-level and quick break-downs of when each collection should be
//! considered. Detailed discussions of strengths and weaknesses of individual collections
//! can be found on their own documentation pages.
//!
//! ### Use a `Vec` when:
//! * You want to collect items up to be processed or sent elsewhere later, and don't care about
//! any properties of the actual values being stored.
//! * You want a sequence of elements in a particular order, and will only be appending to
//! (or near) the end.
//! * You want a stack.
//! * You want a resizable array.
//! * You want a heap-allocated array.
//!
//! ### Use a `VecDeque` when:
//! * You want a `Vec` that supports efficient insertion at both ends of the sequence.
//! * You want a queue.
//! * You want a double-ended queue (deque).
//!
//! ### Use a `LinkedList` when:
//! * You want a `Vec` or `VecDeque` of unknown size, and can't tolerate amortization.
//! * You want to efficiently split and append lists.
//! * You are *absolutely* certain you *really*, *truly*, want a doubly linked list.
//!
//! ### Use a `HashMap` when:
//! * You want to associate arbitrary keys with an arbitrary value.
//! * You want a cache.
//! * You want a map, with no extra functionality.
//!
//! ### Use a `BTreeMap` when:
//! * You're interested in what the smallest or largest key-value pair is.
//! * You want to find the largest or smallest key that is smaller or larger than something
//! * You want to be able to get all of the entries in order on-demand.
//! * You want a sorted map.
//!
//! ### Use a `VecMap` when:
//! * You want a `HashMap` but with known to be small `usize` keys.
//! * You want a `BTreeMap`, but with known to be small `usize` keys.
//!
//! ### Use the `Set` variant of any of these `Map`s when:
//! * You just want to remember which keys you've seen.
//! * There is no meaningful value to associate with your keys.
//! * You just want a set.
//!
//! ### Use a `BitVec` when:
//! * You want to store an unbounded number of booleans in a small space.
//! * You want a bit vector.
//!
//! ### Use a `BitSet` when:
//! * You want a `BitVec`, but want `Set` properties
//!
//! ### Use a `BinaryHeap` when:
//! * You want to store a bunch of elements, but only ever want to process the "biggest"
//! or "most important" one at any given time.
//! * You want a priority queue.
//!
//! # Performance
//!
//! Choosing the right collection for the job requires an understanding of what each collection
//! is good at. Here we briefly summarize the performance of different collections for certain
//! important operations. For further details, see each type's documentation, and note that the
//! names of actual methods may differ from the tables below on certain collections.
//!
//! Throughout the documentation, we will follow a few conventions. For all operations,
//! the collection's size is denoted by n. If another collection is involved in the operation, it
//! contains m elements. Operations which have an *amortized* cost are suffixed with a `*`.
//! Operations with an *expected* cost are suffixed with a `~`.
//!
//! All amortized costs are for the potential need to resize when capacity is exhausted.
//! If a resize occurs it will take O(n) time. Our collections never automatically shrink,
//! so removal operations aren't amortized. Over a sufficiently large series of
//! operations, the average cost per operation will deterministically equal the given cost.
//!
//! Only HashMap has expected costs, due to the probabilistic nature of hashing. It is
//! theoretically possible, though very unlikely, for HashMap to experience worse performance.
//!
//! ## Sequences
//!
//! | | get(i) | insert(i) | remove(i) | append | split_off(i) |
//! |--------------|----------------|-----------------|----------------|--------|----------------|
//! | Vec | O(1) | O(n-i)* | O(n-i) | O(m)* | O(n-i) |
//! | VecDeque | O(1) | O(min(i, n-i))* | O(min(i, n-i)) | O(m)* | O(min(i, n-i)) |
//! | LinkedList | O(min(i, n-i)) | O(min(i, n-i)) | O(min(i, n-i)) | O(1) | O(min(i, n-i)) |
//! | BitVec | O(1) | O(n-i)* | O(n-i) | O(m)* | O(n-i) |
//!
//! Note that where ties occur, Vec is generally going to be faster than VecDeque, and VecDeque
//! is generally going to be faster than LinkedList. BitVec is not a general purpose collection, and
//! therefore cannot reasonably be compared.
//!
//! ## Maps
//!
//! For Sets, all operations have the cost of the equivalent Map operation. For BitSet,
//! refer to VecMap.
//!
//! | | get | insert | remove | predecessor |
//! |----------|-----------|----------|----------|-------------|
//! | HashMap | O(1)~ | O(1)~* | O(1)~ | N/A |
//! | BTreeMap | O(log n) | O(log n) | O(log n) | O(log n) |
//! | VecMap | O(1) | O(1)? | O(1) | O(n) |
//!
//! Note that VecMap is *incredibly* inefficient in terms of space. The O(1) insertion time
//! assumes space for the element is already allocated. Otherwise, a large key may require a
//! massive reallocation, with no direct relation to the number of elements in the collection.
//! VecMap should only be seriously considered for small keys.
//!
//! Note also that BTreeMap's precise preformance depends on the value of B.
//!
//! # Correct and Efficient Usage of Collections
//!
//! Of course, knowing which collection is the right one for the job doesn't instantly
//! permit you to use it correctly. Here are some quick tips for efficient and correct
//! usage of the standard collections in general. If you're interested in how to use a | //! Many collections provide several constructors and methods that refer to "capacity".
//! These collections are generally built on top of an array. Optimally, this array would be
//! exactly the right size to fit only the elements stored in the collection, but for the
//! collection to do this would be very inefficient. If the backing array was exactly the
//! right size at all times, then every time an element is inserted, the collection would
//! have to grow the array to fit it. Due to the way memory is allocated and managed on most
//! computers, this would almost surely require allocating an entirely new array and
//! copying every single element from the old one into the new one. Hopefully you can
//! see that this wouldn't be very efficient to do on every operation.
//!
//! Most collections therefore use an *amortized* allocation strategy. They generally let
//! themselves have a fair amount of unoccupied space so that they only have to grow
//! on occasion. When they do grow, they allocate a substantially larger array to move
//! the elements into so that it will take a while for another grow to be required. While
//! this strategy is great in general, it would be even better if the collection *never*
//! had to resize its backing array. Unfortunately, the collection itself doesn't have
//! enough information to do this itself. Therefore, it is up to us programmers to give it
//! hints.
//!
//! Any `with_capacity` constructor will instruct the collection to allocate enough space
//! for the specified number of elements. Ideally this will be for exactly that many
//! elements, but some implementation details may prevent this. `Vec` and `VecDeque` can
//! be relied on to allocate exactly the requested amount, though. Use `with_capacity`
//! when you know exactly how many elements will be inserted, or at least have a
//! reasonable upper-bound on that number.
//!
//! When anticipating a large influx of elements, the `reserve` family of methods can
//! be used to hint to the collection how much room it should make for the coming items.
//! As with `with_capacity`, the precise behavior of these methods will be specific to
//! the collection of interest.
//!
//! For optimal performance, collections will generally avoid shrinking themselves.
//! If you believe that a collection will not soon contain any more elements, or
//! just really need the memory, the `shrink_to_fit` method prompts the collection
//! to shrink the backing array to the minimum size capable of holding its elements.
//!
//! Finally, if ever you're interested in what the actual capacity of the collection is,
//! most collections provide a `capacity` method to query this information on demand.
//! This can be useful for debugging purposes, or for use with the `reserve` methods.
//!
//! ## Iterators
//!
//! Iterators are a powerful and robust mechanism used throughout Rust's standard
//! libraries. Iterators provide a sequence of values in a generic, safe, efficient
//! and convenient way. The contents of an iterator are usually *lazily* evaluated,
//! so that only the values that are actually needed are ever actually produced, and
//! no allocation need be done to temporarily store them. Iterators are primarily
//! consumed using a `for` loop, although many functions also take iterators where
//! a collection or sequence of values is desired.
//!
//! All of the standard collections provide several iterators for performing bulk
//! manipulation of their contents. The three primary iterators almost every collection
//! should provide are `iter`, `iter_mut`, and `into_iter`. Some of these are not
//! provided on collections where it would be unsound or unreasonable to provide them.
//!
//! `iter` provides an iterator of immutable references to all the contents of a
//! collection in the most "natural" order. For sequence collections like `Vec`, this
//! means the items will be yielded in increasing order of index starting at 0. For ordered
//! collections like `BTreeMap`, this means that the items will be yielded in sorted order.
//! For unordered collections like `HashMap`, the items will be yielded in whatever order
//! the internal representation made most convenient. This is great for reading through
//! all the contents of the collection.
//!
//! ```
//! let vec = vec![1, 2, 3, 4];
//! for x in vec.iter() {
//! println!("vec contained {}", x);
//! }
//! ```
//!
//! `iter_mut` provides an iterator of *mutable* references in the same order as `iter`.
//! This is great for mutating all the contents of the collection.
//!
//! ```
//! let mut vec = vec![1, 2, 3, 4];
//! for x in vec.iter_mut() {
//! *x += 1;
//! }
//! ```
//!
//! `into_iter` transforms the actual collection into an iterator over its contents
//! by-value. This is great when the collection itself is no longer needed, and the
//! values are needed elsewhere. Using `extend` with `into_iter` is the main way that
//! contents of one collection are moved into another. Calling `collect` on an iterator
//! itself is also a great way to convert one collection into another. Both of these
//! methods should internally use the capacity management tools discussed in the
//! previous section to do this as efficiently as possible.
//!
//! ```
//! let mut vec1 = vec![1, 2, 3, 4];
//! let vec2 = vec![10, 20, 30, 40];
//! vec1.extend(vec2.into_iter());
//! ```
//!
//! ```
//! use std::collections::VecDeque;
//!
//! let vec = vec![1, 2, 3, 4];
//! let buf: VecDeque<_> = vec.into_iter().collect();
//! ```
//!
//! Iterators also provide a series of *adapter* methods for performing common tasks to
//! sequences. Among the adapters are functional favorites like `map`, `fold`, `skip`,
//! and `take`. Of particular interest to collections is the `rev` adapter, that
//! reverses any iterator that supports this operation. Most collections provide reversible
//! iterators as the way to iterate over them in reverse order.
//!
//! ```
//! let vec = vec![1, 2, 3, 4];
//! for x in vec.iter().rev() {
//! println!("vec contained {}", x);
//! }
//! ```
//!
//! Several other collection methods also return iterators to yield a sequence of results
//! but avoid allocating an entire collection to store the result in. This provides maximum
//! flexibility as `collect` or `extend` can be called to "pipe" the sequence into any
//! collection if desired. Otherwise, the sequence can be looped over with a `for` loop. The
//! iterator can also be discarded after partial use, preventing the computation of the unused
//! items.
//!
//! ## Entries
//!
//! The `entry` API is intended to provide an efficient mechanism for manipulating
//! the contents of a map conditionally on the presence of a key or not. The primary
//! motivating use case for this is to provide efficient accumulator maps. For instance,
//! if one wishes to maintain a count of the number of times each key has been seen,
//! they will have to perform some conditional logic on whether this is the first time
//! the key has been seen or not. Normally, this would require a `find` followed by an
//! `insert`, effectively duplicating the search effort on each insertion.
//!
//! When a user calls `map.entry(&key)`, the map will search for the key and then yield
//! a variant of the `Entry` enum.
//!
//! If a `Vacant(entry)` is yielded, then the key *was not* found. In this case the
//! only valid operation is to `insert` a value into the entry. When this is done,
//! the vacant entry is consumed and converted into a mutable reference to the
//! the value that was inserted. This allows for further manipulation of the value
//! beyond the lifetime of the search itself. This is useful if complex logic needs to
//! be performed on the value regardless of whether the value was just inserted.
//!
//! If an `Occupied(entry)` is yielded, then the key *was* found. In this case, the user
//! has several options: they can `get`, `insert`, or `remove` the value of the occupied
//! entry. Additionally, they can convert the occupied entry into a mutable reference
//! to its value, providing symmetry to the vacant `insert` case.
//!
//! ### Examples
//!
//! Here are the two primary ways in which `entry` is used. First, a simple example
//! where the logic performed on the values is trivial.
//!
//! #### Counting the number of times each character in a string occurs
//!
//! ```
//! use std::collections::btree_map::{BTreeMap, Entry};
//!
//! let mut count = BTreeMap::new();
//! let message = "she sells sea shells by the sea shore";
//!
//! for c in message.chars() {
//! match count.entry(c) {
//! Entry::Vacant(entry) => { entry.insert(1); },
//! Entry::Occupied(mut entry) => *entry.get_mut() += 1,
//! }
//! }
//!
//! assert_eq!(count.get(&'s'), Some(&8));
//!
//! println!("Number of occurrences of each character");
//! for (char, count) in count.iter() {
//! println!("{}: {}", char, count);
//! }
//! ```
//!
//! When the logic to be performed on the value is more complex, we may simply use
//! the `entry` API to ensure that the value is initialized, and perform the logic
//! afterwards.
//!
//! #### Tracking the inebriation of customers at a bar
//!
//! ```
//! use std::collections::btree_map::{BTreeMap, Entry};
//!
//! // A client of the bar. They have an id and a blood alcohol level.
//! struct Person { id: u32, blood_alcohol: f32 }
//!
//! // All the orders made to the bar, by client id.
//! let orders = vec![1,2,1,2,3,4,1,2,2,3,4,1,1,1];
//!
//! // Our clients.
//! let mut blood_alcohol = BTreeMap::new();
//!
//! for id in orders.into_iter() {
//! // If this is the first time we've seen this customer, initialize them
//! // with no blood alcohol. Otherwise, just retrieve them.
//! let person = match blood_alcohol.entry(id) {
//! Entry::Vacant(entry) => entry.insert(Person{id: id, blood_alcohol: 0.0}),
//! Entry::Occupied(entry) => entry.into_mut(),
//! };
//!
//! // Reduce their blood alcohol level. It takes time to order and drink a beer!
//! person.blood_alcohol *= 0.9;
//!
//! // Check if they're sober enough to have another beer.
//! if person.blood_alcohol > 0.3 {
//! // Too drunk... for now.
//! println!("Sorry {}, I have to cut you off", person.id);
//! } else {
//! // Have another!
//! person.blood_alcohol += 0.1;
//! }
//! }
//! ```
#![stable(feature = "rust1", since = "1.0.0")]
pub use core_collections::Bound;
pub use core_collections::{BinaryHeap, BitVec, BitSet, BTreeMap, BTreeSet};
pub use core_collections::{LinkedList, VecDeque, VecMap};
pub use core_collections::{binary_heap, bit_vec, bit_set, btree_map, btree_set};
pub use core_collections::{linked_list, vec_deque, vec_map};
pub use self::hash_map::HashMap;
pub use self::hash_set::HashSet;
mod hash;
#[stable(feature = "rust1", since = "1.0.0")]
pub mod hash_map {
//! A hashmap
pub use super::hash::map::*;
}
#[stable(feature = "rust1", since = "1.0.0")]
pub mod hash_set {
//! A hashset
pub use super::hash::set::*;
}
/// Experimental support for providing custom hash algorithms to a HashMap and
/// HashSet.
#[unstable(feature = "std_misc", reason = "module was recently added")]
pub mod hash_state {
pub use super::hash::state::*;
} | //! specific collection in particular, consult its documentation for detailed discussion
//! and code examples.
//!
//! ## Capacity Management
//! | random_line_split |
scheme.rs | use alloc::boxed::Box;
use collections::vec::Vec;
use collections::vec_deque::VecDeque;
use core::ops::DerefMut;
use fs::Resource;
use system::error::Result;
use sync::{Intex, WaitQueue};
pub trait NetworkScheme {
fn add(&mut self, resource: *mut NetworkResource);
fn remove(&mut self, resource: *mut NetworkResource);
fn sync(&mut self);
}
pub struct NetworkResource {
pub nic: *mut NetworkScheme,
pub ptr: *mut NetworkResource,
pub inbound: WaitQueue<Vec<u8>>,
pub outbound: Intex<VecDeque<Vec<u8>>>,
}
impl NetworkResource {
pub fn new(nic: *mut NetworkScheme) -> Box<Self> {
let mut ret = box NetworkResource {
nic: nic,
ptr: 0 as *mut NetworkResource,
inbound: WaitQueue::new(),
outbound: Intex::new(VecDeque::new()),
};
unsafe {
ret.ptr = ret.deref_mut();
(*ret.nic).add(ret.ptr);
}
ret
}
}
impl Resource for NetworkResource {
fn dup(&self) -> Result<Box<Resource>> {
let mut ret = box NetworkResource {
nic: self.nic,
ptr: 0 as *mut NetworkResource,
inbound: self.inbound.clone(),
outbound: Intex::new(self.outbound.lock().clone()),
};
unsafe {
ret.ptr = ret.deref_mut();
(*ret.nic).add(ret.ptr);
}
Ok(ret)
}
fn path(&self, buf: &mut [u8]) -> Result<usize> {
let path = b"network:";
let mut i = 0;
while i < buf.len() && i < path.len() {
buf[i] = path[i];
i += 1;
}
Ok(i)
}
fn read(&mut self, buf: &mut [u8]) -> Result<usize> |
fn write(&mut self, buf: &[u8]) -> Result<usize> {
unsafe {
(*self.ptr).outbound.lock().push_back(Vec::from(buf));
(*self.nic).sync();
}
Ok(buf.len())
}
fn sync(&mut self) -> Result<()> {
unsafe {
(*self.nic).sync();
}
Ok(())
}
}
impl Drop for NetworkResource {
fn drop(&mut self) {
unsafe {
(*self.nic).remove(self.ptr);
}
}
}
| {
let bytes = unsafe {
(*self.nic).sync();
(*self.ptr).inbound.receive()
};
let mut i = 0;
while i < bytes.len() && i < buf.len() {
buf[i] = bytes[i];
i += 1;
}
return Ok(bytes.len());
} | identifier_body |
scheme.rs | use alloc::boxed::Box;
use collections::vec::Vec;
use collections::vec_deque::VecDeque;
use core::ops::DerefMut;
use fs::Resource;
use system::error::Result;
use sync::{Intex, WaitQueue};
pub trait NetworkScheme {
fn add(&mut self, resource: *mut NetworkResource);
fn remove(&mut self, resource: *mut NetworkResource);
fn sync(&mut self);
}
pub struct NetworkResource {
pub nic: *mut NetworkScheme,
pub ptr: *mut NetworkResource,
pub inbound: WaitQueue<Vec<u8>>,
pub outbound: Intex<VecDeque<Vec<u8>>>,
}
impl NetworkResource {
pub fn new(nic: *mut NetworkScheme) -> Box<Self> {
let mut ret = box NetworkResource {
nic: nic,
ptr: 0 as *mut NetworkResource,
inbound: WaitQueue::new(),
outbound: Intex::new(VecDeque::new()),
};
unsafe {
ret.ptr = ret.deref_mut();
(*ret.nic).add(ret.ptr);
}
ret
}
}
impl Resource for NetworkResource {
fn dup(&self) -> Result<Box<Resource>> {
let mut ret = box NetworkResource {
nic: self.nic,
ptr: 0 as *mut NetworkResource,
inbound: self.inbound.clone(),
outbound: Intex::new(self.outbound.lock().clone()),
};
unsafe {
ret.ptr = ret.deref_mut();
(*ret.nic).add(ret.ptr);
}
Ok(ret)
}
fn path(&self, buf: &mut [u8]) -> Result<usize> {
let path = b"network:";
let mut i = 0;
while i < buf.len() && i < path.len() {
buf[i] = path[i];
i += 1;
}
Ok(i)
}
fn read(&mut self, buf: &mut [u8]) -> Result<usize> {
let bytes = unsafe {
(*self.nic).sync();
(*self.ptr).inbound.receive()
};
let mut i = 0;
while i < bytes.len() && i < buf.len() {
buf[i] = bytes[i];
i += 1;
}
return Ok(bytes.len());
}
fn | (&mut self, buf: &[u8]) -> Result<usize> {
unsafe {
(*self.ptr).outbound.lock().push_back(Vec::from(buf));
(*self.nic).sync();
}
Ok(buf.len())
}
fn sync(&mut self) -> Result<()> {
unsafe {
(*self.nic).sync();
}
Ok(())
}
}
impl Drop for NetworkResource {
fn drop(&mut self) {
unsafe {
(*self.nic).remove(self.ptr);
}
}
}
| write | identifier_name |
scheme.rs | use alloc::boxed::Box;
use collections::vec::Vec;
use collections::vec_deque::VecDeque;
use core::ops::DerefMut;
use fs::Resource;
use system::error::Result;
use sync::{Intex, WaitQueue};
pub trait NetworkScheme {
fn add(&mut self, resource: *mut NetworkResource);
fn remove(&mut self, resource: *mut NetworkResource);
fn sync(&mut self);
}
pub struct NetworkResource {
pub nic: *mut NetworkScheme,
pub ptr: *mut NetworkResource,
pub inbound: WaitQueue<Vec<u8>>,
pub outbound: Intex<VecDeque<Vec<u8>>>,
}
impl NetworkResource {
pub fn new(nic: *mut NetworkScheme) -> Box<Self> {
let mut ret = box NetworkResource {
nic: nic,
ptr: 0 as *mut NetworkResource,
inbound: WaitQueue::new(),
outbound: Intex::new(VecDeque::new()),
};
unsafe {
ret.ptr = ret.deref_mut();
(*ret.nic).add(ret.ptr);
}
ret
}
}
impl Resource for NetworkResource {
fn dup(&self) -> Result<Box<Resource>> {
let mut ret = box NetworkResource {
nic: self.nic,
ptr: 0 as *mut NetworkResource,
inbound: self.inbound.clone(),
outbound: Intex::new(self.outbound.lock().clone()),
};
unsafe {
ret.ptr = ret.deref_mut();
(*ret.nic).add(ret.ptr);
}
Ok(ret)
}
fn path(&self, buf: &mut [u8]) -> Result<usize> {
let path = b"network:";
let mut i = 0;
while i < buf.len() && i < path.len() {
buf[i] = path[i];
i += 1;
}
Ok(i)
}
fn read(&mut self, buf: &mut [u8]) -> Result<usize> {
let bytes = unsafe {
(*self.nic).sync();
(*self.ptr).inbound.receive()
};
let mut i = 0;
while i < bytes.len() && i < buf.len() {
buf[i] = bytes[i];
i += 1;
}
return Ok(bytes.len());
}
fn write(&mut self, buf: &[u8]) -> Result<usize> {
unsafe { | Ok(buf.len())
}
fn sync(&mut self) -> Result<()> {
unsafe {
(*self.nic).sync();
}
Ok(())
}
}
impl Drop for NetworkResource {
fn drop(&mut self) {
unsafe {
(*self.nic).remove(self.ptr);
}
}
} | (*self.ptr).outbound.lock().push_back(Vec::from(buf));
(*self.nic).sync();
}
| random_line_split |
unsized5.rs | // Copyright 2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
// Test `?Sized` types not allowed in fields (except the last one).
struct S1<X:?Sized> {
f1: X, //~ ERROR `core::marker::Sized` is not implemented
f2: isize,
}
struct S2<X:?Sized> {
f: isize,
g: X, //~ ERROR `core::marker::Sized` is not implemented
h: isize,
}
struct S3 {
f: str, //~ ERROR `core::marker::Sized` is not implemented
g: [usize]
}
struct S4 {
f: str, //~ ERROR `core::marker::Sized` is not implemented
g: usize
}
enum E<X:?Sized> {
V1(X, isize), //~ERROR `core::marker::Sized` is not implemented
}
enum F<X:?Sized> {
V2{f1: X, f: isize}, //~ERROR `core::marker::Sized` is not implemented
}
pub fn main() | {
} | identifier_body |
|
unsized5.rs | // Copyright 2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
// Test `?Sized` types not allowed in fields (except the last one).
struct S1<X:?Sized> {
f1: X, //~ ERROR `core::marker::Sized` is not implemented
f2: isize,
}
struct S2<X:?Sized> {
f: isize,
g: X, //~ ERROR `core::marker::Sized` is not implemented
h: isize,
}
struct S3 {
f: str, //~ ERROR `core::marker::Sized` is not implemented
g: [usize] | struct S4 {
f: str, //~ ERROR `core::marker::Sized` is not implemented
g: usize
}
enum E<X:?Sized> {
V1(X, isize), //~ERROR `core::marker::Sized` is not implemented
}
enum F<X:?Sized> {
V2{f1: X, f: isize}, //~ERROR `core::marker::Sized` is not implemented
}
pub fn main() {
} | } | random_line_split |
unsized5.rs | // Copyright 2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
// Test `?Sized` types not allowed in fields (except the last one).
struct S1<X:?Sized> {
f1: X, //~ ERROR `core::marker::Sized` is not implemented
f2: isize,
}
struct | <X:?Sized> {
f: isize,
g: X, //~ ERROR `core::marker::Sized` is not implemented
h: isize,
}
struct S3 {
f: str, //~ ERROR `core::marker::Sized` is not implemented
g: [usize]
}
struct S4 {
f: str, //~ ERROR `core::marker::Sized` is not implemented
g: usize
}
enum E<X:?Sized> {
V1(X, isize), //~ERROR `core::marker::Sized` is not implemented
}
enum F<X:?Sized> {
V2{f1: X, f: isize}, //~ERROR `core::marker::Sized` is not implemented
}
pub fn main() {
}
| S2 | identifier_name |
mmio.rs | // This file is part of zinc64.
// Copyright (c) 2016-2019 Sebastian Jastrzebski. All rights reserved.
// Licensed under the GPLv3. See LICENSE file in the project root for full license text.
use zinc64_core::{AddressableFaded, Chip, Ram, Shared};
pub struct Mmio {
cia_1: Shared<dyn Chip>,
cia_2: Shared<dyn Chip>, | }
impl Mmio {
pub fn new(
cia_1: Shared<dyn Chip>,
cia_2: Shared<dyn Chip>,
color_ram: Shared<Ram>,
expansion_port: Shared<dyn AddressableFaded>,
sid: Shared<dyn Chip>,
vic: Shared<dyn Chip>,
) -> Self {
Self {
cia_1,
cia_2,
color_ram,
expansion_port,
sid,
vic,
}
}
pub fn read(&self, address: u16) -> u8 {
match address {
0xd000..=0xd3ff => self.vic.borrow_mut().read((address & 0x003f) as u8),
0xd400..=0xd7ff => self.sid.borrow_mut().read((address & 0x001f) as u8),
0xd800..=0xdbff => self.color_ram.borrow().read(address - 0xd800),
0xdc00..=0xdcff => self.cia_1.borrow_mut().read((address & 0x000f) as u8),
0xdd00..=0xddff => self.cia_2.borrow_mut().read((address & 0x000f) as u8),
0xde00..=0xdfff => self.expansion_port.borrow_mut().read(address).unwrap_or(0),
_ => panic!("invalid address 0x{:x}", address),
}
}
pub fn write(&mut self, address: u16, value: u8) {
match address {
0xd000..=0xd3ff => self.vic.borrow_mut().write((address & 0x003f) as u8, value),
0xd400..=0xd7ff => self.sid.borrow_mut().write((address & 0x001f) as u8, value),
0xd800..=0xdbff => self.color_ram.borrow_mut().write(address - 0xd800, value),
0xdc00..=0xdcff => self
.cia_1
.borrow_mut()
.write((address & 0x000f) as u8, value),
0xdd00..=0xddff => self
.cia_2
.borrow_mut()
.write((address & 0x000f) as u8, value),
0xde00..=0xdfff => self.expansion_port.borrow_mut().write(address, value),
_ => panic!("invalid address 0x{:x}", address),
}
}
} | color_ram: Shared<Ram>,
expansion_port: Shared<dyn AddressableFaded>,
sid: Shared<dyn Chip>,
vic: Shared<dyn Chip>, | random_line_split |
mmio.rs | // This file is part of zinc64.
// Copyright (c) 2016-2019 Sebastian Jastrzebski. All rights reserved.
// Licensed under the GPLv3. See LICENSE file in the project root for full license text.
use zinc64_core::{AddressableFaded, Chip, Ram, Shared};
pub struct Mmio {
cia_1: Shared<dyn Chip>,
cia_2: Shared<dyn Chip>,
color_ram: Shared<Ram>,
expansion_port: Shared<dyn AddressableFaded>,
sid: Shared<dyn Chip>,
vic: Shared<dyn Chip>,
}
impl Mmio {
pub fn new(
cia_1: Shared<dyn Chip>,
cia_2: Shared<dyn Chip>,
color_ram: Shared<Ram>,
expansion_port: Shared<dyn AddressableFaded>,
sid: Shared<dyn Chip>,
vic: Shared<dyn Chip>,
) -> Self {
Self {
cia_1,
cia_2,
color_ram,
expansion_port,
sid,
vic,
}
}
pub fn | (&self, address: u16) -> u8 {
match address {
0xd000..=0xd3ff => self.vic.borrow_mut().read((address & 0x003f) as u8),
0xd400..=0xd7ff => self.sid.borrow_mut().read((address & 0x001f) as u8),
0xd800..=0xdbff => self.color_ram.borrow().read(address - 0xd800),
0xdc00..=0xdcff => self.cia_1.borrow_mut().read((address & 0x000f) as u8),
0xdd00..=0xddff => self.cia_2.borrow_mut().read((address & 0x000f) as u8),
0xde00..=0xdfff => self.expansion_port.borrow_mut().read(address).unwrap_or(0),
_ => panic!("invalid address 0x{:x}", address),
}
}
pub fn write(&mut self, address: u16, value: u8) {
match address {
0xd000..=0xd3ff => self.vic.borrow_mut().write((address & 0x003f) as u8, value),
0xd400..=0xd7ff => self.sid.borrow_mut().write((address & 0x001f) as u8, value),
0xd800..=0xdbff => self.color_ram.borrow_mut().write(address - 0xd800, value),
0xdc00..=0xdcff => self
.cia_1
.borrow_mut()
.write((address & 0x000f) as u8, value),
0xdd00..=0xddff => self
.cia_2
.borrow_mut()
.write((address & 0x000f) as u8, value),
0xde00..=0xdfff => self.expansion_port.borrow_mut().write(address, value),
_ => panic!("invalid address 0x{:x}", address),
}
}
}
| read | identifier_name |
borrowck-lend-flow-match.rs | // Copyright 2012 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
// xfail-pretty -- comments are unfaithfully preserved
#[allow(unused_variable)];
#[allow(dead_assignment)];
fn cond() -> bool { fail!() }
fn link<'a>(v: &'a uint, w: &mut &'a uint) -> bool { *w = v; true }
fn separate_arms() {
// Here both arms perform assignments, but only is illegal.
let mut x = None;
match x {
None => {
// It is ok to reassign x here, because there is in
// fact no outstanding loan of x!
x = Some(0);
}
Some(ref _i) => {
x = Some(1); //~ ERROR cannot assign
}
}
copy x; // just to prevent liveness warnings
}
fn guard() |
b = ~8; //~ ERROR cannot assign
}
fn main() {}
| {
// Here the guard performs a borrow. This borrow "infects" all
// subsequent arms (but not the prior ones).
let mut a = ~3;
let mut b = ~4;
let mut w = &*a;
match 22 {
_ if cond() => {
b = ~5;
}
_ if link(&*b, &mut w) => {
b = ~6; //~ ERROR cannot assign
}
_ => {
b = ~7; //~ ERROR cannot assign
}
} | identifier_body |
borrowck-lend-flow-match.rs | // Copyright 2012 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
// xfail-pretty -- comments are unfaithfully preserved
#[allow(unused_variable)];
#[allow(dead_assignment)];
fn cond() -> bool { fail!() }
fn link<'a>(v: &'a uint, w: &mut &'a uint) -> bool { *w = v; true }
fn separate_arms() {
// Here both arms perform assignments, but only is illegal.
let mut x = None;
match x {
None => {
// It is ok to reassign x here, because there is in
// fact no outstanding loan of x!
x = Some(0);
}
Some(ref _i) => {
x = Some(1); //~ ERROR cannot assign
}
}
copy x; // just to prevent liveness warnings
}
fn | () {
// Here the guard performs a borrow. This borrow "infects" all
// subsequent arms (but not the prior ones).
let mut a = ~3;
let mut b = ~4;
let mut w = &*a;
match 22 {
_ if cond() => {
b = ~5;
}
_ if link(&*b, &mut w) => {
b = ~6; //~ ERROR cannot assign
}
_ => {
b = ~7; //~ ERROR cannot assign
}
}
b = ~8; //~ ERROR cannot assign
}
fn main() {}
| guard | identifier_name |
borrowck-lend-flow-match.rs | // Copyright 2012 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
// xfail-pretty -- comments are unfaithfully preserved
#[allow(unused_variable)];
#[allow(dead_assignment)];
fn cond() -> bool { fail!() }
fn link<'a>(v: &'a uint, w: &mut &'a uint) -> bool { *w = v; true }
fn separate_arms() {
// Here both arms perform assignments, but only is illegal.
let mut x = None;
match x {
None => {
// It is ok to reassign x here, because there is in
// fact no outstanding loan of x!
x = Some(0);
}
Some(ref _i) => {
x = Some(1); //~ ERROR cannot assign
}
}
copy x; // just to prevent liveness warnings
}
fn guard() {
// Here the guard performs a borrow. This borrow "infects" all
// subsequent arms (but not the prior ones).
let mut a = ~3;
let mut b = ~4;
let mut w = &*a;
match 22 {
_ if cond() => {
b = ~5;
}
_ if link(&*b, &mut w) => { |
_ => {
b = ~7; //~ ERROR cannot assign
}
}
b = ~8; //~ ERROR cannot assign
}
fn main() {} | b = ~6; //~ ERROR cannot assign
} | random_line_split |
mod.rs | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
#![allow(unsafe_code)]
//! A drop-in replacement for string_cache, but backed by Gecko `nsAtom`s.
use gecko_bindings::bindings::Gecko_AddRefAtom;
use gecko_bindings::bindings::Gecko_Atomize;
use gecko_bindings::bindings::Gecko_Atomize16;
use gecko_bindings::bindings::Gecko_ReleaseAtom;
use gecko_bindings::structs::{nsAtom, nsAtom_AtomKind, nsDynamicAtom, nsStaticAtom};
use nsstring::{nsAString, nsStr};
use precomputed_hash::PrecomputedHash;
use std::{mem, slice, str};
use std::borrow::{Borrow, Cow};
use std::char::{self, DecodeUtf16};
use std::fmt::{self, Write};
use std::hash::{Hash, Hasher};
use std::iter::Cloned;
use std::ops::Deref;
use style_traits::SpecifiedValueInfo;
#[macro_use]
#[allow(improper_ctypes, non_camel_case_types, missing_docs)]
pub mod atom_macro {
include!(concat!(env!("OUT_DIR"), "/gecko/atom_macro.rs"));
}
#[macro_use]
pub mod namespace;
pub use self::namespace::{Namespace, WeakNamespace};
macro_rules! local_name {
($s:tt) => {
atom!($s)
};
}
/// A strong reference to a Gecko atom.
#[derive(Eq, PartialEq)]
pub struct Atom(*mut WeakAtom);
/// An atom *without* a strong reference.
///
/// Only usable as `&'a WeakAtom`,
/// where `'a` is the lifetime of something that holds a strong reference to that atom.
pub struct WeakAtom(nsAtom);
/// A BorrowedAtom for Gecko is just a weak reference to a `nsAtom`, that
/// hasn't been bumped.
pub type BorrowedAtom<'a> = &'a WeakAtom;
impl Deref for Atom {
type Target = WeakAtom;
#[inline]
fn deref(&self) -> &WeakAtom {
unsafe { &*self.0 }
}
}
impl PrecomputedHash for Atom {
#[inline]
fn precomputed_hash(&self) -> u32 {
self.get_hash()
}
}
impl Borrow<WeakAtom> for Atom {
#[inline]
fn borrow(&self) -> &WeakAtom {
self
}
}
impl Eq for WeakAtom {}
impl PartialEq for WeakAtom {
#[inline]
fn eq(&self, other: &Self) -> bool {
let weak: *const WeakAtom = self;
let other: *const WeakAtom = other;
weak == other
}
}
unsafe impl Send for Atom {}
unsafe impl Sync for Atom {}
unsafe impl Sync for WeakAtom {}
impl WeakAtom {
/// Construct a `WeakAtom` from a raw `nsAtom`.
#[inline]
pub unsafe fn new<'a>(atom: *const nsAtom) -> &'a mut Self {
&mut *(atom as *mut WeakAtom)
}
/// Clone this atom, bumping the refcount if the atom is not static.
#[inline]
pub fn clone(&self) -> Atom {
unsafe { Atom::from_raw(self.as_ptr()) }
}
/// Get the atom hash.
#[inline]
pub fn get_hash(&self) -> u32 {
self.0.mHash
}
/// Get the atom as a slice of utf-16 chars.
#[inline]
pub fn as_slice(&self) -> &[u16] {
let string = if self.is_static() {
let atom_ptr = self.as_ptr() as *const nsStaticAtom;
let string_offset = unsafe { (*atom_ptr).mStringOffset };
let string_offset = -(string_offset as isize);
let u8_ptr = atom_ptr as *const u8;
// It is safe to use offset() here because both addresses are within
// the same struct, e.g. mozilla::detail::gGkAtoms.
unsafe { u8_ptr.offset(string_offset) as *const u16 }
} else {
let atom_ptr = self.as_ptr() as *const nsDynamicAtom;
unsafe { (*(atom_ptr)).mString }
};
unsafe { slice::from_raw_parts(string, self.len() as usize) }
}
// NOTE: don't expose this, since it's slow, and easy to be misused.
fn chars(&self) -> DecodeUtf16<Cloned<slice::Iter<u16>>> {
char::decode_utf16(self.as_slice().iter().cloned())
}
/// Execute `cb` with the string that this atom represents.
///
/// Find alternatives to this function when possible, please, since it's
/// pretty slow.
pub fn with_str<F, Output>(&self, cb: F) -> Output
where
F: FnOnce(&str) -> Output,
{
let mut buffer: [u8; 64] = unsafe { mem::uninitialized() };
// The total string length in utf16 is going to be less than or equal
// the slice length (each utf16 character is going to take at least one
// and at most 2 items in the utf16 slice).
//
// Each of those characters will take at most four bytes in the utf8
// one. Thus if the slice is less than 64 / 4 (16) we can guarantee that
// we'll decode it in place.
let owned_string;
let len = self.len();
let utf8_slice = if len <= 16 {
let mut total_len = 0;
for c in self.chars() {
let c = c.unwrap_or(char::REPLACEMENT_CHARACTER);
let utf8_len = c.encode_utf8(&mut buffer[total_len..]).len();
total_len += utf8_len;
}
let slice = unsafe { str::from_utf8_unchecked(&buffer[..total_len]) };
debug_assert_eq!(slice, String::from_utf16_lossy(self.as_slice()));
slice
} else {
owned_string = String::from_utf16_lossy(self.as_slice());
&*owned_string
};
cb(utf8_slice)
}
/// Returns whether this atom is static.
#[inline]
pub fn is_static(&self) -> bool {
unsafe { (*self.as_ptr()).mKind() == nsAtom_AtomKind::Static as u32 }
}
/// Returns the length of the atom string.
#[inline]
pub fn len(&self) -> u32 {
unsafe { (*self.as_ptr()).mLength() }
}
/// Returns whether this atom is the empty string.
#[inline]
pub fn is_empty(&self) -> bool {
self.len() == 0
}
/// Returns the atom as a mutable pointer.
#[inline]
pub fn as_ptr(&self) -> *mut nsAtom {
let const_ptr: *const nsAtom = &self.0;
const_ptr as *mut nsAtom
}
/// Convert this atom to ASCII lower-case
pub fn to_ascii_lowercase(&self) -> Atom {
let slice = self.as_slice();
match slice
.iter()
.position(|&char16| (b'A' as u16) <= char16 && char16 <= (b'Z' as u16))
{
None => self.clone(),
Some(i) => {
let mut buffer: [u16; 64] = unsafe { mem::uninitialized() };
let mut vec;
let mutable_slice = if let Some(buffer_prefix) = buffer.get_mut(..slice.len()) {
buffer_prefix.copy_from_slice(slice);
buffer_prefix
} else {
vec = slice.to_vec();
&mut vec
};
for char16 in &mut mutable_slice[i..] {
if *char16 <= 0x7F {
*char16 = (*char16 as u8).to_ascii_lowercase() as u16
}
}
Atom::from(&*mutable_slice)
},
}
}
/// Return whether two atoms are ASCII-case-insensitive matches
pub fn eq_ignore_ascii_case(&self, other: &Self) -> bool {
if self == other {
return true;
}
let a = self.as_slice();
let b = other.as_slice();
a.len() == b.len() && a.iter().zip(b).all(|(&a16, &b16)| {
if a16 <= 0x7F && b16 <= 0x7F {
(a16 as u8).eq_ignore_ascii_case(&(b16 as u8))
} else {
a16 == b16
}
})
}
/// Return whether this atom is an ASCII-case-insensitive match for the given string
pub fn eq_str_ignore_ascii_case(&self, other: &str) -> bool {
self.chars()
.map(|r| r.map(|c: char| c.to_ascii_lowercase()))
.eq(other.chars().map(|c: char| Ok(c.to_ascii_lowercase())))
}
}
impl fmt::Debug for WeakAtom {
fn fmt(&self, w: &mut fmt::Formatter) -> fmt::Result {
write!(w, "Gecko WeakAtom({:p}, {})", self, self)
}
}
impl fmt::Display for WeakAtom {
fn fmt(&self, w: &mut fmt::Formatter) -> fmt::Result {
for c in self.chars() {
w.write_char(c.unwrap_or(char::REPLACEMENT_CHARACTER))?
}
Ok(())
}
}
| impl Atom {
/// Execute a callback with the atom represented by `ptr`.
pub unsafe fn with<F, R>(ptr: *mut nsAtom, callback: F) -> R
where
F: FnOnce(&Atom) -> R,
{
let atom = Atom(WeakAtom::new(ptr));
let ret = callback(&atom);
mem::forget(atom);
ret
}
/// Creates an atom from an static atom pointer without checking in release
/// builds.
///
/// Right now it's only used by the atom macro, and ideally it should keep
/// that way, now we have sugar for is_static, creating atoms using
/// Atom::from_raw should involve almost no overhead.
#[inline]
pub unsafe fn from_static(ptr: *mut nsStaticAtom) -> Self {
let atom = Atom(ptr as *mut WeakAtom);
debug_assert!(
atom.is_static(),
"Called from_static for a non-static atom!"
);
atom
}
/// Creates an atom from an atom pointer.
#[inline(always)]
pub unsafe fn from_raw(ptr: *mut nsAtom) -> Self {
let atom = Atom(ptr as *mut WeakAtom);
if!atom.is_static() {
Gecko_AddRefAtom(ptr);
}
atom
}
/// Creates an atom from a dynamic atom pointer that has already had AddRef
/// called on it.
#[inline]
pub unsafe fn from_addrefed(ptr: *mut nsAtom) -> Self {
assert!(!ptr.is_null());
Atom(WeakAtom::new(ptr))
}
/// Convert this atom into an addrefed nsAtom pointer.
#[inline]
pub fn into_addrefed(self) -> *mut nsAtom {
let ptr = self.as_ptr();
mem::forget(self);
ptr
}
}
impl Hash for Atom {
fn hash<H>(&self, state: &mut H)
where
H: Hasher,
{
state.write_u32(self.get_hash());
}
}
impl Hash for WeakAtom {
fn hash<H>(&self, state: &mut H)
where
H: Hasher,
{
state.write_u32(self.get_hash());
}
}
impl Clone for Atom {
#[inline(always)]
fn clone(&self) -> Atom {
unsafe { Atom::from_raw(self.as_ptr()) }
}
}
impl Drop for Atom {
#[inline]
fn drop(&mut self) {
if!self.is_static() {
unsafe {
Gecko_ReleaseAtom(self.as_ptr());
}
}
}
}
impl Default for Atom {
#[inline]
fn default() -> Self {
atom!("")
}
}
impl fmt::Debug for Atom {
fn fmt(&self, w: &mut fmt::Formatter) -> fmt::Result {
write!(w, "Gecko Atom({:p}, {})", self.0, self)
}
}
impl fmt::Display for Atom {
fn fmt(&self, w: &mut fmt::Formatter) -> fmt::Result {
unsafe { (&*self.0).fmt(w) }
}
}
impl<'a> From<&'a str> for Atom {
#[inline]
fn from(string: &str) -> Atom {
debug_assert!(string.len() <= u32::max_value() as usize);
unsafe {
Atom(WeakAtom::new(Gecko_Atomize(
string.as_ptr() as *const _,
string.len() as u32,
)))
}
}
}
impl<'a> From<&'a [u16]> for Atom {
#[inline]
fn from(slice: &[u16]) -> Atom {
Atom::from(&*nsStr::from(slice))
}
}
impl<'a> From<&'a nsAString> for Atom {
#[inline]
fn from(string: &nsAString) -> Atom {
unsafe { Atom(WeakAtom::new(Gecko_Atomize16(string))) }
}
}
impl<'a> From<Cow<'a, str>> for Atom {
#[inline]
fn from(string: Cow<'a, str>) -> Atom {
Atom::from(&*string)
}
}
impl From<String> for Atom {
#[inline]
fn from(string: String) -> Atom {
Atom::from(&*string)
}
}
malloc_size_of_is_0!(Atom);
impl SpecifiedValueInfo for Atom {} | random_line_split |
|
mod.rs | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
#![allow(unsafe_code)]
//! A drop-in replacement for string_cache, but backed by Gecko `nsAtom`s.
use gecko_bindings::bindings::Gecko_AddRefAtom;
use gecko_bindings::bindings::Gecko_Atomize;
use gecko_bindings::bindings::Gecko_Atomize16;
use gecko_bindings::bindings::Gecko_ReleaseAtom;
use gecko_bindings::structs::{nsAtom, nsAtom_AtomKind, nsDynamicAtom, nsStaticAtom};
use nsstring::{nsAString, nsStr};
use precomputed_hash::PrecomputedHash;
use std::{mem, slice, str};
use std::borrow::{Borrow, Cow};
use std::char::{self, DecodeUtf16};
use std::fmt::{self, Write};
use std::hash::{Hash, Hasher};
use std::iter::Cloned;
use std::ops::Deref;
use style_traits::SpecifiedValueInfo;
#[macro_use]
#[allow(improper_ctypes, non_camel_case_types, missing_docs)]
pub mod atom_macro {
include!(concat!(env!("OUT_DIR"), "/gecko/atom_macro.rs"));
}
#[macro_use]
pub mod namespace;
pub use self::namespace::{Namespace, WeakNamespace};
macro_rules! local_name {
($s:tt) => {
atom!($s)
};
}
/// A strong reference to a Gecko atom.
#[derive(Eq, PartialEq)]
pub struct Atom(*mut WeakAtom);
/// An atom *without* a strong reference.
///
/// Only usable as `&'a WeakAtom`,
/// where `'a` is the lifetime of something that holds a strong reference to that atom.
pub struct WeakAtom(nsAtom);
/// A BorrowedAtom for Gecko is just a weak reference to a `nsAtom`, that
/// hasn't been bumped.
pub type BorrowedAtom<'a> = &'a WeakAtom;
impl Deref for Atom {
type Target = WeakAtom;
#[inline]
fn deref(&self) -> &WeakAtom {
unsafe { &*self.0 }
}
}
impl PrecomputedHash for Atom {
#[inline]
fn precomputed_hash(&self) -> u32 {
self.get_hash()
}
}
impl Borrow<WeakAtom> for Atom {
#[inline]
fn borrow(&self) -> &WeakAtom {
self
}
}
impl Eq for WeakAtom {}
impl PartialEq for WeakAtom {
#[inline]
fn eq(&self, other: &Self) -> bool {
let weak: *const WeakAtom = self;
let other: *const WeakAtom = other;
weak == other
}
}
unsafe impl Send for Atom {}
unsafe impl Sync for Atom {}
unsafe impl Sync for WeakAtom {}
impl WeakAtom {
/// Construct a `WeakAtom` from a raw `nsAtom`.
#[inline]
pub unsafe fn | <'a>(atom: *const nsAtom) -> &'a mut Self {
&mut *(atom as *mut WeakAtom)
}
/// Clone this atom, bumping the refcount if the atom is not static.
#[inline]
pub fn clone(&self) -> Atom {
unsafe { Atom::from_raw(self.as_ptr()) }
}
/// Get the atom hash.
#[inline]
pub fn get_hash(&self) -> u32 {
self.0.mHash
}
/// Get the atom as a slice of utf-16 chars.
#[inline]
pub fn as_slice(&self) -> &[u16] {
let string = if self.is_static() {
let atom_ptr = self.as_ptr() as *const nsStaticAtom;
let string_offset = unsafe { (*atom_ptr).mStringOffset };
let string_offset = -(string_offset as isize);
let u8_ptr = atom_ptr as *const u8;
// It is safe to use offset() here because both addresses are within
// the same struct, e.g. mozilla::detail::gGkAtoms.
unsafe { u8_ptr.offset(string_offset) as *const u16 }
} else {
let atom_ptr = self.as_ptr() as *const nsDynamicAtom;
unsafe { (*(atom_ptr)).mString }
};
unsafe { slice::from_raw_parts(string, self.len() as usize) }
}
// NOTE: don't expose this, since it's slow, and easy to be misused.
fn chars(&self) -> DecodeUtf16<Cloned<slice::Iter<u16>>> {
char::decode_utf16(self.as_slice().iter().cloned())
}
/// Execute `cb` with the string that this atom represents.
///
/// Find alternatives to this function when possible, please, since it's
/// pretty slow.
pub fn with_str<F, Output>(&self, cb: F) -> Output
where
F: FnOnce(&str) -> Output,
{
let mut buffer: [u8; 64] = unsafe { mem::uninitialized() };
// The total string length in utf16 is going to be less than or equal
// the slice length (each utf16 character is going to take at least one
// and at most 2 items in the utf16 slice).
//
// Each of those characters will take at most four bytes in the utf8
// one. Thus if the slice is less than 64 / 4 (16) we can guarantee that
// we'll decode it in place.
let owned_string;
let len = self.len();
let utf8_slice = if len <= 16 {
let mut total_len = 0;
for c in self.chars() {
let c = c.unwrap_or(char::REPLACEMENT_CHARACTER);
let utf8_len = c.encode_utf8(&mut buffer[total_len..]).len();
total_len += utf8_len;
}
let slice = unsafe { str::from_utf8_unchecked(&buffer[..total_len]) };
debug_assert_eq!(slice, String::from_utf16_lossy(self.as_slice()));
slice
} else {
owned_string = String::from_utf16_lossy(self.as_slice());
&*owned_string
};
cb(utf8_slice)
}
/// Returns whether this atom is static.
#[inline]
pub fn is_static(&self) -> bool {
unsafe { (*self.as_ptr()).mKind() == nsAtom_AtomKind::Static as u32 }
}
/// Returns the length of the atom string.
#[inline]
pub fn len(&self) -> u32 {
unsafe { (*self.as_ptr()).mLength() }
}
/// Returns whether this atom is the empty string.
#[inline]
pub fn is_empty(&self) -> bool {
self.len() == 0
}
/// Returns the atom as a mutable pointer.
#[inline]
pub fn as_ptr(&self) -> *mut nsAtom {
let const_ptr: *const nsAtom = &self.0;
const_ptr as *mut nsAtom
}
/// Convert this atom to ASCII lower-case
pub fn to_ascii_lowercase(&self) -> Atom {
let slice = self.as_slice();
match slice
.iter()
.position(|&char16| (b'A' as u16) <= char16 && char16 <= (b'Z' as u16))
{
None => self.clone(),
Some(i) => {
let mut buffer: [u16; 64] = unsafe { mem::uninitialized() };
let mut vec;
let mutable_slice = if let Some(buffer_prefix) = buffer.get_mut(..slice.len()) {
buffer_prefix.copy_from_slice(slice);
buffer_prefix
} else {
vec = slice.to_vec();
&mut vec
};
for char16 in &mut mutable_slice[i..] {
if *char16 <= 0x7F {
*char16 = (*char16 as u8).to_ascii_lowercase() as u16
}
}
Atom::from(&*mutable_slice)
},
}
}
/// Return whether two atoms are ASCII-case-insensitive matches
pub fn eq_ignore_ascii_case(&self, other: &Self) -> bool {
if self == other {
return true;
}
let a = self.as_slice();
let b = other.as_slice();
a.len() == b.len() && a.iter().zip(b).all(|(&a16, &b16)| {
if a16 <= 0x7F && b16 <= 0x7F {
(a16 as u8).eq_ignore_ascii_case(&(b16 as u8))
} else {
a16 == b16
}
})
}
/// Return whether this atom is an ASCII-case-insensitive match for the given string
pub fn eq_str_ignore_ascii_case(&self, other: &str) -> bool {
self.chars()
.map(|r| r.map(|c: char| c.to_ascii_lowercase()))
.eq(other.chars().map(|c: char| Ok(c.to_ascii_lowercase())))
}
}
impl fmt::Debug for WeakAtom {
fn fmt(&self, w: &mut fmt::Formatter) -> fmt::Result {
write!(w, "Gecko WeakAtom({:p}, {})", self, self)
}
}
impl fmt::Display for WeakAtom {
fn fmt(&self, w: &mut fmt::Formatter) -> fmt::Result {
for c in self.chars() {
w.write_char(c.unwrap_or(char::REPLACEMENT_CHARACTER))?
}
Ok(())
}
}
impl Atom {
/// Execute a callback with the atom represented by `ptr`.
pub unsafe fn with<F, R>(ptr: *mut nsAtom, callback: F) -> R
where
F: FnOnce(&Atom) -> R,
{
let atom = Atom(WeakAtom::new(ptr));
let ret = callback(&atom);
mem::forget(atom);
ret
}
/// Creates an atom from an static atom pointer without checking in release
/// builds.
///
/// Right now it's only used by the atom macro, and ideally it should keep
/// that way, now we have sugar for is_static, creating atoms using
/// Atom::from_raw should involve almost no overhead.
#[inline]
pub unsafe fn from_static(ptr: *mut nsStaticAtom) -> Self {
let atom = Atom(ptr as *mut WeakAtom);
debug_assert!(
atom.is_static(),
"Called from_static for a non-static atom!"
);
atom
}
/// Creates an atom from an atom pointer.
#[inline(always)]
pub unsafe fn from_raw(ptr: *mut nsAtom) -> Self {
let atom = Atom(ptr as *mut WeakAtom);
if!atom.is_static() {
Gecko_AddRefAtom(ptr);
}
atom
}
/// Creates an atom from a dynamic atom pointer that has already had AddRef
/// called on it.
#[inline]
pub unsafe fn from_addrefed(ptr: *mut nsAtom) -> Self {
assert!(!ptr.is_null());
Atom(WeakAtom::new(ptr))
}
/// Convert this atom into an addrefed nsAtom pointer.
#[inline]
pub fn into_addrefed(self) -> *mut nsAtom {
let ptr = self.as_ptr();
mem::forget(self);
ptr
}
}
impl Hash for Atom {
fn hash<H>(&self, state: &mut H)
where
H: Hasher,
{
state.write_u32(self.get_hash());
}
}
impl Hash for WeakAtom {
fn hash<H>(&self, state: &mut H)
where
H: Hasher,
{
state.write_u32(self.get_hash());
}
}
impl Clone for Atom {
#[inline(always)]
fn clone(&self) -> Atom {
unsafe { Atom::from_raw(self.as_ptr()) }
}
}
impl Drop for Atom {
#[inline]
fn drop(&mut self) {
if!self.is_static() {
unsafe {
Gecko_ReleaseAtom(self.as_ptr());
}
}
}
}
impl Default for Atom {
#[inline]
fn default() -> Self {
atom!("")
}
}
impl fmt::Debug for Atom {
fn fmt(&self, w: &mut fmt::Formatter) -> fmt::Result {
write!(w, "Gecko Atom({:p}, {})", self.0, self)
}
}
impl fmt::Display for Atom {
fn fmt(&self, w: &mut fmt::Formatter) -> fmt::Result {
unsafe { (&*self.0).fmt(w) }
}
}
impl<'a> From<&'a str> for Atom {
#[inline]
fn from(string: &str) -> Atom {
debug_assert!(string.len() <= u32::max_value() as usize);
unsafe {
Atom(WeakAtom::new(Gecko_Atomize(
string.as_ptr() as *const _,
string.len() as u32,
)))
}
}
}
impl<'a> From<&'a [u16]> for Atom {
#[inline]
fn from(slice: &[u16]) -> Atom {
Atom::from(&*nsStr::from(slice))
}
}
impl<'a> From<&'a nsAString> for Atom {
#[inline]
fn from(string: &nsAString) -> Atom {
unsafe { Atom(WeakAtom::new(Gecko_Atomize16(string))) }
}
}
impl<'a> From<Cow<'a, str>> for Atom {
#[inline]
fn from(string: Cow<'a, str>) -> Atom {
Atom::from(&*string)
}
}
impl From<String> for Atom {
#[inline]
fn from(string: String) -> Atom {
Atom::from(&*string)
}
}
malloc_size_of_is_0!(Atom);
impl SpecifiedValueInfo for Atom {}
| new | identifier_name |
mod.rs | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
#![allow(unsafe_code)]
//! A drop-in replacement for string_cache, but backed by Gecko `nsAtom`s.
use gecko_bindings::bindings::Gecko_AddRefAtom;
use gecko_bindings::bindings::Gecko_Atomize;
use gecko_bindings::bindings::Gecko_Atomize16;
use gecko_bindings::bindings::Gecko_ReleaseAtom;
use gecko_bindings::structs::{nsAtom, nsAtom_AtomKind, nsDynamicAtom, nsStaticAtom};
use nsstring::{nsAString, nsStr};
use precomputed_hash::PrecomputedHash;
use std::{mem, slice, str};
use std::borrow::{Borrow, Cow};
use std::char::{self, DecodeUtf16};
use std::fmt::{self, Write};
use std::hash::{Hash, Hasher};
use std::iter::Cloned;
use std::ops::Deref;
use style_traits::SpecifiedValueInfo;
#[macro_use]
#[allow(improper_ctypes, non_camel_case_types, missing_docs)]
pub mod atom_macro {
include!(concat!(env!("OUT_DIR"), "/gecko/atom_macro.rs"));
}
#[macro_use]
pub mod namespace;
pub use self::namespace::{Namespace, WeakNamespace};
macro_rules! local_name {
($s:tt) => {
atom!($s)
};
}
/// A strong reference to a Gecko atom.
#[derive(Eq, PartialEq)]
pub struct Atom(*mut WeakAtom);
/// An atom *without* a strong reference.
///
/// Only usable as `&'a WeakAtom`,
/// where `'a` is the lifetime of something that holds a strong reference to that atom.
pub struct WeakAtom(nsAtom);
/// A BorrowedAtom for Gecko is just a weak reference to a `nsAtom`, that
/// hasn't been bumped.
pub type BorrowedAtom<'a> = &'a WeakAtom;
impl Deref for Atom {
type Target = WeakAtom;
#[inline]
fn deref(&self) -> &WeakAtom {
unsafe { &*self.0 }
}
}
impl PrecomputedHash for Atom {
#[inline]
fn precomputed_hash(&self) -> u32 {
self.get_hash()
}
}
impl Borrow<WeakAtom> for Atom {
#[inline]
fn borrow(&self) -> &WeakAtom {
self
}
}
impl Eq for WeakAtom {}
impl PartialEq for WeakAtom {
#[inline]
fn eq(&self, other: &Self) -> bool {
let weak: *const WeakAtom = self;
let other: *const WeakAtom = other;
weak == other
}
}
unsafe impl Send for Atom {}
unsafe impl Sync for Atom {}
unsafe impl Sync for WeakAtom {}
impl WeakAtom {
/// Construct a `WeakAtom` from a raw `nsAtom`.
#[inline]
pub unsafe fn new<'a>(atom: *const nsAtom) -> &'a mut Self {
&mut *(atom as *mut WeakAtom)
}
/// Clone this atom, bumping the refcount if the atom is not static.
#[inline]
pub fn clone(&self) -> Atom {
unsafe { Atom::from_raw(self.as_ptr()) }
}
/// Get the atom hash.
#[inline]
pub fn get_hash(&self) -> u32 {
self.0.mHash
}
/// Get the atom as a slice of utf-16 chars.
#[inline]
pub fn as_slice(&self) -> &[u16] {
let string = if self.is_static() {
let atom_ptr = self.as_ptr() as *const nsStaticAtom;
let string_offset = unsafe { (*atom_ptr).mStringOffset };
let string_offset = -(string_offset as isize);
let u8_ptr = atom_ptr as *const u8;
// It is safe to use offset() here because both addresses are within
// the same struct, e.g. mozilla::detail::gGkAtoms.
unsafe { u8_ptr.offset(string_offset) as *const u16 }
} else {
let atom_ptr = self.as_ptr() as *const nsDynamicAtom;
unsafe { (*(atom_ptr)).mString }
};
unsafe { slice::from_raw_parts(string, self.len() as usize) }
}
// NOTE: don't expose this, since it's slow, and easy to be misused.
fn chars(&self) -> DecodeUtf16<Cloned<slice::Iter<u16>>> {
char::decode_utf16(self.as_slice().iter().cloned())
}
/// Execute `cb` with the string that this atom represents.
///
/// Find alternatives to this function when possible, please, since it's
/// pretty slow.
pub fn with_str<F, Output>(&self, cb: F) -> Output
where
F: FnOnce(&str) -> Output,
{
let mut buffer: [u8; 64] = unsafe { mem::uninitialized() };
// The total string length in utf16 is going to be less than or equal
// the slice length (each utf16 character is going to take at least one
// and at most 2 items in the utf16 slice).
//
// Each of those characters will take at most four bytes in the utf8
// one. Thus if the slice is less than 64 / 4 (16) we can guarantee that
// we'll decode it in place.
let owned_string;
let len = self.len();
let utf8_slice = if len <= 16 {
let mut total_len = 0;
for c in self.chars() {
let c = c.unwrap_or(char::REPLACEMENT_CHARACTER);
let utf8_len = c.encode_utf8(&mut buffer[total_len..]).len();
total_len += utf8_len;
}
let slice = unsafe { str::from_utf8_unchecked(&buffer[..total_len]) };
debug_assert_eq!(slice, String::from_utf16_lossy(self.as_slice()));
slice
} else {
owned_string = String::from_utf16_lossy(self.as_slice());
&*owned_string
};
cb(utf8_slice)
}
/// Returns whether this atom is static.
#[inline]
pub fn is_static(&self) -> bool {
unsafe { (*self.as_ptr()).mKind() == nsAtom_AtomKind::Static as u32 }
}
/// Returns the length of the atom string.
#[inline]
pub fn len(&self) -> u32 {
unsafe { (*self.as_ptr()).mLength() }
}
/// Returns whether this atom is the empty string.
#[inline]
pub fn is_empty(&self) -> bool {
self.len() == 0
}
/// Returns the atom as a mutable pointer.
#[inline]
pub fn as_ptr(&self) -> *mut nsAtom {
let const_ptr: *const nsAtom = &self.0;
const_ptr as *mut nsAtom
}
/// Convert this atom to ASCII lower-case
pub fn to_ascii_lowercase(&self) -> Atom {
let slice = self.as_slice();
match slice
.iter()
.position(|&char16| (b'A' as u16) <= char16 && char16 <= (b'Z' as u16))
{
None => self.clone(),
Some(i) => | ,
}
}
/// Return whether two atoms are ASCII-case-insensitive matches
pub fn eq_ignore_ascii_case(&self, other: &Self) -> bool {
if self == other {
return true;
}
let a = self.as_slice();
let b = other.as_slice();
a.len() == b.len() && a.iter().zip(b).all(|(&a16, &b16)| {
if a16 <= 0x7F && b16 <= 0x7F {
(a16 as u8).eq_ignore_ascii_case(&(b16 as u8))
} else {
a16 == b16
}
})
}
/// Return whether this atom is an ASCII-case-insensitive match for the given string
pub fn eq_str_ignore_ascii_case(&self, other: &str) -> bool {
self.chars()
.map(|r| r.map(|c: char| c.to_ascii_lowercase()))
.eq(other.chars().map(|c: char| Ok(c.to_ascii_lowercase())))
}
}
impl fmt::Debug for WeakAtom {
fn fmt(&self, w: &mut fmt::Formatter) -> fmt::Result {
write!(w, "Gecko WeakAtom({:p}, {})", self, self)
}
}
impl fmt::Display for WeakAtom {
fn fmt(&self, w: &mut fmt::Formatter) -> fmt::Result {
for c in self.chars() {
w.write_char(c.unwrap_or(char::REPLACEMENT_CHARACTER))?
}
Ok(())
}
}
impl Atom {
/// Execute a callback with the atom represented by `ptr`.
pub unsafe fn with<F, R>(ptr: *mut nsAtom, callback: F) -> R
where
F: FnOnce(&Atom) -> R,
{
let atom = Atom(WeakAtom::new(ptr));
let ret = callback(&atom);
mem::forget(atom);
ret
}
/// Creates an atom from an static atom pointer without checking in release
/// builds.
///
/// Right now it's only used by the atom macro, and ideally it should keep
/// that way, now we have sugar for is_static, creating atoms using
/// Atom::from_raw should involve almost no overhead.
#[inline]
pub unsafe fn from_static(ptr: *mut nsStaticAtom) -> Self {
let atom = Atom(ptr as *mut WeakAtom);
debug_assert!(
atom.is_static(),
"Called from_static for a non-static atom!"
);
atom
}
/// Creates an atom from an atom pointer.
#[inline(always)]
pub unsafe fn from_raw(ptr: *mut nsAtom) -> Self {
let atom = Atom(ptr as *mut WeakAtom);
if!atom.is_static() {
Gecko_AddRefAtom(ptr);
}
atom
}
/// Creates an atom from a dynamic atom pointer that has already had AddRef
/// called on it.
#[inline]
pub unsafe fn from_addrefed(ptr: *mut nsAtom) -> Self {
assert!(!ptr.is_null());
Atom(WeakAtom::new(ptr))
}
/// Convert this atom into an addrefed nsAtom pointer.
#[inline]
pub fn into_addrefed(self) -> *mut nsAtom {
let ptr = self.as_ptr();
mem::forget(self);
ptr
}
}
impl Hash for Atom {
fn hash<H>(&self, state: &mut H)
where
H: Hasher,
{
state.write_u32(self.get_hash());
}
}
impl Hash for WeakAtom {
fn hash<H>(&self, state: &mut H)
where
H: Hasher,
{
state.write_u32(self.get_hash());
}
}
impl Clone for Atom {
#[inline(always)]
fn clone(&self) -> Atom {
unsafe { Atom::from_raw(self.as_ptr()) }
}
}
impl Drop for Atom {
#[inline]
fn drop(&mut self) {
if!self.is_static() {
unsafe {
Gecko_ReleaseAtom(self.as_ptr());
}
}
}
}
impl Default for Atom {
#[inline]
fn default() -> Self {
atom!("")
}
}
impl fmt::Debug for Atom {
fn fmt(&self, w: &mut fmt::Formatter) -> fmt::Result {
write!(w, "Gecko Atom({:p}, {})", self.0, self)
}
}
impl fmt::Display for Atom {
fn fmt(&self, w: &mut fmt::Formatter) -> fmt::Result {
unsafe { (&*self.0).fmt(w) }
}
}
impl<'a> From<&'a str> for Atom {
#[inline]
fn from(string: &str) -> Atom {
debug_assert!(string.len() <= u32::max_value() as usize);
unsafe {
Atom(WeakAtom::new(Gecko_Atomize(
string.as_ptr() as *const _,
string.len() as u32,
)))
}
}
}
impl<'a> From<&'a [u16]> for Atom {
#[inline]
fn from(slice: &[u16]) -> Atom {
Atom::from(&*nsStr::from(slice))
}
}
impl<'a> From<&'a nsAString> for Atom {
#[inline]
fn from(string: &nsAString) -> Atom {
unsafe { Atom(WeakAtom::new(Gecko_Atomize16(string))) }
}
}
impl<'a> From<Cow<'a, str>> for Atom {
#[inline]
fn from(string: Cow<'a, str>) -> Atom {
Atom::from(&*string)
}
}
impl From<String> for Atom {
#[inline]
fn from(string: String) -> Atom {
Atom::from(&*string)
}
}
malloc_size_of_is_0!(Atom);
impl SpecifiedValueInfo for Atom {}
| {
let mut buffer: [u16; 64] = unsafe { mem::uninitialized() };
let mut vec;
let mutable_slice = if let Some(buffer_prefix) = buffer.get_mut(..slice.len()) {
buffer_prefix.copy_from_slice(slice);
buffer_prefix
} else {
vec = slice.to_vec();
&mut vec
};
for char16 in &mut mutable_slice[i..] {
if *char16 <= 0x7F {
*char16 = (*char16 as u8).to_ascii_lowercase() as u16
}
}
Atom::from(&*mutable_slice)
} | conditional_block |
mod.rs | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
#![allow(unsafe_code)]
//! A drop-in replacement for string_cache, but backed by Gecko `nsAtom`s.
use gecko_bindings::bindings::Gecko_AddRefAtom;
use gecko_bindings::bindings::Gecko_Atomize;
use gecko_bindings::bindings::Gecko_Atomize16;
use gecko_bindings::bindings::Gecko_ReleaseAtom;
use gecko_bindings::structs::{nsAtom, nsAtom_AtomKind, nsDynamicAtom, nsStaticAtom};
use nsstring::{nsAString, nsStr};
use precomputed_hash::PrecomputedHash;
use std::{mem, slice, str};
use std::borrow::{Borrow, Cow};
use std::char::{self, DecodeUtf16};
use std::fmt::{self, Write};
use std::hash::{Hash, Hasher};
use std::iter::Cloned;
use std::ops::Deref;
use style_traits::SpecifiedValueInfo;
#[macro_use]
#[allow(improper_ctypes, non_camel_case_types, missing_docs)]
pub mod atom_macro {
include!(concat!(env!("OUT_DIR"), "/gecko/atom_macro.rs"));
}
#[macro_use]
pub mod namespace;
pub use self::namespace::{Namespace, WeakNamespace};
macro_rules! local_name {
($s:tt) => {
atom!($s)
};
}
/// A strong reference to a Gecko atom.
#[derive(Eq, PartialEq)]
pub struct Atom(*mut WeakAtom);
/// An atom *without* a strong reference.
///
/// Only usable as `&'a WeakAtom`,
/// where `'a` is the lifetime of something that holds a strong reference to that atom.
pub struct WeakAtom(nsAtom);
/// A BorrowedAtom for Gecko is just a weak reference to a `nsAtom`, that
/// hasn't been bumped.
pub type BorrowedAtom<'a> = &'a WeakAtom;
impl Deref for Atom {
type Target = WeakAtom;
#[inline]
fn deref(&self) -> &WeakAtom {
unsafe { &*self.0 }
}
}
impl PrecomputedHash for Atom {
#[inline]
fn precomputed_hash(&self) -> u32 {
self.get_hash()
}
}
impl Borrow<WeakAtom> for Atom {
#[inline]
fn borrow(&self) -> &WeakAtom {
self
}
}
impl Eq for WeakAtom {}
impl PartialEq for WeakAtom {
#[inline]
fn eq(&self, other: &Self) -> bool {
let weak: *const WeakAtom = self;
let other: *const WeakAtom = other;
weak == other
}
}
unsafe impl Send for Atom {}
unsafe impl Sync for Atom {}
unsafe impl Sync for WeakAtom {}
impl WeakAtom {
/// Construct a `WeakAtom` from a raw `nsAtom`.
#[inline]
pub unsafe fn new<'a>(atom: *const nsAtom) -> &'a mut Self {
&mut *(atom as *mut WeakAtom)
}
/// Clone this atom, bumping the refcount if the atom is not static.
#[inline]
pub fn clone(&self) -> Atom {
unsafe { Atom::from_raw(self.as_ptr()) }
}
/// Get the atom hash.
#[inline]
pub fn get_hash(&self) -> u32 {
self.0.mHash
}
/// Get the atom as a slice of utf-16 chars.
#[inline]
pub fn as_slice(&self) -> &[u16] {
let string = if self.is_static() {
let atom_ptr = self.as_ptr() as *const nsStaticAtom;
let string_offset = unsafe { (*atom_ptr).mStringOffset };
let string_offset = -(string_offset as isize);
let u8_ptr = atom_ptr as *const u8;
// It is safe to use offset() here because both addresses are within
// the same struct, e.g. mozilla::detail::gGkAtoms.
unsafe { u8_ptr.offset(string_offset) as *const u16 }
} else {
let atom_ptr = self.as_ptr() as *const nsDynamicAtom;
unsafe { (*(atom_ptr)).mString }
};
unsafe { slice::from_raw_parts(string, self.len() as usize) }
}
// NOTE: don't expose this, since it's slow, and easy to be misused.
fn chars(&self) -> DecodeUtf16<Cloned<slice::Iter<u16>>> {
char::decode_utf16(self.as_slice().iter().cloned())
}
/// Execute `cb` with the string that this atom represents.
///
/// Find alternatives to this function when possible, please, since it's
/// pretty slow.
pub fn with_str<F, Output>(&self, cb: F) -> Output
where
F: FnOnce(&str) -> Output,
{
let mut buffer: [u8; 64] = unsafe { mem::uninitialized() };
// The total string length in utf16 is going to be less than or equal
// the slice length (each utf16 character is going to take at least one
// and at most 2 items in the utf16 slice).
//
// Each of those characters will take at most four bytes in the utf8
// one. Thus if the slice is less than 64 / 4 (16) we can guarantee that
// we'll decode it in place.
let owned_string;
let len = self.len();
let utf8_slice = if len <= 16 {
let mut total_len = 0;
for c in self.chars() {
let c = c.unwrap_or(char::REPLACEMENT_CHARACTER);
let utf8_len = c.encode_utf8(&mut buffer[total_len..]).len();
total_len += utf8_len;
}
let slice = unsafe { str::from_utf8_unchecked(&buffer[..total_len]) };
debug_assert_eq!(slice, String::from_utf16_lossy(self.as_slice()));
slice
} else {
owned_string = String::from_utf16_lossy(self.as_slice());
&*owned_string
};
cb(utf8_slice)
}
/// Returns whether this atom is static.
#[inline]
pub fn is_static(&self) -> bool {
unsafe { (*self.as_ptr()).mKind() == nsAtom_AtomKind::Static as u32 }
}
/// Returns the length of the atom string.
#[inline]
pub fn len(&self) -> u32 {
unsafe { (*self.as_ptr()).mLength() }
}
/// Returns whether this atom is the empty string.
#[inline]
pub fn is_empty(&self) -> bool {
self.len() == 0
}
/// Returns the atom as a mutable pointer.
#[inline]
pub fn as_ptr(&self) -> *mut nsAtom {
let const_ptr: *const nsAtom = &self.0;
const_ptr as *mut nsAtom
}
/// Convert this atom to ASCII lower-case
pub fn to_ascii_lowercase(&self) -> Atom {
let slice = self.as_slice();
match slice
.iter()
.position(|&char16| (b'A' as u16) <= char16 && char16 <= (b'Z' as u16))
{
None => self.clone(),
Some(i) => {
let mut buffer: [u16; 64] = unsafe { mem::uninitialized() };
let mut vec;
let mutable_slice = if let Some(buffer_prefix) = buffer.get_mut(..slice.len()) {
buffer_prefix.copy_from_slice(slice);
buffer_prefix
} else {
vec = slice.to_vec();
&mut vec
};
for char16 in &mut mutable_slice[i..] {
if *char16 <= 0x7F {
*char16 = (*char16 as u8).to_ascii_lowercase() as u16
}
}
Atom::from(&*mutable_slice)
},
}
}
/// Return whether two atoms are ASCII-case-insensitive matches
pub fn eq_ignore_ascii_case(&self, other: &Self) -> bool {
if self == other {
return true;
}
let a = self.as_slice();
let b = other.as_slice();
a.len() == b.len() && a.iter().zip(b).all(|(&a16, &b16)| {
if a16 <= 0x7F && b16 <= 0x7F {
(a16 as u8).eq_ignore_ascii_case(&(b16 as u8))
} else {
a16 == b16
}
})
}
/// Return whether this atom is an ASCII-case-insensitive match for the given string
pub fn eq_str_ignore_ascii_case(&self, other: &str) -> bool {
self.chars()
.map(|r| r.map(|c: char| c.to_ascii_lowercase()))
.eq(other.chars().map(|c: char| Ok(c.to_ascii_lowercase())))
}
}
impl fmt::Debug for WeakAtom {
fn fmt(&self, w: &mut fmt::Formatter) -> fmt::Result {
write!(w, "Gecko WeakAtom({:p}, {})", self, self)
}
}
impl fmt::Display for WeakAtom {
fn fmt(&self, w: &mut fmt::Formatter) -> fmt::Result {
for c in self.chars() {
w.write_char(c.unwrap_or(char::REPLACEMENT_CHARACTER))?
}
Ok(())
}
}
impl Atom {
/// Execute a callback with the atom represented by `ptr`.
pub unsafe fn with<F, R>(ptr: *mut nsAtom, callback: F) -> R
where
F: FnOnce(&Atom) -> R,
{
let atom = Atom(WeakAtom::new(ptr));
let ret = callback(&atom);
mem::forget(atom);
ret
}
/// Creates an atom from an static atom pointer without checking in release
/// builds.
///
/// Right now it's only used by the atom macro, and ideally it should keep
/// that way, now we have sugar for is_static, creating atoms using
/// Atom::from_raw should involve almost no overhead.
#[inline]
pub unsafe fn from_static(ptr: *mut nsStaticAtom) -> Self {
let atom = Atom(ptr as *mut WeakAtom);
debug_assert!(
atom.is_static(),
"Called from_static for a non-static atom!"
);
atom
}
/// Creates an atom from an atom pointer.
#[inline(always)]
pub unsafe fn from_raw(ptr: *mut nsAtom) -> Self {
let atom = Atom(ptr as *mut WeakAtom);
if!atom.is_static() {
Gecko_AddRefAtom(ptr);
}
atom
}
/// Creates an atom from a dynamic atom pointer that has already had AddRef
/// called on it.
#[inline]
pub unsafe fn from_addrefed(ptr: *mut nsAtom) -> Self {
assert!(!ptr.is_null());
Atom(WeakAtom::new(ptr))
}
/// Convert this atom into an addrefed nsAtom pointer.
#[inline]
pub fn into_addrefed(self) -> *mut nsAtom {
let ptr = self.as_ptr();
mem::forget(self);
ptr
}
}
impl Hash for Atom {
fn hash<H>(&self, state: &mut H)
where
H: Hasher,
{
state.write_u32(self.get_hash());
}
}
impl Hash for WeakAtom {
fn hash<H>(&self, state: &mut H)
where
H: Hasher,
{
state.write_u32(self.get_hash());
}
}
impl Clone for Atom {
#[inline(always)]
fn clone(&self) -> Atom {
unsafe { Atom::from_raw(self.as_ptr()) }
}
}
impl Drop for Atom {
#[inline]
fn drop(&mut self) {
if!self.is_static() {
unsafe {
Gecko_ReleaseAtom(self.as_ptr());
}
}
}
}
impl Default for Atom {
#[inline]
fn default() -> Self {
atom!("")
}
}
impl fmt::Debug for Atom {
fn fmt(&self, w: &mut fmt::Formatter) -> fmt::Result |
}
impl fmt::Display for Atom {
fn fmt(&self, w: &mut fmt::Formatter) -> fmt::Result {
unsafe { (&*self.0).fmt(w) }
}
}
impl<'a> From<&'a str> for Atom {
#[inline]
fn from(string: &str) -> Atom {
debug_assert!(string.len() <= u32::max_value() as usize);
unsafe {
Atom(WeakAtom::new(Gecko_Atomize(
string.as_ptr() as *const _,
string.len() as u32,
)))
}
}
}
impl<'a> From<&'a [u16]> for Atom {
#[inline]
fn from(slice: &[u16]) -> Atom {
Atom::from(&*nsStr::from(slice))
}
}
impl<'a> From<&'a nsAString> for Atom {
#[inline]
fn from(string: &nsAString) -> Atom {
unsafe { Atom(WeakAtom::new(Gecko_Atomize16(string))) }
}
}
impl<'a> From<Cow<'a, str>> for Atom {
#[inline]
fn from(string: Cow<'a, str>) -> Atom {
Atom::from(&*string)
}
}
impl From<String> for Atom {
#[inline]
fn from(string: String) -> Atom {
Atom::from(&*string)
}
}
malloc_size_of_is_0!(Atom);
impl SpecifiedValueInfo for Atom {}
| {
write!(w, "Gecko Atom({:p}, {})", self.0, self)
} | identifier_body |
main.rs | use std::collections::HashMap;
use std::io::{self, BufRead};
use lazy_regex::regex;
use regex::Regex;
use structopt::StructOpt;
type H = HashMap<Header, Vec<(String, String, String)>>;
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
enum Header {
Versioned { package: String, version: String },
Missing { package: String },
}
#[derive(Debug, StructOpt)]
#[structopt(
name = "commenter",
about = "Automates generation of bounds in build-constraints.yaml"
)]
enum Opt {
Clear,
Add,
Outdated,
}
fn main() {
let opt = Opt::from_args();
match opt {
Opt::Clear => clear(),
Opt::Add => add(),
Opt::Outdated => outdated(),
}
}
fn clear() {
commenter::clear();
}
fn outdated() {
commenter::outdated();
}
fn add() {
let mut lib_exes: H = Default::default();
let mut tests: H = Default::default();
let mut benches: H = Default::default();
let mut last_header: Option<Header> = None;
let header_versioned = regex!(
r#"^(?P<package>[a-zA-z]([a-zA-z0-9.-]*?))-(?P<version>(\d+(\.\d+)*)).+?is out of bounds for:$"#
);
let header_missing = regex!(r#"^(?P<package>[a-zA-z]([a-zA-z0-9.-]*)).+?depended on by:$"#);
let package = regex!(
r#"^- \[ \] (?P<package>[a-zA-z]([a-zA-z0-9.-]*?))-(?P<version>(\d+(\.\d+)*)).+?Used by: (?P<component>.+)$"#
);
// Ignore everything until the bounds issues show up.
let mut process_line = false;
for line in io::stdin().lock().lines().flatten() {
if is_reg_match(&line, regex!(r#"^\s*$"#)) {
// noop
} else if line == "curator: Snapshot dependency graph contains errors:" {
process_line = true;
} else if!process_line {
println!("[INFO] {}", line);
} else if let Some(cap) = package.captures(&line) {
let root = last_header.clone().unwrap();
let package = cap.name("package").unwrap().as_str();
let version = cap.name("version").unwrap().as_str();
let component = cap.name("component").unwrap().as_str();
match component {
"library" | "executable" => {
insert(&mut lib_exes, root, package, version, component)
}
"benchmark" => insert(&mut benches, root, package, version, "benchmarks"),
"test-suite" => insert(&mut tests, root, package, version, component),
_ => panic!("Bad component: {}", component),
}
} else if let Some(cap) = header_versioned.captures(&line) {
let package = cap.name("package").unwrap().as_str().to_owned();
let version = cap.name("version").unwrap().as_str().to_owned();
last_header = Some(Header::Versioned { package, version });
} else if let Some(cap) = header_missing.captures(&line) {
let package = cap.name("package").unwrap().as_str().to_owned();
last_header = Some(Header::Missing { package });
} else {
panic!("Unhandled: {:?}", line);
}
}
let mut auto_lib_exes = vec![];
let mut auto_tests = vec![];
let mut auto_benches = vec![];
if!lib_exes.is_empty() {
println!("\nLIBS + EXES\n");
}
for (header, packages) in lib_exes {
for (package, version, component) in packages {
let s = printer(" ", &package, true, &version, &component, &header);
println!("{}", s);
auto_lib_exes.push(s);
} | println!("\nTESTS\n");
}
for (header, packages) in tests {
for (package, version, component) in packages {
let s = printer(" ", &package, false, &version, &component, &header);
println!("{}", s);
auto_tests.push(s);
}
}
if!benches.is_empty() {
println!("\nBENCHMARKS\n");
}
for (header, packages) in benches {
for (package, version, component) in packages {
let s = printer(" ", &package, false, &version, &component, &header);
println!("{}", s);
auto_benches.push(s);
}
}
println!();
println!(
"Adding {lib_exes} libs, {tests} tests, {benches} benches to build-constraints.yaml",
lib_exes = auto_lib_exes.len(),
tests = auto_tests.len(),
benches = auto_benches.len()
);
commenter::add(auto_lib_exes, auto_tests, auto_benches);
}
fn printer(
indent: &str,
package: &str,
lt0: bool,
version: &str,
component: &str,
header: &Header,
) -> String {
let lt0 = if lt0 { " < 0" } else { "" };
format!(
"{indent}- {package}{lt0} # tried {package}-{version}, but its *{component}* {cause}",
indent = indent,
package = package,
lt0 = lt0,
version = version,
component = component,
cause = match header {
Header::Versioned { package, version } => format!(
"does not support: {package}-{version}",
package = package,
version = version
),
Header::Missing { package } => format!(
"requires the disabled package: {package}",
package = package
),
},
)
}
fn insert(h: &mut H, header: Header, package: &str, version: &str, component: &str) {
(*h.entry(header).or_insert_with(Vec::new)).push((
package.to_owned(),
version.to_owned(),
component.to_owned(),
));
}
fn is_reg_match(s: &str, r: &Regex) -> bool {
r.captures(s).is_some()
} | }
if !tests.is_empty() { | random_line_split |
main.rs | use std::collections::HashMap;
use std::io::{self, BufRead};
use lazy_regex::regex;
use regex::Regex;
use structopt::StructOpt;
type H = HashMap<Header, Vec<(String, String, String)>>;
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
enum Header {
Versioned { package: String, version: String },
Missing { package: String },
}
#[derive(Debug, StructOpt)]
#[structopt(
name = "commenter",
about = "Automates generation of bounds in build-constraints.yaml"
)]
enum Opt {
Clear,
Add,
Outdated,
}
fn main() {
let opt = Opt::from_args();
match opt {
Opt::Clear => clear(),
Opt::Add => add(),
Opt::Outdated => outdated(),
}
}
fn clear() {
commenter::clear();
}
fn outdated() |
fn add() {
let mut lib_exes: H = Default::default();
let mut tests: H = Default::default();
let mut benches: H = Default::default();
let mut last_header: Option<Header> = None;
let header_versioned = regex!(
r#"^(?P<package>[a-zA-z]([a-zA-z0-9.-]*?))-(?P<version>(\d+(\.\d+)*)).+?is out of bounds for:$"#
);
let header_missing = regex!(r#"^(?P<package>[a-zA-z]([a-zA-z0-9.-]*)).+?depended on by:$"#);
let package = regex!(
r#"^- \[ \] (?P<package>[a-zA-z]([a-zA-z0-9.-]*?))-(?P<version>(\d+(\.\d+)*)).+?Used by: (?P<component>.+)$"#
);
// Ignore everything until the bounds issues show up.
let mut process_line = false;
for line in io::stdin().lock().lines().flatten() {
if is_reg_match(&line, regex!(r#"^\s*$"#)) {
// noop
} else if line == "curator: Snapshot dependency graph contains errors:" {
process_line = true;
} else if!process_line {
println!("[INFO] {}", line);
} else if let Some(cap) = package.captures(&line) {
let root = last_header.clone().unwrap();
let package = cap.name("package").unwrap().as_str();
let version = cap.name("version").unwrap().as_str();
let component = cap.name("component").unwrap().as_str();
match component {
"library" | "executable" => {
insert(&mut lib_exes, root, package, version, component)
}
"benchmark" => insert(&mut benches, root, package, version, "benchmarks"),
"test-suite" => insert(&mut tests, root, package, version, component),
_ => panic!("Bad component: {}", component),
}
} else if let Some(cap) = header_versioned.captures(&line) {
let package = cap.name("package").unwrap().as_str().to_owned();
let version = cap.name("version").unwrap().as_str().to_owned();
last_header = Some(Header::Versioned { package, version });
} else if let Some(cap) = header_missing.captures(&line) {
let package = cap.name("package").unwrap().as_str().to_owned();
last_header = Some(Header::Missing { package });
} else {
panic!("Unhandled: {:?}", line);
}
}
let mut auto_lib_exes = vec![];
let mut auto_tests = vec![];
let mut auto_benches = vec![];
if!lib_exes.is_empty() {
println!("\nLIBS + EXES\n");
}
for (header, packages) in lib_exes {
for (package, version, component) in packages {
let s = printer(" ", &package, true, &version, &component, &header);
println!("{}", s);
auto_lib_exes.push(s);
}
}
if!tests.is_empty() {
println!("\nTESTS\n");
}
for (header, packages) in tests {
for (package, version, component) in packages {
let s = printer(" ", &package, false, &version, &component, &header);
println!("{}", s);
auto_tests.push(s);
}
}
if!benches.is_empty() {
println!("\nBENCHMARKS\n");
}
for (header, packages) in benches {
for (package, version, component) in packages {
let s = printer(" ", &package, false, &version, &component, &header);
println!("{}", s);
auto_benches.push(s);
}
}
println!();
println!(
"Adding {lib_exes} libs, {tests} tests, {benches} benches to build-constraints.yaml",
lib_exes = auto_lib_exes.len(),
tests = auto_tests.len(),
benches = auto_benches.len()
);
commenter::add(auto_lib_exes, auto_tests, auto_benches);
}
fn printer(
indent: &str,
package: &str,
lt0: bool,
version: &str,
component: &str,
header: &Header,
) -> String {
let lt0 = if lt0 { " < 0" } else { "" };
format!(
"{indent}- {package}{lt0} # tried {package}-{version}, but its *{component}* {cause}",
indent = indent,
package = package,
lt0 = lt0,
version = version,
component = component,
cause = match header {
Header::Versioned { package, version } => format!(
"does not support: {package}-{version}",
package = package,
version = version
),
Header::Missing { package } => format!(
"requires the disabled package: {package}",
package = package
),
},
)
}
fn insert(h: &mut H, header: Header, package: &str, version: &str, component: &str) {
(*h.entry(header).or_insert_with(Vec::new)).push((
package.to_owned(),
version.to_owned(),
component.to_owned(),
));
}
fn is_reg_match(s: &str, r: &Regex) -> bool {
r.captures(s).is_some()
}
| {
commenter::outdated();
} | identifier_body |
main.rs | use std::collections::HashMap;
use std::io::{self, BufRead};
use lazy_regex::regex;
use regex::Regex;
use structopt::StructOpt;
type H = HashMap<Header, Vec<(String, String, String)>>;
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
enum Header {
Versioned { package: String, version: String },
Missing { package: String },
}
#[derive(Debug, StructOpt)]
#[structopt(
name = "commenter",
about = "Automates generation of bounds in build-constraints.yaml"
)]
enum Opt {
Clear,
Add,
Outdated,
}
fn main() {
let opt = Opt::from_args();
match opt {
Opt::Clear => clear(),
Opt::Add => add(),
Opt::Outdated => outdated(),
}
}
fn clear() {
commenter::clear();
}
fn outdated() {
commenter::outdated();
}
fn add() {
let mut lib_exes: H = Default::default();
let mut tests: H = Default::default();
let mut benches: H = Default::default();
let mut last_header: Option<Header> = None;
let header_versioned = regex!(
r#"^(?P<package>[a-zA-z]([a-zA-z0-9.-]*?))-(?P<version>(\d+(\.\d+)*)).+?is out of bounds for:$"#
);
let header_missing = regex!(r#"^(?P<package>[a-zA-z]([a-zA-z0-9.-]*)).+?depended on by:$"#);
let package = regex!(
r#"^- \[ \] (?P<package>[a-zA-z]([a-zA-z0-9.-]*?))-(?P<version>(\d+(\.\d+)*)).+?Used by: (?P<component>.+)$"#
);
// Ignore everything until the bounds issues show up.
let mut process_line = false;
for line in io::stdin().lock().lines().flatten() {
if is_reg_match(&line, regex!(r#"^\s*$"#)) {
// noop
} else if line == "curator: Snapshot dependency graph contains errors:" {
process_line = true;
} else if!process_line {
println!("[INFO] {}", line);
} else if let Some(cap) = package.captures(&line) {
let root = last_header.clone().unwrap();
let package = cap.name("package").unwrap().as_str();
let version = cap.name("version").unwrap().as_str();
let component = cap.name("component").unwrap().as_str();
match component {
"library" | "executable" => {
insert(&mut lib_exes, root, package, version, component)
}
"benchmark" => insert(&mut benches, root, package, version, "benchmarks"),
"test-suite" => insert(&mut tests, root, package, version, component),
_ => panic!("Bad component: {}", component),
}
} else if let Some(cap) = header_versioned.captures(&line) {
let package = cap.name("package").unwrap().as_str().to_owned();
let version = cap.name("version").unwrap().as_str().to_owned();
last_header = Some(Header::Versioned { package, version });
} else if let Some(cap) = header_missing.captures(&line) {
let package = cap.name("package").unwrap().as_str().to_owned();
last_header = Some(Header::Missing { package });
} else {
panic!("Unhandled: {:?}", line);
}
}
let mut auto_lib_exes = vec![];
let mut auto_tests = vec![];
let mut auto_benches = vec![];
if!lib_exes.is_empty() {
println!("\nLIBS + EXES\n");
}
for (header, packages) in lib_exes {
for (package, version, component) in packages {
let s = printer(" ", &package, true, &version, &component, &header);
println!("{}", s);
auto_lib_exes.push(s);
}
}
if!tests.is_empty() {
println!("\nTESTS\n");
}
for (header, packages) in tests {
for (package, version, component) in packages {
let s = printer(" ", &package, false, &version, &component, &header);
println!("{}", s);
auto_tests.push(s);
}
}
if!benches.is_empty() {
println!("\nBENCHMARKS\n");
}
for (header, packages) in benches {
for (package, version, component) in packages {
let s = printer(" ", &package, false, &version, &component, &header);
println!("{}", s);
auto_benches.push(s);
}
}
println!();
println!(
"Adding {lib_exes} libs, {tests} tests, {benches} benches to build-constraints.yaml",
lib_exes = auto_lib_exes.len(),
tests = auto_tests.len(),
benches = auto_benches.len()
);
commenter::add(auto_lib_exes, auto_tests, auto_benches);
}
fn printer(
indent: &str,
package: &str,
lt0: bool,
version: &str,
component: &str,
header: &Header,
) -> String {
let lt0 = if lt0 { " < 0" } else { "" };
format!(
"{indent}- {package}{lt0} # tried {package}-{version}, but its *{component}* {cause}",
indent = indent,
package = package,
lt0 = lt0,
version = version,
component = component,
cause = match header {
Header::Versioned { package, version } => format!(
"does not support: {package}-{version}",
package = package,
version = version
),
Header::Missing { package } => format!(
"requires the disabled package: {package}",
package = package
),
},
)
}
fn insert(h: &mut H, header: Header, package: &str, version: &str, component: &str) {
(*h.entry(header).or_insert_with(Vec::new)).push((
package.to_owned(),
version.to_owned(),
component.to_owned(),
));
}
fn | (s: &str, r: &Regex) -> bool {
r.captures(s).is_some()
}
| is_reg_match | identifier_name |
main.rs | use std::collections::HashMap;
use std::io::{self, BufRead};
use lazy_regex::regex;
use regex::Regex;
use structopt::StructOpt;
type H = HashMap<Header, Vec<(String, String, String)>>;
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
enum Header {
Versioned { package: String, version: String },
Missing { package: String },
}
#[derive(Debug, StructOpt)]
#[structopt(
name = "commenter",
about = "Automates generation of bounds in build-constraints.yaml"
)]
enum Opt {
Clear,
Add,
Outdated,
}
fn main() {
let opt = Opt::from_args();
match opt {
Opt::Clear => clear(),
Opt::Add => add(),
Opt::Outdated => outdated(),
}
}
fn clear() {
commenter::clear();
}
fn outdated() {
commenter::outdated();
}
fn add() {
let mut lib_exes: H = Default::default();
let mut tests: H = Default::default();
let mut benches: H = Default::default();
let mut last_header: Option<Header> = None;
let header_versioned = regex!(
r#"^(?P<package>[a-zA-z]([a-zA-z0-9.-]*?))-(?P<version>(\d+(\.\d+)*)).+?is out of bounds for:$"#
);
let header_missing = regex!(r#"^(?P<package>[a-zA-z]([a-zA-z0-9.-]*)).+?depended on by:$"#);
let package = regex!(
r#"^- \[ \] (?P<package>[a-zA-z]([a-zA-z0-9.-]*?))-(?P<version>(\d+(\.\d+)*)).+?Used by: (?P<component>.+)$"#
);
// Ignore everything until the bounds issues show up.
let mut process_line = false;
for line in io::stdin().lock().lines().flatten() {
if is_reg_match(&line, regex!(r#"^\s*$"#)) {
// noop
} else if line == "curator: Snapshot dependency graph contains errors:" {
process_line = true;
} else if!process_line {
println!("[INFO] {}", line);
} else if let Some(cap) = package.captures(&line) {
let root = last_header.clone().unwrap();
let package = cap.name("package").unwrap().as_str();
let version = cap.name("version").unwrap().as_str();
let component = cap.name("component").unwrap().as_str();
match component {
"library" | "executable" => {
insert(&mut lib_exes, root, package, version, component)
}
"benchmark" => insert(&mut benches, root, package, version, "benchmarks"),
"test-suite" => insert(&mut tests, root, package, version, component),
_ => panic!("Bad component: {}", component),
}
} else if let Some(cap) = header_versioned.captures(&line) {
let package = cap.name("package").unwrap().as_str().to_owned();
let version = cap.name("version").unwrap().as_str().to_owned();
last_header = Some(Header::Versioned { package, version });
} else if let Some(cap) = header_missing.captures(&line) {
let package = cap.name("package").unwrap().as_str().to_owned();
last_header = Some(Header::Missing { package });
} else {
panic!("Unhandled: {:?}", line);
}
}
let mut auto_lib_exes = vec![];
let mut auto_tests = vec![];
let mut auto_benches = vec![];
if!lib_exes.is_empty() {
println!("\nLIBS + EXES\n");
}
for (header, packages) in lib_exes {
for (package, version, component) in packages {
let s = printer(" ", &package, true, &version, &component, &header);
println!("{}", s);
auto_lib_exes.push(s);
}
}
if!tests.is_empty() {
println!("\nTESTS\n");
}
for (header, packages) in tests {
for (package, version, component) in packages {
let s = printer(" ", &package, false, &version, &component, &header);
println!("{}", s);
auto_tests.push(s);
}
}
if!benches.is_empty() {
println!("\nBENCHMARKS\n");
}
for (header, packages) in benches {
for (package, version, component) in packages {
let s = printer(" ", &package, false, &version, &component, &header);
println!("{}", s);
auto_benches.push(s);
}
}
println!();
println!(
"Adding {lib_exes} libs, {tests} tests, {benches} benches to build-constraints.yaml",
lib_exes = auto_lib_exes.len(),
tests = auto_tests.len(),
benches = auto_benches.len()
);
commenter::add(auto_lib_exes, auto_tests, auto_benches);
}
fn printer(
indent: &str,
package: &str,
lt0: bool,
version: &str,
component: &str,
header: &Header,
) -> String {
let lt0 = if lt0 { " < 0" } else | ;
format!(
"{indent}- {package}{lt0} # tried {package}-{version}, but its *{component}* {cause}",
indent = indent,
package = package,
lt0 = lt0,
version = version,
component = component,
cause = match header {
Header::Versioned { package, version } => format!(
"does not support: {package}-{version}",
package = package,
version = version
),
Header::Missing { package } => format!(
"requires the disabled package: {package}",
package = package
),
},
)
}
fn insert(h: &mut H, header: Header, package: &str, version: &str, component: &str) {
(*h.entry(header).or_insert_with(Vec::new)).push((
package.to_owned(),
version.to_owned(),
component.to_owned(),
));
}
fn is_reg_match(s: &str, r: &Regex) -> bool {
r.captures(s).is_some()
}
| { "" } | conditional_block |
trait-cast-generic.rs | // Copyright 2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
// Testing casting of a generic Struct to a Trait with a generic method.
// This is test for issue 10955.
#[allow(unused_variable)];
trait Foo {
fn f<A>(a: A) -> A {
a
}
}
struct Bar<T> {
x: T,
}
impl<T> Foo for Bar<T> { }
pub fn main() | {
let a = Bar { x: 1 };
let b = &a as &Foo;
} | identifier_body |
|
trait-cast-generic.rs | // Copyright 2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
// Testing casting of a generic Struct to a Trait with a generic method.
// This is test for issue 10955.
#[allow(unused_variable)];
trait Foo {
fn f<A>(a: A) -> A {
a
}
}
struct | <T> {
x: T,
}
impl<T> Foo for Bar<T> { }
pub fn main() {
let a = Bar { x: 1 };
let b = &a as &Foo;
}
| Bar | identifier_name |
trait-cast-generic.rs | // Copyright 2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
// Testing casting of a generic Struct to a Trait with a generic method.
// This is test for issue 10955.
#[allow(unused_variable)];
trait Foo {
fn f<A>(a: A) -> A {
a
}
}
struct Bar<T> {
x: T,
}
impl<T> Foo for Bar<T> { }
pub fn main() { | let b = &a as &Foo;
} | let a = Bar { x: 1 }; | random_line_split |
config.rs | use std::io::prelude::*;
use std::fs::File;
use std::str::FromStr;
use docopt::Docopt;
use toml;
use gobjects;
use version::Version;
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum WorkMode {
Normal, //generate widgets etc.
Sys, //generate -sys with ffi
}
impl Default for WorkMode {
fn default() -> WorkMode { WorkMode::Normal }
}
impl FromStr for WorkMode {
type Err = String;
fn from_str(s: &str) -> Result<Self, Self::Err> {
match s {
"normal" => Ok(WorkMode::Normal),
"sys" => Ok(WorkMode::Sys),
_ => Err("Wrong work mode".into())
}
}
}
static USAGE: &'static str = "
Usage: gir [options] [<library> <version>]
gir --help
Options:
-h, --help Show this message.
-c CONFIG Config file path (default: Gir.toml)
-d GIRSPATH Directory for girs
-m MODE Work mode: normal or sys
-o PATH Target path
-b, --make_backup Make backup before generating
";
#[derive(Debug)]
pub struct Config {
pub work_mode: WorkMode,
pub girs_dir: String,
pub library_name: String,
pub library_version: String,
pub target_path: String,
pub external_libraries: Vec<String>,
pub objects: gobjects::GObjects,
pub min_cfg_version: Version,
pub make_backup: bool,
}
impl Config {
pub fn new() -> Config {
let args = Docopt::new(USAGE)
.and_then(|dopt| dopt.parse())
.unwrap_or_else(|e| e.exit());
let config_file = match args.get_str("-c") {
"" => "Gir.toml",
a => a,
};
//TODO: add check file existence when stable std::fs::PathExt
let toml = read_toml(config_file);
let work_mode_str = match args.get_str("-m") {
"" => toml.lookup("options.work_mode")
.expect("No options.work_mode in config")
.as_str().unwrap(),
a => a,
};
let work_mode = WorkMode::from_str(work_mode_str)
.unwrap_or_else(|e| panic!(e));
let girs_dir = match args.get_str("-d") {
"" => toml.lookup("options.girs_dir")
.expect("No options.girs_dir in config")
.as_str().unwrap(),
a => a
};
let (library_name, library_version) =
match (args.get_str("<library>"), args.get_str("<version>")) {
("", "") => (
toml.lookup("options.library")
.expect("No options.library in config")
.as_str().unwrap(),
toml.lookup("options.version")
.expect("No options.version in config")
.as_str().unwrap()
),
("", _) | (_, "") => panic!("Library and version can not be specified separately"),
(a, b) => (a, b)
};
let target_path = match args.get_str("-o") {
"" => toml.lookup("options.target_path")
.expect("No target path specified")
.as_str().unwrap(),
a => a
}; |
let external_libraries = toml.lookup("options.external_libraries")
.map(|a| a.as_slice().unwrap().iter()
.filter_map(|v|
if let &toml::Value::String(ref s) = v { Some(s.clone()) } else { None } )
.collect())
.unwrap_or_else(|| Vec::new());
let min_cfg_version = toml.lookup("options.min_cfg_version")
.map_or_else(|| Ok(Default::default()), |t| t.as_str().unwrap().parse())
.unwrap_or_else(|e| panic!(e));
let make_backup = args.get_bool("-b");
Config {
work_mode: work_mode,
girs_dir: girs_dir.into(),
library_name: library_name.into(),
library_version: library_version.into(),
target_path: target_path.into(),
external_libraries: external_libraries,
objects: objects,
min_cfg_version: min_cfg_version,
make_backup: make_backup,
}
}
pub fn library_full_name(&self) -> String {
format!("{}-{}", self.library_name, self.library_version)
}
}
fn read_toml(filename: &str) -> toml::Value {
let mut input = String::new();
File::open(filename).and_then(|mut f| {
f.read_to_string(&mut input)
}).unwrap();
let mut parser = toml::Parser::new(&input);
match parser.parse() {
Some(toml) => toml::Value::Table(toml),
None => {
for err in &parser.errors {
let (loline, locol) = parser.to_linecol(err.lo);
let (hiline, hicol) = parser.to_linecol(err.hi);
println!("{}:{}:{}-{}:{} error: {}",
filename, loline, locol, hiline, hicol, err.desc);
}
panic!("Errors in config")
}
}
} |
let mut objects = toml.lookup("object").map(|t| gobjects::parse_toml(t))
.unwrap_or_else(|| Default::default());
gobjects::parse_status_shorthands(&mut objects, &toml); | random_line_split |
config.rs | use std::io::prelude::*;
use std::fs::File;
use std::str::FromStr;
use docopt::Docopt;
use toml;
use gobjects;
use version::Version;
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum WorkMode {
Normal, //generate widgets etc.
Sys, //generate -sys with ffi
}
impl Default for WorkMode {
fn default() -> WorkMode { WorkMode::Normal }
}
impl FromStr for WorkMode {
type Err = String;
fn | (s: &str) -> Result<Self, Self::Err> {
match s {
"normal" => Ok(WorkMode::Normal),
"sys" => Ok(WorkMode::Sys),
_ => Err("Wrong work mode".into())
}
}
}
static USAGE: &'static str = "
Usage: gir [options] [<library> <version>]
gir --help
Options:
-h, --help Show this message.
-c CONFIG Config file path (default: Gir.toml)
-d GIRSPATH Directory for girs
-m MODE Work mode: normal or sys
-o PATH Target path
-b, --make_backup Make backup before generating
";
#[derive(Debug)]
pub struct Config {
pub work_mode: WorkMode,
pub girs_dir: String,
pub library_name: String,
pub library_version: String,
pub target_path: String,
pub external_libraries: Vec<String>,
pub objects: gobjects::GObjects,
pub min_cfg_version: Version,
pub make_backup: bool,
}
impl Config {
pub fn new() -> Config {
let args = Docopt::new(USAGE)
.and_then(|dopt| dopt.parse())
.unwrap_or_else(|e| e.exit());
let config_file = match args.get_str("-c") {
"" => "Gir.toml",
a => a,
};
//TODO: add check file existence when stable std::fs::PathExt
let toml = read_toml(config_file);
let work_mode_str = match args.get_str("-m") {
"" => toml.lookup("options.work_mode")
.expect("No options.work_mode in config")
.as_str().unwrap(),
a => a,
};
let work_mode = WorkMode::from_str(work_mode_str)
.unwrap_or_else(|e| panic!(e));
let girs_dir = match args.get_str("-d") {
"" => toml.lookup("options.girs_dir")
.expect("No options.girs_dir in config")
.as_str().unwrap(),
a => a
};
let (library_name, library_version) =
match (args.get_str("<library>"), args.get_str("<version>")) {
("", "") => (
toml.lookup("options.library")
.expect("No options.library in config")
.as_str().unwrap(),
toml.lookup("options.version")
.expect("No options.version in config")
.as_str().unwrap()
),
("", _) | (_, "") => panic!("Library and version can not be specified separately"),
(a, b) => (a, b)
};
let target_path = match args.get_str("-o") {
"" => toml.lookup("options.target_path")
.expect("No target path specified")
.as_str().unwrap(),
a => a
};
let mut objects = toml.lookup("object").map(|t| gobjects::parse_toml(t))
.unwrap_or_else(|| Default::default());
gobjects::parse_status_shorthands(&mut objects, &toml);
let external_libraries = toml.lookup("options.external_libraries")
.map(|a| a.as_slice().unwrap().iter()
.filter_map(|v|
if let &toml::Value::String(ref s) = v { Some(s.clone()) } else { None } )
.collect())
.unwrap_or_else(|| Vec::new());
let min_cfg_version = toml.lookup("options.min_cfg_version")
.map_or_else(|| Ok(Default::default()), |t| t.as_str().unwrap().parse())
.unwrap_or_else(|e| panic!(e));
let make_backup = args.get_bool("-b");
Config {
work_mode: work_mode,
girs_dir: girs_dir.into(),
library_name: library_name.into(),
library_version: library_version.into(),
target_path: target_path.into(),
external_libraries: external_libraries,
objects: objects,
min_cfg_version: min_cfg_version,
make_backup: make_backup,
}
}
pub fn library_full_name(&self) -> String {
format!("{}-{}", self.library_name, self.library_version)
}
}
fn read_toml(filename: &str) -> toml::Value {
let mut input = String::new();
File::open(filename).and_then(|mut f| {
f.read_to_string(&mut input)
}).unwrap();
let mut parser = toml::Parser::new(&input);
match parser.parse() {
Some(toml) => toml::Value::Table(toml),
None => {
for err in &parser.errors {
let (loline, locol) = parser.to_linecol(err.lo);
let (hiline, hicol) = parser.to_linecol(err.hi);
println!("{}:{}:{}-{}:{} error: {}",
filename, loline, locol, hiline, hicol, err.desc);
}
panic!("Errors in config")
}
}
}
| from_str | identifier_name |
config.rs | use std::io::prelude::*;
use std::fs::File;
use std::str::FromStr;
use docopt::Docopt;
use toml;
use gobjects;
use version::Version;
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum WorkMode {
Normal, //generate widgets etc.
Sys, //generate -sys with ffi
}
impl Default for WorkMode {
fn default() -> WorkMode { WorkMode::Normal }
}
impl FromStr for WorkMode {
type Err = String;
fn from_str(s: &str) -> Result<Self, Self::Err> |
}
static USAGE: &'static str = "
Usage: gir [options] [<library> <version>]
gir --help
Options:
-h, --help Show this message.
-c CONFIG Config file path (default: Gir.toml)
-d GIRSPATH Directory for girs
-m MODE Work mode: normal or sys
-o PATH Target path
-b, --make_backup Make backup before generating
";
#[derive(Debug)]
pub struct Config {
pub work_mode: WorkMode,
pub girs_dir: String,
pub library_name: String,
pub library_version: String,
pub target_path: String,
pub external_libraries: Vec<String>,
pub objects: gobjects::GObjects,
pub min_cfg_version: Version,
pub make_backup: bool,
}
impl Config {
pub fn new() -> Config {
let args = Docopt::new(USAGE)
.and_then(|dopt| dopt.parse())
.unwrap_or_else(|e| e.exit());
let config_file = match args.get_str("-c") {
"" => "Gir.toml",
a => a,
};
//TODO: add check file existence when stable std::fs::PathExt
let toml = read_toml(config_file);
let work_mode_str = match args.get_str("-m") {
"" => toml.lookup("options.work_mode")
.expect("No options.work_mode in config")
.as_str().unwrap(),
a => a,
};
let work_mode = WorkMode::from_str(work_mode_str)
.unwrap_or_else(|e| panic!(e));
let girs_dir = match args.get_str("-d") {
"" => toml.lookup("options.girs_dir")
.expect("No options.girs_dir in config")
.as_str().unwrap(),
a => a
};
let (library_name, library_version) =
match (args.get_str("<library>"), args.get_str("<version>")) {
("", "") => (
toml.lookup("options.library")
.expect("No options.library in config")
.as_str().unwrap(),
toml.lookup("options.version")
.expect("No options.version in config")
.as_str().unwrap()
),
("", _) | (_, "") => panic!("Library and version can not be specified separately"),
(a, b) => (a, b)
};
let target_path = match args.get_str("-o") {
"" => toml.lookup("options.target_path")
.expect("No target path specified")
.as_str().unwrap(),
a => a
};
let mut objects = toml.lookup("object").map(|t| gobjects::parse_toml(t))
.unwrap_or_else(|| Default::default());
gobjects::parse_status_shorthands(&mut objects, &toml);
let external_libraries = toml.lookup("options.external_libraries")
.map(|a| a.as_slice().unwrap().iter()
.filter_map(|v|
if let &toml::Value::String(ref s) = v { Some(s.clone()) } else { None } )
.collect())
.unwrap_or_else(|| Vec::new());
let min_cfg_version = toml.lookup("options.min_cfg_version")
.map_or_else(|| Ok(Default::default()), |t| t.as_str().unwrap().parse())
.unwrap_or_else(|e| panic!(e));
let make_backup = args.get_bool("-b");
Config {
work_mode: work_mode,
girs_dir: girs_dir.into(),
library_name: library_name.into(),
library_version: library_version.into(),
target_path: target_path.into(),
external_libraries: external_libraries,
objects: objects,
min_cfg_version: min_cfg_version,
make_backup: make_backup,
}
}
pub fn library_full_name(&self) -> String {
format!("{}-{}", self.library_name, self.library_version)
}
}
fn read_toml(filename: &str) -> toml::Value {
let mut input = String::new();
File::open(filename).and_then(|mut f| {
f.read_to_string(&mut input)
}).unwrap();
let mut parser = toml::Parser::new(&input);
match parser.parse() {
Some(toml) => toml::Value::Table(toml),
None => {
for err in &parser.errors {
let (loline, locol) = parser.to_linecol(err.lo);
let (hiline, hicol) = parser.to_linecol(err.hi);
println!("{}:{}:{}-{}:{} error: {}",
filename, loline, locol, hiline, hicol, err.desc);
}
panic!("Errors in config")
}
}
}
| {
match s {
"normal" => Ok(WorkMode::Normal),
"sys" => Ok(WorkMode::Sys),
_ => Err("Wrong work mode".into())
}
} | identifier_body |
dompoint.rs | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
use dom::bindings::codegen::Bindings::DOMPointBinding::{DOMPointInit, DOMPointMethods, Wrap};
use dom::bindings::codegen::Bindings::DOMPointReadOnlyBinding::DOMPointReadOnlyMethods;
use dom::bindings::error::Fallible;
use dom::bindings::reflector::reflect_dom_object;
use dom::bindings::root::DomRoot;
use dom::dompointreadonly::{DOMPointReadOnly, DOMPointWriteMethods};
use dom::globalscope::GlobalScope;
use dom_struct::dom_struct;
// http://dev.w3.org/fxtf/geometry/Overview.html#dompoint
#[dom_struct]
pub struct DOMPoint {
point: DOMPointReadOnly,
}
impl DOMPoint {
fn new_inherited(x: f64, y: f64, z: f64, w: f64) -> DOMPoint {
DOMPoint {
point: DOMPointReadOnly::new_inherited(x, y, z, w),
}
}
pub fn new(global: &GlobalScope, x: f64, y: f64, z: f64, w: f64) -> DomRoot<DOMPoint> {
reflect_dom_object(Box::new(DOMPoint::new_inherited(x, y, z, w)), global, Wrap)
}
pub fn Constructor(
global: &GlobalScope,
x: f64,
y: f64,
z: f64,
w: f64,
) -> Fallible<DomRoot<DOMPoint>> {
Ok(DOMPoint::new(global, x, y, z, w))
}
pub fn new_from_init(global: &GlobalScope, p: &DOMPointInit) -> DomRoot<DOMPoint> |
}
impl DOMPointMethods for DOMPoint {
// https://dev.w3.org/fxtf/geometry/Overview.html#dom-dompointreadonly-x
fn X(&self) -> f64 {
self.point.X()
}
// https://dev.w3.org/fxtf/geometry/Overview.html#dom-dompointreadonly-x
fn SetX(&self, value: f64) {
self.point.SetX(value);
}
// https://dev.w3.org/fxtf/geometry/Overview.html#dom-dompointreadonly-y
fn Y(&self) -> f64 {
self.point.Y()
}
// https://dev.w3.org/fxtf/geometry/Overview.html#dom-dompointreadonly-y
fn SetY(&self, value: f64) {
self.point.SetY(value);
}
// https://dev.w3.org/fxtf/geometry/Overview.html#dom-dompointreadonly-z
fn Z(&self) -> f64 {
self.point.Z()
}
// https://dev.w3.org/fxtf/geometry/Overview.html#dom-dompointreadonly-z
fn SetZ(&self, value: f64) {
self.point.SetZ(value);
}
// https://dev.w3.org/fxtf/geometry/Overview.html#dom-dompointreadonly-w
fn W(&self) -> f64 {
self.point.W()
}
// https://dev.w3.org/fxtf/geometry/Overview.html#dom-dompointreadonly-w
fn SetW(&self, value: f64) {
self.point.SetW(value);
}
}
| {
DOMPoint::new(global, p.x, p.y, p.z, p.w)
} | identifier_body |
dompoint.rs | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
use dom::bindings::codegen::Bindings::DOMPointBinding::{DOMPointInit, DOMPointMethods, Wrap};
use dom::bindings::codegen::Bindings::DOMPointReadOnlyBinding::DOMPointReadOnlyMethods;
use dom::bindings::error::Fallible;
use dom::bindings::reflector::reflect_dom_object;
use dom::bindings::root::DomRoot;
use dom::dompointreadonly::{DOMPointReadOnly, DOMPointWriteMethods};
use dom::globalscope::GlobalScope;
use dom_struct::dom_struct;
// http://dev.w3.org/fxtf/geometry/Overview.html#dompoint
#[dom_struct]
pub struct DOMPoint {
point: DOMPointReadOnly,
}
impl DOMPoint {
fn new_inherited(x: f64, y: f64, z: f64, w: f64) -> DOMPoint {
DOMPoint {
point: DOMPointReadOnly::new_inherited(x, y, z, w),
}
}
pub fn new(global: &GlobalScope, x: f64, y: f64, z: f64, w: f64) -> DomRoot<DOMPoint> {
reflect_dom_object(Box::new(DOMPoint::new_inherited(x, y, z, w)), global, Wrap)
}
pub fn Constructor(
global: &GlobalScope,
x: f64,
y: f64,
z: f64,
w: f64,
) -> Fallible<DomRoot<DOMPoint>> {
Ok(DOMPoint::new(global, x, y, z, w))
}
pub fn new_from_init(global: &GlobalScope, p: &DOMPointInit) -> DomRoot<DOMPoint> {
DOMPoint::new(global, p.x, p.y, p.z, p.w)
}
}
impl DOMPointMethods for DOMPoint {
// https://dev.w3.org/fxtf/geometry/Overview.html#dom-dompointreadonly-x
fn X(&self) -> f64 {
self.point.X()
}
// https://dev.w3.org/fxtf/geometry/Overview.html#dom-dompointreadonly-x
fn SetX(&self, value: f64) {
self.point.SetX(value);
}
// https://dev.w3.org/fxtf/geometry/Overview.html#dom-dompointreadonly-y
fn Y(&self) -> f64 {
self.point.Y()
}
// https://dev.w3.org/fxtf/geometry/Overview.html#dom-dompointreadonly-y
fn SetY(&self, value: f64) {
self.point.SetY(value);
}
// https://dev.w3.org/fxtf/geometry/Overview.html#dom-dompointreadonly-z
fn Z(&self) -> f64 {
self.point.Z()
}
// https://dev.w3.org/fxtf/geometry/Overview.html#dom-dompointreadonly-z
fn SetZ(&self, value: f64) {
self.point.SetZ(value);
}
// https://dev.w3.org/fxtf/geometry/Overview.html#dom-dompointreadonly-w
fn W(&self) -> f64 { | }
// https://dev.w3.org/fxtf/geometry/Overview.html#dom-dompointreadonly-w
fn SetW(&self, value: f64) {
self.point.SetW(value);
}
} | self.point.W() | random_line_split |
dompoint.rs | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
use dom::bindings::codegen::Bindings::DOMPointBinding::{DOMPointInit, DOMPointMethods, Wrap};
use dom::bindings::codegen::Bindings::DOMPointReadOnlyBinding::DOMPointReadOnlyMethods;
use dom::bindings::error::Fallible;
use dom::bindings::reflector::reflect_dom_object;
use dom::bindings::root::DomRoot;
use dom::dompointreadonly::{DOMPointReadOnly, DOMPointWriteMethods};
use dom::globalscope::GlobalScope;
use dom_struct::dom_struct;
// http://dev.w3.org/fxtf/geometry/Overview.html#dompoint
#[dom_struct]
pub struct DOMPoint {
point: DOMPointReadOnly,
}
impl DOMPoint {
fn new_inherited(x: f64, y: f64, z: f64, w: f64) -> DOMPoint {
DOMPoint {
point: DOMPointReadOnly::new_inherited(x, y, z, w),
}
}
pub fn new(global: &GlobalScope, x: f64, y: f64, z: f64, w: f64) -> DomRoot<DOMPoint> {
reflect_dom_object(Box::new(DOMPoint::new_inherited(x, y, z, w)), global, Wrap)
}
pub fn Constructor(
global: &GlobalScope,
x: f64,
y: f64,
z: f64,
w: f64,
) -> Fallible<DomRoot<DOMPoint>> {
Ok(DOMPoint::new(global, x, y, z, w))
}
pub fn new_from_init(global: &GlobalScope, p: &DOMPointInit) -> DomRoot<DOMPoint> {
DOMPoint::new(global, p.x, p.y, p.z, p.w)
}
}
impl DOMPointMethods for DOMPoint {
// https://dev.w3.org/fxtf/geometry/Overview.html#dom-dompointreadonly-x
fn X(&self) -> f64 {
self.point.X()
}
// https://dev.w3.org/fxtf/geometry/Overview.html#dom-dompointreadonly-x
fn SetX(&self, value: f64) {
self.point.SetX(value);
}
// https://dev.w3.org/fxtf/geometry/Overview.html#dom-dompointreadonly-y
fn Y(&self) -> f64 {
self.point.Y()
}
// https://dev.w3.org/fxtf/geometry/Overview.html#dom-dompointreadonly-y
fn SetY(&self, value: f64) {
self.point.SetY(value);
}
// https://dev.w3.org/fxtf/geometry/Overview.html#dom-dompointreadonly-z
fn | (&self) -> f64 {
self.point.Z()
}
// https://dev.w3.org/fxtf/geometry/Overview.html#dom-dompointreadonly-z
fn SetZ(&self, value: f64) {
self.point.SetZ(value);
}
// https://dev.w3.org/fxtf/geometry/Overview.html#dom-dompointreadonly-w
fn W(&self) -> f64 {
self.point.W()
}
// https://dev.w3.org/fxtf/geometry/Overview.html#dom-dompointreadonly-w
fn SetW(&self, value: f64) {
self.point.SetW(value);
}
}
| Z | identifier_name |
assoc-types.rs | // Copyright 2015 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
#![crate_type="lib"]
// @has assoc_types/trait.Index.html
pub trait Index<I:?Sized> {
// @has - '//*[@id="associatedtype.Output"]//code' 'type Output:?Sized'
type Output:?Sized;
// @has - '//*[@id="tymethod.index"]//code' \
// "fn index<'a>(&'a self, index: I) -> &'a Self::Output"
fn index<'a>(&'a self, index: I) -> &'a Self::Output;
}
// @has assoc_types/fn.use_output.html
// @has - '//*[@class="rust fn"]' '-> &T::Output'
pub fn use_output<T: Index<usize>>(obj: &T, index: usize) -> &T::Output {
obj.index(index)
}
pub trait Feed {
type Input;
}
// @has assoc_types/fn.use_input.html
// @has - '//*[@class="rust fn"]' 'T::Input'
pub fn use_input<T: Feed>(_feed: &T, _element: T::Input) |
// @has assoc_types/fn.cmp_input.html
// @has - '//*[@class="rust fn"]' 'where T::Input: PartialEq<U::Input>'
pub fn cmp_input<T: Feed, U: Feed>(a: &T::Input, b: &U::Input) -> bool
where T::Input: PartialEq<U::Input>
{
a == b
}
| { } | identifier_body |
assoc-types.rs | // Copyright 2015 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
#![crate_type="lib"]
// @has assoc_types/trait.Index.html
pub trait Index<I:?Sized> {
// @has - '//*[@id="associatedtype.Output"]//code' 'type Output:?Sized'
type Output:?Sized;
// @has - '//*[@id="tymethod.index"]//code' \
// "fn index<'a>(&'a self, index: I) -> &'a Self::Output"
fn index<'a>(&'a self, index: I) -> &'a Self::Output;
}
// @has assoc_types/fn.use_output.html
// @has - '//*[@class="rust fn"]' '-> &T::Output'
pub fn | <T: Index<usize>>(obj: &T, index: usize) -> &T::Output {
obj.index(index)
}
pub trait Feed {
type Input;
}
// @has assoc_types/fn.use_input.html
// @has - '//*[@class="rust fn"]' 'T::Input'
pub fn use_input<T: Feed>(_feed: &T, _element: T::Input) { }
// @has assoc_types/fn.cmp_input.html
// @has - '//*[@class="rust fn"]' 'where T::Input: PartialEq<U::Input>'
pub fn cmp_input<T: Feed, U: Feed>(a: &T::Input, b: &U::Input) -> bool
where T::Input: PartialEq<U::Input>
{
a == b
}
| use_output | identifier_name |
assoc-types.rs | // Copyright 2015 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or | // option. This file may not be copied, modified, or distributed
// except according to those terms.
#![crate_type="lib"]
// @has assoc_types/trait.Index.html
pub trait Index<I:?Sized> {
// @has - '//*[@id="associatedtype.Output"]//code' 'type Output:?Sized'
type Output:?Sized;
// @has - '//*[@id="tymethod.index"]//code' \
// "fn index<'a>(&'a self, index: I) -> &'a Self::Output"
fn index<'a>(&'a self, index: I) -> &'a Self::Output;
}
// @has assoc_types/fn.use_output.html
// @has - '//*[@class="rust fn"]' '-> &T::Output'
pub fn use_output<T: Index<usize>>(obj: &T, index: usize) -> &T::Output {
obj.index(index)
}
pub trait Feed {
type Input;
}
// @has assoc_types/fn.use_input.html
// @has - '//*[@class="rust fn"]' 'T::Input'
pub fn use_input<T: Feed>(_feed: &T, _element: T::Input) { }
// @has assoc_types/fn.cmp_input.html
// @has - '//*[@class="rust fn"]' 'where T::Input: PartialEq<U::Input>'
pub fn cmp_input<T: Feed, U: Feed>(a: &T::Input, b: &U::Input) -> bool
where T::Input: PartialEq<U::Input>
{
a == b
} | // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your | random_line_split |
underscore_const_names.rs | // Copyright 2012-2018 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
// compile-pass
#![feature(const_let)]
#![feature(underscore_const_names)]
trait Trt {}
struct Str {}
impl Trt for Str {}
macro_rules! check_impl {
($struct:ident,$trait:ident) => {
const _ : () = {
use std::marker::PhantomData;
struct ImplementsTrait<T: $trait>(PhantomData<T>);
let _ = ImplementsTrait::<$struct>(PhantomData);
()
};
}
}
#[deny(unused)]
const _ : () = ();
const _ : i32 = 42;
const _ : Str = Str{};
check_impl!(Str, Trt);
check_impl!(Str, Trt);
fn main() | {
check_impl!(Str, Trt);
check_impl!(Str, Trt);
} | identifier_body |
|
underscore_const_names.rs | // Copyright 2012-2018 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
// compile-pass
#![feature(const_let)]
#![feature(underscore_const_names)]
trait Trt {}
struct Str {}
impl Trt for Str {}
macro_rules! check_impl {
($struct:ident,$trait:ident) => {
const _ : () = {
use std::marker::PhantomData;
struct ImplementsTrait<T: $trait>(PhantomData<T>);
let _ = ImplementsTrait::<$struct>(PhantomData);
()
};
}
}
#[deny(unused)]
const _ : () = ();
const _ : i32 = 42;
const _ : Str = Str{};
check_impl!(Str, Trt);
check_impl!(Str, Trt);
fn | () {
check_impl!(Str, Trt);
check_impl!(Str, Trt);
}
| main | identifier_name |
underscore_const_names.rs | // Copyright 2012-2018 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
|
trait Trt {}
struct Str {}
impl Trt for Str {}
macro_rules! check_impl {
($struct:ident,$trait:ident) => {
const _ : () = {
use std::marker::PhantomData;
struct ImplementsTrait<T: $trait>(PhantomData<T>);
let _ = ImplementsTrait::<$struct>(PhantomData);
()
};
}
}
#[deny(unused)]
const _ : () = ();
const _ : i32 = 42;
const _ : Str = Str{};
check_impl!(Str, Trt);
check_impl!(Str, Trt);
fn main() {
check_impl!(Str, Trt);
check_impl!(Str, Trt);
} | // compile-pass
#![feature(const_let)]
#![feature(underscore_const_names)] | random_line_split |
mod.rs | use libc::{self, c_int};
#[macro_use]
pub mod dlsym;
#[cfg(any(target_os = "linux", target_os = "android"))]
mod epoll;
#[cfg(any(target_os = "linux", target_os = "android"))]
pub use self::epoll::{Events, Selector};
#[cfg(any(target_os = "bitrig", target_os = "dragonfly",
target_os = "freebsd", target_os = "ios", target_os = "macos",
target_os = "netbsd", target_os = "openbsd"))]
mod kqueue;
#[cfg(any(target_os = "bitrig", target_os = "dragonfly",
target_os = "freebsd", target_os = "ios", target_os = "macos",
target_os = "netbsd", target_os = "openbsd"))]
pub use self::kqueue::{Events, Selector};
mod awakener;
mod eventedfd;
mod io;
mod ready;
mod tcp;
mod udp;
#[cfg(feature = "with-deprecated")]
mod uds;
pub use self::awakener::Awakener;
pub use self::eventedfd::EventedFd;
pub use self::io::{Io, set_nonblock};
pub use self::ready::UnixReady;
pub use self::tcp::{TcpStream, TcpListener};
pub use self::udp::UdpSocket;
#[cfg(feature = "with-deprecated")]
pub use self::uds::UnixSocket;
pub use iovec::IoVec;
use std::os::unix::io::FromRawFd;
pub fn pipe() -> ::io::Result<(Io, Io)> {
// Use pipe2 for atomically setting O_CLOEXEC if we can, but otherwise
// just fall back to using `pipe`.
dlsym!(fn pipe2(*mut c_int, c_int) -> c_int);
let mut pipes = [0; 2];
let flags = libc::O_NONBLOCK | libc::O_CLOEXEC;
unsafe {
match pipe2.get() {
Some(pipe2_fn) => {
cvt(pipe2_fn(pipes.as_mut_ptr(), flags))?;
}
None => {
cvt(libc::pipe(pipes.as_mut_ptr()))?;
libc::fcntl(pipes[0], libc::F_SETFL, flags);
libc::fcntl(pipes[1], libc::F_SETFL, flags);
}
}
}
unsafe {
Ok((Io::from_raw_fd(pipes[0]), Io::from_raw_fd(pipes[1])))
}
} | }
impl IsMinusOne for i32 {
fn is_minus_one(&self) -> bool { *self == -1 }
}
impl IsMinusOne for isize {
fn is_minus_one(&self) -> bool { *self == -1 }
}
fn cvt<T: IsMinusOne>(t: T) -> ::io::Result<T> {
use std::io;
if t.is_minus_one() {
Err(io::Error::last_os_error())
} else {
Ok(t)
}
} |
trait IsMinusOne {
fn is_minus_one(&self) -> bool; | random_line_split |
mod.rs | use libc::{self, c_int};
#[macro_use]
pub mod dlsym;
#[cfg(any(target_os = "linux", target_os = "android"))]
mod epoll;
#[cfg(any(target_os = "linux", target_os = "android"))]
pub use self::epoll::{Events, Selector};
#[cfg(any(target_os = "bitrig", target_os = "dragonfly",
target_os = "freebsd", target_os = "ios", target_os = "macos",
target_os = "netbsd", target_os = "openbsd"))]
mod kqueue;
#[cfg(any(target_os = "bitrig", target_os = "dragonfly",
target_os = "freebsd", target_os = "ios", target_os = "macos",
target_os = "netbsd", target_os = "openbsd"))]
pub use self::kqueue::{Events, Selector};
mod awakener;
mod eventedfd;
mod io;
mod ready;
mod tcp;
mod udp;
#[cfg(feature = "with-deprecated")]
mod uds;
pub use self::awakener::Awakener;
pub use self::eventedfd::EventedFd;
pub use self::io::{Io, set_nonblock};
pub use self::ready::UnixReady;
pub use self::tcp::{TcpStream, TcpListener};
pub use self::udp::UdpSocket;
#[cfg(feature = "with-deprecated")]
pub use self::uds::UnixSocket;
pub use iovec::IoVec;
use std::os::unix::io::FromRawFd;
pub fn pipe() -> ::io::Result<(Io, Io)> {
// Use pipe2 for atomically setting O_CLOEXEC if we can, but otherwise
// just fall back to using `pipe`.
dlsym!(fn pipe2(*mut c_int, c_int) -> c_int);
let mut pipes = [0; 2];
let flags = libc::O_NONBLOCK | libc::O_CLOEXEC;
unsafe {
match pipe2.get() {
Some(pipe2_fn) => {
cvt(pipe2_fn(pipes.as_mut_ptr(), flags))?;
}
None => {
cvt(libc::pipe(pipes.as_mut_ptr()))?;
libc::fcntl(pipes[0], libc::F_SETFL, flags);
libc::fcntl(pipes[1], libc::F_SETFL, flags);
}
}
}
unsafe {
Ok((Io::from_raw_fd(pipes[0]), Io::from_raw_fd(pipes[1])))
}
}
trait IsMinusOne {
fn is_minus_one(&self) -> bool;
}
impl IsMinusOne for i32 {
fn is_minus_one(&self) -> bool { *self == -1 }
}
impl IsMinusOne for isize {
fn is_minus_one(&self) -> bool { *self == -1 }
}
fn cvt<T: IsMinusOne>(t: T) -> ::io::Result<T> {
use std::io;
if t.is_minus_one() {
Err(io::Error::last_os_error())
} else |
}
| {
Ok(t)
} | conditional_block |
mod.rs | use libc::{self, c_int};
#[macro_use]
pub mod dlsym;
#[cfg(any(target_os = "linux", target_os = "android"))]
mod epoll;
#[cfg(any(target_os = "linux", target_os = "android"))]
pub use self::epoll::{Events, Selector};
#[cfg(any(target_os = "bitrig", target_os = "dragonfly",
target_os = "freebsd", target_os = "ios", target_os = "macos",
target_os = "netbsd", target_os = "openbsd"))]
mod kqueue;
#[cfg(any(target_os = "bitrig", target_os = "dragonfly",
target_os = "freebsd", target_os = "ios", target_os = "macos",
target_os = "netbsd", target_os = "openbsd"))]
pub use self::kqueue::{Events, Selector};
mod awakener;
mod eventedfd;
mod io;
mod ready;
mod tcp;
mod udp;
#[cfg(feature = "with-deprecated")]
mod uds;
pub use self::awakener::Awakener;
pub use self::eventedfd::EventedFd;
pub use self::io::{Io, set_nonblock};
pub use self::ready::UnixReady;
pub use self::tcp::{TcpStream, TcpListener};
pub use self::udp::UdpSocket;
#[cfg(feature = "with-deprecated")]
pub use self::uds::UnixSocket;
pub use iovec::IoVec;
use std::os::unix::io::FromRawFd;
pub fn pipe() -> ::io::Result<(Io, Io)> {
// Use pipe2 for atomically setting O_CLOEXEC if we can, but otherwise
// just fall back to using `pipe`.
dlsym!(fn pipe2(*mut c_int, c_int) -> c_int);
let mut pipes = [0; 2];
let flags = libc::O_NONBLOCK | libc::O_CLOEXEC;
unsafe {
match pipe2.get() {
Some(pipe2_fn) => {
cvt(pipe2_fn(pipes.as_mut_ptr(), flags))?;
}
None => {
cvt(libc::pipe(pipes.as_mut_ptr()))?;
libc::fcntl(pipes[0], libc::F_SETFL, flags);
libc::fcntl(pipes[1], libc::F_SETFL, flags);
}
}
}
unsafe {
Ok((Io::from_raw_fd(pipes[0]), Io::from_raw_fd(pipes[1])))
}
}
trait IsMinusOne {
fn is_minus_one(&self) -> bool;
}
impl IsMinusOne for i32 {
fn is_minus_one(&self) -> bool { *self == -1 }
}
impl IsMinusOne for isize {
fn | (&self) -> bool { *self == -1 }
}
fn cvt<T: IsMinusOne>(t: T) -> ::io::Result<T> {
use std::io;
if t.is_minus_one() {
Err(io::Error::last_os_error())
} else {
Ok(t)
}
}
| is_minus_one | identifier_name |
mod.rs | use libc::{self, c_int};
#[macro_use]
pub mod dlsym;
#[cfg(any(target_os = "linux", target_os = "android"))]
mod epoll;
#[cfg(any(target_os = "linux", target_os = "android"))]
pub use self::epoll::{Events, Selector};
#[cfg(any(target_os = "bitrig", target_os = "dragonfly",
target_os = "freebsd", target_os = "ios", target_os = "macos",
target_os = "netbsd", target_os = "openbsd"))]
mod kqueue;
#[cfg(any(target_os = "bitrig", target_os = "dragonfly",
target_os = "freebsd", target_os = "ios", target_os = "macos",
target_os = "netbsd", target_os = "openbsd"))]
pub use self::kqueue::{Events, Selector};
mod awakener;
mod eventedfd;
mod io;
mod ready;
mod tcp;
mod udp;
#[cfg(feature = "with-deprecated")]
mod uds;
pub use self::awakener::Awakener;
pub use self::eventedfd::EventedFd;
pub use self::io::{Io, set_nonblock};
pub use self::ready::UnixReady;
pub use self::tcp::{TcpStream, TcpListener};
pub use self::udp::UdpSocket;
#[cfg(feature = "with-deprecated")]
pub use self::uds::UnixSocket;
pub use iovec::IoVec;
use std::os::unix::io::FromRawFd;
pub fn pipe() -> ::io::Result<(Io, Io)> | unsafe {
Ok((Io::from_raw_fd(pipes[0]), Io::from_raw_fd(pipes[1])))
}
}
trait IsMinusOne {
fn is_minus_one(&self) -> bool;
}
impl IsMinusOne for i32 {
fn is_minus_one(&self) -> bool { *self == -1 }
}
impl IsMinusOne for isize {
fn is_minus_one(&self) -> bool { *self == -1 }
}
fn cvt<T: IsMinusOne>(t: T) -> ::io::Result<T> {
use std::io;
if t.is_minus_one() {
Err(io::Error::last_os_error())
} else {
Ok(t)
}
}
| {
// Use pipe2 for atomically setting O_CLOEXEC if we can, but otherwise
// just fall back to using `pipe`.
dlsym!(fn pipe2(*mut c_int, c_int) -> c_int);
let mut pipes = [0; 2];
let flags = libc::O_NONBLOCK | libc::O_CLOEXEC;
unsafe {
match pipe2.get() {
Some(pipe2_fn) => {
cvt(pipe2_fn(pipes.as_mut_ptr(), flags))?;
}
None => {
cvt(libc::pipe(pipes.as_mut_ptr()))?;
libc::fcntl(pipes[0], libc::F_SETFL, flags);
libc::fcntl(pipes[1], libc::F_SETFL, flags);
}
}
}
| identifier_body |
mod.rs | mod handlers;
use crate::server::Server;
use log::{debug, error};
use protocol::frame::Framed;
use protocol::Decode;
use runtime::net::TcpStream;
use std::sync::Arc;
const SALT_LEN: usize = 32;
const AES_KEY_LEN: usize = 32;
const AES_IV_LEN: usize = 16;
#[derive(PartialEq, Eq, Debug)]
enum State {
Init,
Logged {
aes_key: [u8; AES_KEY_LEN],
ticket: String,
},
}
pub struct Session {
stream: Framed<TcpStream>,
state: State,
server: Arc<Server>,
}
impl Session {
pub fn new(stream: TcpStream, server: Arc<Server>) -> Self {
Self {
stream: Framed::new(stream),
state: State::Init,
server,
}
}
pub async fn run(mut self) -> std::io::Result<()> | let mut rng = rand::thread_rng();
std::iter::repeat(())
.map(|()| rng.sample(rand::distributions::Alphanumeric))
.take(SALT_LEN)
.collect()
};
self.stream.write(HelloConnectMessage {
salt: &salt,
key: unsafe {
std::slice::from_raw_parts(
self.server.public_key.as_ptr() as *const i8,
self.server.public_key.len(),
)
},
})?;
self.stream.flush().await?;
while let Some(frame) = self.stream.next().await {
let frame = frame?;
debug!("received message with id {}", frame.id());
match frame.id() {
<IdentificationMessage<'_> as Decode<'_>>::ID => {
match IdentificationMessage::decode(&mut frame.payload()) {
Ok(msg) => self.handle_identification(msg).await?,
Err(err) => error!("decode error: {}", err),
}
}
<ServerSelectionMessage<'_> as Decode<'_>>::ID => {
match ServerSelectionMessage::decode(&mut frame.payload()) {
Ok(msg) => self.handle_server_selection(msg).await?,
Err(err) => error!("decode error: {}", err),
}
}
_ => (),
}
}
Ok(())
}
}
| {
use futures::StreamExt;
use protocol::messages::connection::HelloConnectMessage;
use protocol::messages::connection::IdentificationMessage;
use protocol::messages::connection::ServerSelectionMessage;
use protocol::messages::handshake::ProtocolRequired;
use rand::Rng;
debug!(
"new connection from {:?}",
self.stream.get_ref().peer_addr()
);
self.stream.write(ProtocolRequired {
required_version: 1924,
current_version: 1924,
_phantom: std::marker::PhantomData,
})?;
let salt: String = { | identifier_body |
mod.rs | mod handlers;
use crate::server::Server;
use log::{debug, error};
use protocol::frame::Framed;
use protocol::Decode;
use runtime::net::TcpStream;
use std::sync::Arc;
const SALT_LEN: usize = 32;
const AES_KEY_LEN: usize = 32;
const AES_IV_LEN: usize = 16;
#[derive(PartialEq, Eq, Debug)]
enum | {
Init,
Logged {
aes_key: [u8; AES_KEY_LEN],
ticket: String,
},
}
pub struct Session {
stream: Framed<TcpStream>,
state: State,
server: Arc<Server>,
}
impl Session {
pub fn new(stream: TcpStream, server: Arc<Server>) -> Self {
Self {
stream: Framed::new(stream),
state: State::Init,
server,
}
}
pub async fn run(mut self) -> std::io::Result<()> {
use futures::StreamExt;
use protocol::messages::connection::HelloConnectMessage;
use protocol::messages::connection::IdentificationMessage;
use protocol::messages::connection::ServerSelectionMessage;
use protocol::messages::handshake::ProtocolRequired;
use rand::Rng;
debug!(
"new connection from {:?}",
self.stream.get_ref().peer_addr()
);
self.stream.write(ProtocolRequired {
required_version: 1924,
current_version: 1924,
_phantom: std::marker::PhantomData,
})?;
let salt: String = {
let mut rng = rand::thread_rng();
std::iter::repeat(())
.map(|()| rng.sample(rand::distributions::Alphanumeric))
.take(SALT_LEN)
.collect()
};
self.stream.write(HelloConnectMessage {
salt: &salt,
key: unsafe {
std::slice::from_raw_parts(
self.server.public_key.as_ptr() as *const i8,
self.server.public_key.len(),
)
},
})?;
self.stream.flush().await?;
while let Some(frame) = self.stream.next().await {
let frame = frame?;
debug!("received message with id {}", frame.id());
match frame.id() {
<IdentificationMessage<'_> as Decode<'_>>::ID => {
match IdentificationMessage::decode(&mut frame.payload()) {
Ok(msg) => self.handle_identification(msg).await?,
Err(err) => error!("decode error: {}", err),
}
}
<ServerSelectionMessage<'_> as Decode<'_>>::ID => {
match ServerSelectionMessage::decode(&mut frame.payload()) {
Ok(msg) => self.handle_server_selection(msg).await?,
Err(err) => error!("decode error: {}", err),
}
}
_ => (),
}
}
Ok(())
}
}
| State | identifier_name |
mod.rs | mod handlers;
use crate::server::Server;
use log::{debug, error};
use protocol::frame::Framed;
use protocol::Decode;
use runtime::net::TcpStream;
use std::sync::Arc;
const SALT_LEN: usize = 32;
const AES_KEY_LEN: usize = 32;
const AES_IV_LEN: usize = 16;
#[derive(PartialEq, Eq, Debug)]
enum State {
Init,
Logged {
aes_key: [u8; AES_KEY_LEN],
ticket: String,
},
}
pub struct Session {
stream: Framed<TcpStream>,
state: State,
server: Arc<Server>,
}
impl Session {
pub fn new(stream: TcpStream, server: Arc<Server>) -> Self {
Self {
stream: Framed::new(stream),
state: State::Init,
server,
}
}
pub async fn run(mut self) -> std::io::Result<()> {
use futures::StreamExt;
use protocol::messages::connection::HelloConnectMessage;
use protocol::messages::connection::IdentificationMessage;
use protocol::messages::connection::ServerSelectionMessage;
use protocol::messages::handshake::ProtocolRequired;
use rand::Rng;
debug!(
"new connection from {:?}",
self.stream.get_ref().peer_addr()
);
self.stream.write(ProtocolRequired {
required_version: 1924,
current_version: 1924,
_phantom: std::marker::PhantomData,
})?;
let salt: String = {
let mut rng = rand::thread_rng();
std::iter::repeat(())
.map(|()| rng.sample(rand::distributions::Alphanumeric))
.take(SALT_LEN)
.collect()
};
self.stream.write(HelloConnectMessage {
salt: &salt,
key: unsafe {
std::slice::from_raw_parts(
self.server.public_key.as_ptr() as *const i8,
self.server.public_key.len(),
)
},
})?;
self.stream.flush().await?;
while let Some(frame) = self.stream.next().await {
let frame = frame?;
| match IdentificationMessage::decode(&mut frame.payload()) {
Ok(msg) => self.handle_identification(msg).await?,
Err(err) => error!("decode error: {}", err),
}
}
<ServerSelectionMessage<'_> as Decode<'_>>::ID => {
match ServerSelectionMessage::decode(&mut frame.payload()) {
Ok(msg) => self.handle_server_selection(msg).await?,
Err(err) => error!("decode error: {}", err),
}
}
_ => (),
}
}
Ok(())
}
} | debug!("received message with id {}", frame.id());
match frame.id() {
<IdentificationMessage<'_> as Decode<'_>>::ID => { | random_line_split |
main.rs | extern crate sdl2;
extern crate rustc_serialize;
use sdl2::keycode::KeyCode;
use sdl2::event::Event;
use sdl2::timer::get_ticks;
mod sprite;
mod assets;
mod draw;
mod player;
mod tile;
mod map;
mod physics;
use sprite::Sprite;
use player::Player;
use player::PlayerStatus;
use draw::Draw;
fn | () {
//initialize sdl
let sdl_context = sdl2::init().video().events().build()
.ok().expect("Failed to initialize SDL.");
//create a window
let window = sdl_context.window("Rust-Man", 640, 480)
.position_centered()
.build()
.ok().expect("Failed to create window.");
//create a renderer
let mut renderer = window.renderer().accelerated().build()
.ok().expect("Failed to create accelerated renderer.");
//create a new player
let mut player = Player::new(Sprite::new_from_file("sonic.bmp", &renderer),
PlayerStatus::Stationary);
//start drawing
let mut drawer = renderer.drawer();
drawer.clear();
drawer.present();
//event loop stuff
let mut running = true;
let mut event_pump = sdl_context.event_pump();
let mut prev_time = get_ticks();
let mut delta_t = get_ticks() - prev_time;
while running {
//timer stuff
delta_t = get_ticks() - prev_time;
//limit to 60fps
if delta_t > 16 {
//handle event queue
for event in event_pump.poll_iter() {
match event {
Event::Quit {..} | Event::KeyDown {keycode: KeyCode::Escape,.. } => {
running = false
},
Event::KeyDown {keycode: KeyCode::Left,.. } => {
player.status = PlayerStatus::MovingLeft
},
Event::KeyDown {keycode: KeyCode::Right,.. } => {
player.status = PlayerStatus::MovingRight
},
Event::KeyUp {keycode: KeyCode::Left,.. } => {
player.status = PlayerStatus::Decelerating
},
Event::KeyUp {keycode: KeyCode::Right,.. } => {
player.status = PlayerStatus::Decelerating
},
_ => {}
}
}
//move player
player.update();
//draw
drawer.clear();
player.draw(&mut drawer, &None);
drawer.present();
//more timer stuff
prev_time = get_ticks();
}
}
println!("Goodbye, world!");
}
| main | identifier_name |
main.rs | extern crate sdl2;
extern crate rustc_serialize;
use sdl2::keycode::KeyCode;
use sdl2::event::Event;
use sdl2::timer::get_ticks;
mod sprite;
mod assets;
mod draw;
mod player;
mod tile;
mod map;
mod physics;
use sprite::Sprite;
use player::Player;
use player::PlayerStatus;
use draw::Draw;
fn main() | let mut drawer = renderer.drawer();
drawer.clear();
drawer.present();
//event loop stuff
let mut running = true;
let mut event_pump = sdl_context.event_pump();
let mut prev_time = get_ticks();
let mut delta_t = get_ticks() - prev_time;
while running {
//timer stuff
delta_t = get_ticks() - prev_time;
//limit to 60fps
if delta_t > 16 {
//handle event queue
for event in event_pump.poll_iter() {
match event {
Event::Quit {..} | Event::KeyDown {keycode: KeyCode::Escape,.. } => {
running = false
},
Event::KeyDown {keycode: KeyCode::Left,.. } => {
player.status = PlayerStatus::MovingLeft
},
Event::KeyDown {keycode: KeyCode::Right,.. } => {
player.status = PlayerStatus::MovingRight
},
Event::KeyUp {keycode: KeyCode::Left,.. } => {
player.status = PlayerStatus::Decelerating
},
Event::KeyUp {keycode: KeyCode::Right,.. } => {
player.status = PlayerStatus::Decelerating
},
_ => {}
}
}
//move player
player.update();
//draw
drawer.clear();
player.draw(&mut drawer, &None);
drawer.present();
//more timer stuff
prev_time = get_ticks();
}
}
println!("Goodbye, world!");
}
| {
//initialize sdl
let sdl_context = sdl2::init().video().events().build()
.ok().expect("Failed to initialize SDL.");
//create a window
let window = sdl_context.window("Rust-Man", 640, 480)
.position_centered()
.build()
.ok().expect("Failed to create window.");
//create a renderer
let mut renderer = window.renderer().accelerated().build()
.ok().expect("Failed to create accelerated renderer.");
//create a new player
let mut player = Player::new(Sprite::new_from_file("sonic.bmp", &renderer),
PlayerStatus::Stationary);
//start drawing | identifier_body |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.