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
range.rs
use std::borrow::Borrow; use std::collections::HashSet; use enums::Direction; use structs::Point; use traits::travel::Travel; use traits::range::Base; /// Trait wrapping range implementation pub trait Range: Borrow<Point> { /// Find the points within the provided manhattan distance fn range(&self, range: i32) -> HashSet<Point>; } impl<T> Range for T where T: Borrow<Point> { pub fn range(&self, range: i32) -> HashSet<Point> { let mut set: HashSet<Point> = point.base_range(range); for index in 1..range + 1 { let diff = range - index; set.extend(point.travel(&Direction::Up, index).base_range(diff)); set.extend(point.travel(&Direction::Down, index).base_range(diff)); } set } } #[cfg(test)] mod tests { use super::*; #[test] fn
() { let point: Point = Point(1, 2, 5); let set: HashSet<Point> = point.range(1); assert!(set.contains(&Point(1, 2, 5))); assert!(set.contains(&Point(2, 2, 5))); assert!(set.contains(&Point(1, 3, 5))); assert!(set.contains(&Point(0, 3, 5))); assert!(set.contains(&Point(0, 2, 5))); assert!(set.contains(&Point(1, 1, 5))); assert!(set.contains(&Point(2, 1, 5))); assert!(set.contains(&Point(1, 2, 4))); assert!(set.contains(&Point(1, 2, 6))); assert!(set.len() == 9); } }
range
identifier_name
range.rs
use std::borrow::Borrow; use std::collections::HashSet; use enums::Direction; use structs::Point; use traits::travel::Travel; use traits::range::Base; /// Trait wrapping range implementation pub trait Range: Borrow<Point> { /// Find the points within the provided manhattan distance fn range(&self, range: i32) -> HashSet<Point>; } impl<T> Range for T where T: Borrow<Point> { pub fn range(&self, range: i32) -> HashSet<Point> { let mut set: HashSet<Point> = point.base_range(range); for index in 1..range + 1 { let diff = range - index; set.extend(point.travel(&Direction::Up, index).base_range(diff)); set.extend(point.travel(&Direction::Down, index).base_range(diff)); } set } } #[cfg(test)] mod tests { use super::*; #[test] fn range()
}
{ let point: Point = Point(1, 2, 5); let set: HashSet<Point> = point.range(1); assert!(set.contains(&Point(1, 2, 5))); assert!(set.contains(&Point(2, 2, 5))); assert!(set.contains(&Point(1, 3, 5))); assert!(set.contains(&Point(0, 3, 5))); assert!(set.contains(&Point(0, 2, 5))); assert!(set.contains(&Point(1, 1, 5))); assert!(set.contains(&Point(2, 1, 5))); assert!(set.contains(&Point(1, 2, 4))); assert!(set.contains(&Point(1, 2, 6))); assert!(set.len() == 9); }
identifier_body
range.rs
use std::borrow::Borrow; use std::collections::HashSet; use enums::Direction; use structs::Point; use traits::travel::Travel; use traits::range::Base; /// Trait wrapping range implementation pub trait Range: Borrow<Point> { /// Find the points within the provided manhattan distance fn range(&self, range: i32) -> HashSet<Point>; } impl<T> Range for T where T: Borrow<Point> { pub fn range(&self, range: i32) -> HashSet<Point> { let mut set: HashSet<Point> = point.base_range(range); for index in 1..range + 1 { let diff = range - index;
} set } } #[cfg(test)] mod tests { use super::*; #[test] fn range() { let point: Point = Point(1, 2, 5); let set: HashSet<Point> = point.range(1); assert!(set.contains(&Point(1, 2, 5))); assert!(set.contains(&Point(2, 2, 5))); assert!(set.contains(&Point(1, 3, 5))); assert!(set.contains(&Point(0, 3, 5))); assert!(set.contains(&Point(0, 2, 5))); assert!(set.contains(&Point(1, 1, 5))); assert!(set.contains(&Point(2, 1, 5))); assert!(set.contains(&Point(1, 2, 4))); assert!(set.contains(&Point(1, 2, 6))); assert!(set.len() == 9); } }
set.extend(point.travel(&Direction::Up, index).base_range(diff)); set.extend(point.travel(&Direction::Down, index).base_range(diff));
random_line_split
script.rs
#[cfg(any(target_arch = "x86", target_arch = "arm"))] pub type Word = u32; #[cfg(any(target_arch = "x86_64", target_arch = "aarch64"))] pub type Word = u64; #[cfg_attr(any(target_arch = "x86_64", target_arch = "aarch64"), repr(C, u64))] #[cfg_attr(any(target_arch = "x86", target_arch = "arm"), repr(C, u32))] #[allow(dead_code)] #[derive(Debug)] pub enum
{ /// Close last opened file and open a new file. OpenNext(LoadStatementOpen), /// Open a file, and save the file descriptor. Open(LoadStatementOpen), /// Map a part of the last opened file into memory. MmapFile(LoadStatementMmap), /// Mapping a segment of anonymous private space into memory instead of mapping from a file. MmapAnonymous(LoadStatementMmap), /// Set the stack space to be executable MakeStackExec(LoadStatementStackExec), /// (The purpose of the project is not yet clear) StartTraced(LoadStatementStart), /// Start(LoadStatementStart), } #[repr(C)] #[derive(Debug)] pub struct LoadStatementOpen { pub string_address: Word, } #[repr(C)] #[derive(Debug)] pub struct LoadStatementMmap { /// The starting address for the new mapping. pub addr: Word, /// The length of the mapping. pub length: Word, /// The desired memory protection of the mapping. pub prot: Word, /// The offset in the file which the mapping will start at. pub offset: Word, /// The byte size of the memory area to be zeroed forward at the end of the /// page in this memory mapping. pub clear_length: Word, } #[repr(C)] #[derive(Debug)] pub struct LoadStatementStackExec { /// The beginning address (page-aligned) of the stack. pub start: Word, } #[repr(C)] #[derive(Debug)] pub struct LoadStatementStart { /// Value of stack pointer pub stack_pointer: Word, /// The entry address of the executable, or the entry address of the loader if `PT_INTERP` exists. pub entry_point: Word, pub at_phdr: Word, pub at_phent: Word, pub at_phnum: Word, pub at_entry: Word, pub at_execfn: Word, } impl LoadStatement { pub fn as_bytes(&self) -> &[u8] { let mut size = match self { LoadStatement::OpenNext(_) | LoadStatement::Open(_) => { core::mem::size_of::<LoadStatementOpen>() } LoadStatement::MmapFile(_) | LoadStatement::MmapAnonymous(_) => { core::mem::size_of::<LoadStatementMmap>() } LoadStatement::MakeStackExec(_) => core::mem::size_of::<LoadStatementStackExec>(), LoadStatement::StartTraced(_) | LoadStatement::Start(_) => { core::mem::size_of::<LoadStatementStart>() } }; size += core::mem::size_of::<Word>(); let bytes = unsafe { core::slice::from_raw_parts((self as *const LoadStatement) as *const u8, size) }; bytes } }
LoadStatement
identifier_name
script.rs
#[cfg(any(target_arch = "x86", target_arch = "arm"))] pub type Word = u32; #[cfg(any(target_arch = "x86_64", target_arch = "aarch64"))] pub type Word = u64; #[cfg_attr(any(target_arch = "x86_64", target_arch = "aarch64"), repr(C, u64))] #[cfg_attr(any(target_arch = "x86", target_arch = "arm"), repr(C, u32))] #[allow(dead_code)] #[derive(Debug)] pub enum LoadStatement { /// Close last opened file and open a new file. OpenNext(LoadStatementOpen), /// Open a file, and save the file descriptor. Open(LoadStatementOpen), /// Map a part of the last opened file into memory. MmapFile(LoadStatementMmap), /// Mapping a segment of anonymous private space into memory instead of mapping from a file.
StartTraced(LoadStatementStart), /// Start(LoadStatementStart), } #[repr(C)] #[derive(Debug)] pub struct LoadStatementOpen { pub string_address: Word, } #[repr(C)] #[derive(Debug)] pub struct LoadStatementMmap { /// The starting address for the new mapping. pub addr: Word, /// The length of the mapping. pub length: Word, /// The desired memory protection of the mapping. pub prot: Word, /// The offset in the file which the mapping will start at. pub offset: Word, /// The byte size of the memory area to be zeroed forward at the end of the /// page in this memory mapping. pub clear_length: Word, } #[repr(C)] #[derive(Debug)] pub struct LoadStatementStackExec { /// The beginning address (page-aligned) of the stack. pub start: Word, } #[repr(C)] #[derive(Debug)] pub struct LoadStatementStart { /// Value of stack pointer pub stack_pointer: Word, /// The entry address of the executable, or the entry address of the loader if `PT_INTERP` exists. pub entry_point: Word, pub at_phdr: Word, pub at_phent: Word, pub at_phnum: Word, pub at_entry: Word, pub at_execfn: Word, } impl LoadStatement { pub fn as_bytes(&self) -> &[u8] { let mut size = match self { LoadStatement::OpenNext(_) | LoadStatement::Open(_) => { core::mem::size_of::<LoadStatementOpen>() } LoadStatement::MmapFile(_) | LoadStatement::MmapAnonymous(_) => { core::mem::size_of::<LoadStatementMmap>() } LoadStatement::MakeStackExec(_) => core::mem::size_of::<LoadStatementStackExec>(), LoadStatement::StartTraced(_) | LoadStatement::Start(_) => { core::mem::size_of::<LoadStatementStart>() } }; size += core::mem::size_of::<Word>(); let bytes = unsafe { core::slice::from_raw_parts((self as *const LoadStatement) as *const u8, size) }; bytes } }
MmapAnonymous(LoadStatementMmap), /// Set the stack space to be executable MakeStackExec(LoadStatementStackExec), /// (The purpose of the project is not yet clear)
random_line_split
mod.rs
use num::{ToPrimitive, FromPrimitive}; use std::ptr; use EventPump; use rect::Rect; use video::Window; use sys::keyboard as ll; mod keycode; mod scancode; pub use self::keycode::Keycode; pub use self::scancode::Scancode; bitflags! { flags Mod: u32 { const NOMOD = 0x0000, const LSHIFTMOD = 0x0001, const RSHIFTMOD = 0x0002, const LCTRLMOD = 0x0040, const RCTRLMOD = 0x0080, const LALTMOD = 0x0100, const RALTMOD = 0x0200, const LGUIMOD = 0x0400, const RGUIMOD = 0x0800, const NUMMOD = 0x1000, const CAPSMOD = 0x2000, const MODEMOD = 0x4000, const RESERVEDMOD = 0x8000 } } pub struct KeyboardState<'a> { keyboard_state: &'a [u8] } impl<'a> KeyboardState<'a> { pub fn new(_e: &'a EventPump) -> KeyboardState<'a> { let keyboard_state = unsafe { let mut count = 0; let state_ptr = ll::SDL_GetKeyboardState(&mut count); ::std::slice::from_raw_parts(state_ptr, count as usize) }; KeyboardState { keyboard_state: keyboard_state } } /// Returns true if the scancode is pressed. /// /// # Example /// ```no_run /// use sdl2::keyboard::Scancode; /// /// fn is_a_pressed(e: &sdl2::EventPump) -> bool { /// e.keyboard_state().is_scancode_pressed(Scancode::A) /// } /// ``` pub fn is_scancode_pressed(&self, scancode: Scancode) -> bool { self.keyboard_state[ToPrimitive::to_isize(&scancode).unwrap() as usize]!= 0 } /// Returns an iterator all scancodes with a boolean indicating if the scancode is pressed. pub fn scancodes(&self) -> ScancodeIterator { ScancodeIterator { index: 0, keyboard_state: self.keyboard_state } } /// Returns an iterator of pressed scancodes. /// /// # Example /// ```no_run /// use sdl2::keyboard::Keycode; /// use sdl2::keyboard::Scancode; /// use std::collections::HashSet; /// /// fn pressed_scancode_set(e: &sdl2::EventPump) -> HashSet<Scancode> { /// e.keyboard_state().pressed_scancodes().collect() /// } /// /// fn pressed_keycode_set(e: &sdl2::EventPump) -> HashSet<Keycode> { /// e.keyboard_state().pressed_scancodes() /// .filter_map(Keycode::from_scancode) /// .collect() /// } /// /// fn newly_pressed(old: &HashSet<Scancode>, new: &HashSet<Scancode>) -> HashSet<Scancode> { /// new - old /// // sugar for: new.difference(old).collect() /// } /// ``` pub fn pressed_scancodes(&self) -> PressedScancodeIterator { PressedScancodeIterator { iter: self.scancodes() } } } pub struct ScancodeIterator<'a> { index: usize, keyboard_state: &'a [u8] } impl<'a> Iterator for ScancodeIterator<'a> { type Item = (Scancode, bool); fn next(&mut self) -> Option<(Scancode, bool)> { if self.index < self.keyboard_state.len() { let index = self.index; self.index += 1; if let Some(scancode) = FromPrimitive::from_usize(index) { let pressed = self.keyboard_state[index]!= 0; Some((scancode, pressed)) } else { self.next() } } else { None } } } pub struct PressedScancodeIterator<'a> { iter: ScancodeIterator<'a> } impl<'a> Iterator for PressedScancodeIterator<'a> { type Item = Scancode; fn
(&mut self) -> Option<Scancode> { while let Some((scancode, pressed)) = self.iter.next() { if pressed { return Some(scancode) } } None } } impl ::Sdl { #[inline] pub fn keyboard(&self) -> KeyboardUtil { KeyboardUtil { _sdldrop: self.sdldrop() } } } impl ::VideoSubsystem { #[inline] pub fn text_input(&self) -> TextInputUtil { TextInputUtil { _subsystem: self.clone() } } } /// Keyboard utility functions. Access with `Sdl::keyboard()`. /// /// ```no_run /// let sdl_context = sdl2::init().unwrap(); /// /// let focused = sdl_context.keyboard().focused_window_id().is_some(); /// ``` pub struct KeyboardUtil { _sdldrop: ::std::rc::Rc<::SdlDrop> } impl KeyboardUtil { /// Gets the id of the window which currently has keyboard focus. pub fn focused_window_id(&self) -> Option<u32> { let raw = unsafe { ll::SDL_GetKeyboardFocus() }; if raw == ptr::null_mut() { None } else { let id = unsafe { ::sys::video::SDL_GetWindowID(raw) }; Some(id) } } pub fn mod_state(&self) -> Mod { unsafe { Mod::from_bits(ll::SDL_GetModState()).unwrap() } } pub fn set_mod_state(&self, flags: Mod) { unsafe { ll::SDL_SetModState(flags.bits()); } } } /// Text input utility functions. Access with `VideoSubsystem::text_input()`. /// /// These functions require the video subsystem to be initialized and are not thread-safe. /// /// ```no_run /// let sdl_context = sdl2::init().unwrap(); /// let video_subsystem = sdl_context.video().unwrap(); /// /// // Start accepting text input events... /// video_subsystem.text_input().start(); /// ``` pub struct TextInputUtil { _subsystem: ::VideoSubsystem } impl TextInputUtil { pub fn start(&self) { unsafe { ll::SDL_StartTextInput(); } } pub fn is_active(&self, ) -> bool { unsafe { ll::SDL_IsTextInputActive() == 1 } } pub fn stop(&self) { unsafe { ll::SDL_StopTextInput(); } } pub fn set_rect(&self, rect: &Rect) { unsafe { ll::SDL_SetTextInputRect(rect.raw()); } } pub fn has_screen_keyboard_support(&self) -> bool { unsafe { ll::SDL_HasScreenKeyboardSupport() == 1 } } pub fn is_screen_keyboard_shown(&self, window: &Window) -> bool { unsafe { ll::SDL_IsScreenKeyboardShown(window.raw()) == 1 } } }
next
identifier_name
mod.rs
use num::{ToPrimitive, FromPrimitive}; use std::ptr; use EventPump; use rect::Rect; use video::Window; use sys::keyboard as ll; mod keycode; mod scancode; pub use self::keycode::Keycode; pub use self::scancode::Scancode; bitflags! { flags Mod: u32 { const NOMOD = 0x0000, const LSHIFTMOD = 0x0001, const RSHIFTMOD = 0x0002, const LCTRLMOD = 0x0040, const RCTRLMOD = 0x0080, const LALTMOD = 0x0100, const RALTMOD = 0x0200, const LGUIMOD = 0x0400, const RGUIMOD = 0x0800, const NUMMOD = 0x1000, const CAPSMOD = 0x2000, const MODEMOD = 0x4000, const RESERVEDMOD = 0x8000 } } pub struct KeyboardState<'a> { keyboard_state: &'a [u8] } impl<'a> KeyboardState<'a> { pub fn new(_e: &'a EventPump) -> KeyboardState<'a> { let keyboard_state = unsafe { let mut count = 0; let state_ptr = ll::SDL_GetKeyboardState(&mut count); ::std::slice::from_raw_parts(state_ptr, count as usize) }; KeyboardState { keyboard_state: keyboard_state } } /// Returns true if the scancode is pressed. /// /// # Example /// ```no_run /// use sdl2::keyboard::Scancode; /// /// fn is_a_pressed(e: &sdl2::EventPump) -> bool { /// e.keyboard_state().is_scancode_pressed(Scancode::A) /// } /// ``` pub fn is_scancode_pressed(&self, scancode: Scancode) -> bool { self.keyboard_state[ToPrimitive::to_isize(&scancode).unwrap() as usize]!= 0 }
/// Returns an iterator all scancodes with a boolean indicating if the scancode is pressed. pub fn scancodes(&self) -> ScancodeIterator { ScancodeIterator { index: 0, keyboard_state: self.keyboard_state } } /// Returns an iterator of pressed scancodes. /// /// # Example /// ```no_run /// use sdl2::keyboard::Keycode; /// use sdl2::keyboard::Scancode; /// use std::collections::HashSet; /// /// fn pressed_scancode_set(e: &sdl2::EventPump) -> HashSet<Scancode> { /// e.keyboard_state().pressed_scancodes().collect() /// } /// /// fn pressed_keycode_set(e: &sdl2::EventPump) -> HashSet<Keycode> { /// e.keyboard_state().pressed_scancodes() /// .filter_map(Keycode::from_scancode) /// .collect() /// } /// /// fn newly_pressed(old: &HashSet<Scancode>, new: &HashSet<Scancode>) -> HashSet<Scancode> { /// new - old /// // sugar for: new.difference(old).collect() /// } /// ``` pub fn pressed_scancodes(&self) -> PressedScancodeIterator { PressedScancodeIterator { iter: self.scancodes() } } } pub struct ScancodeIterator<'a> { index: usize, keyboard_state: &'a [u8] } impl<'a> Iterator for ScancodeIterator<'a> { type Item = (Scancode, bool); fn next(&mut self) -> Option<(Scancode, bool)> { if self.index < self.keyboard_state.len() { let index = self.index; self.index += 1; if let Some(scancode) = FromPrimitive::from_usize(index) { let pressed = self.keyboard_state[index]!= 0; Some((scancode, pressed)) } else { self.next() } } else { None } } } pub struct PressedScancodeIterator<'a> { iter: ScancodeIterator<'a> } impl<'a> Iterator for PressedScancodeIterator<'a> { type Item = Scancode; fn next(&mut self) -> Option<Scancode> { while let Some((scancode, pressed)) = self.iter.next() { if pressed { return Some(scancode) } } None } } impl ::Sdl { #[inline] pub fn keyboard(&self) -> KeyboardUtil { KeyboardUtil { _sdldrop: self.sdldrop() } } } impl ::VideoSubsystem { #[inline] pub fn text_input(&self) -> TextInputUtil { TextInputUtil { _subsystem: self.clone() } } } /// Keyboard utility functions. Access with `Sdl::keyboard()`. /// /// ```no_run /// let sdl_context = sdl2::init().unwrap(); /// /// let focused = sdl_context.keyboard().focused_window_id().is_some(); /// ``` pub struct KeyboardUtil { _sdldrop: ::std::rc::Rc<::SdlDrop> } impl KeyboardUtil { /// Gets the id of the window which currently has keyboard focus. pub fn focused_window_id(&self) -> Option<u32> { let raw = unsafe { ll::SDL_GetKeyboardFocus() }; if raw == ptr::null_mut() { None } else { let id = unsafe { ::sys::video::SDL_GetWindowID(raw) }; Some(id) } } pub fn mod_state(&self) -> Mod { unsafe { Mod::from_bits(ll::SDL_GetModState()).unwrap() } } pub fn set_mod_state(&self, flags: Mod) { unsafe { ll::SDL_SetModState(flags.bits()); } } } /// Text input utility functions. Access with `VideoSubsystem::text_input()`. /// /// These functions require the video subsystem to be initialized and are not thread-safe. /// /// ```no_run /// let sdl_context = sdl2::init().unwrap(); /// let video_subsystem = sdl_context.video().unwrap(); /// /// // Start accepting text input events... /// video_subsystem.text_input().start(); /// ``` pub struct TextInputUtil { _subsystem: ::VideoSubsystem } impl TextInputUtil { pub fn start(&self) { unsafe { ll::SDL_StartTextInput(); } } pub fn is_active(&self, ) -> bool { unsafe { ll::SDL_IsTextInputActive() == 1 } } pub fn stop(&self) { unsafe { ll::SDL_StopTextInput(); } } pub fn set_rect(&self, rect: &Rect) { unsafe { ll::SDL_SetTextInputRect(rect.raw()); } } pub fn has_screen_keyboard_support(&self) -> bool { unsafe { ll::SDL_HasScreenKeyboardSupport() == 1 } } pub fn is_screen_keyboard_shown(&self, window: &Window) -> bool { unsafe { ll::SDL_IsScreenKeyboardShown(window.raw()) == 1 } } }
random_line_split
mod.rs
use num::{ToPrimitive, FromPrimitive}; use std::ptr; use EventPump; use rect::Rect; use video::Window; use sys::keyboard as ll; mod keycode; mod scancode; pub use self::keycode::Keycode; pub use self::scancode::Scancode; bitflags! { flags Mod: u32 { const NOMOD = 0x0000, const LSHIFTMOD = 0x0001, const RSHIFTMOD = 0x0002, const LCTRLMOD = 0x0040, const RCTRLMOD = 0x0080, const LALTMOD = 0x0100, const RALTMOD = 0x0200, const LGUIMOD = 0x0400, const RGUIMOD = 0x0800, const NUMMOD = 0x1000, const CAPSMOD = 0x2000, const MODEMOD = 0x4000, const RESERVEDMOD = 0x8000 } } pub struct KeyboardState<'a> { keyboard_state: &'a [u8] } impl<'a> KeyboardState<'a> { pub fn new(_e: &'a EventPump) -> KeyboardState<'a> { let keyboard_state = unsafe { let mut count = 0; let state_ptr = ll::SDL_GetKeyboardState(&mut count); ::std::slice::from_raw_parts(state_ptr, count as usize) }; KeyboardState { keyboard_state: keyboard_state } } /// Returns true if the scancode is pressed. /// /// # Example /// ```no_run /// use sdl2::keyboard::Scancode; /// /// fn is_a_pressed(e: &sdl2::EventPump) -> bool { /// e.keyboard_state().is_scancode_pressed(Scancode::A) /// } /// ``` pub fn is_scancode_pressed(&self, scancode: Scancode) -> bool { self.keyboard_state[ToPrimitive::to_isize(&scancode).unwrap() as usize]!= 0 } /// Returns an iterator all scancodes with a boolean indicating if the scancode is pressed. pub fn scancodes(&self) -> ScancodeIterator { ScancodeIterator { index: 0, keyboard_state: self.keyboard_state } } /// Returns an iterator of pressed scancodes. /// /// # Example /// ```no_run /// use sdl2::keyboard::Keycode; /// use sdl2::keyboard::Scancode; /// use std::collections::HashSet; /// /// fn pressed_scancode_set(e: &sdl2::EventPump) -> HashSet<Scancode> { /// e.keyboard_state().pressed_scancodes().collect() /// } /// /// fn pressed_keycode_set(e: &sdl2::EventPump) -> HashSet<Keycode> { /// e.keyboard_state().pressed_scancodes() /// .filter_map(Keycode::from_scancode) /// .collect() /// } /// /// fn newly_pressed(old: &HashSet<Scancode>, new: &HashSet<Scancode>) -> HashSet<Scancode> { /// new - old /// // sugar for: new.difference(old).collect() /// } /// ``` pub fn pressed_scancodes(&self) -> PressedScancodeIterator { PressedScancodeIterator { iter: self.scancodes() } } } pub struct ScancodeIterator<'a> { index: usize, keyboard_state: &'a [u8] } impl<'a> Iterator for ScancodeIterator<'a> { type Item = (Scancode, bool); fn next(&mut self) -> Option<(Scancode, bool)> { if self.index < self.keyboard_state.len() { let index = self.index; self.index += 1; if let Some(scancode) = FromPrimitive::from_usize(index) { let pressed = self.keyboard_state[index]!= 0; Some((scancode, pressed)) } else { self.next() } } else { None } } } pub struct PressedScancodeIterator<'a> { iter: ScancodeIterator<'a> } impl<'a> Iterator for PressedScancodeIterator<'a> { type Item = Scancode; fn next(&mut self) -> Option<Scancode> { while let Some((scancode, pressed)) = self.iter.next() { if pressed { return Some(scancode) } } None } } impl ::Sdl { #[inline] pub fn keyboard(&self) -> KeyboardUtil { KeyboardUtil { _sdldrop: self.sdldrop() } } } impl ::VideoSubsystem { #[inline] pub fn text_input(&self) -> TextInputUtil { TextInputUtil { _subsystem: self.clone() } } } /// Keyboard utility functions. Access with `Sdl::keyboard()`. /// /// ```no_run /// let sdl_context = sdl2::init().unwrap(); /// /// let focused = sdl_context.keyboard().focused_window_id().is_some(); /// ``` pub struct KeyboardUtil { _sdldrop: ::std::rc::Rc<::SdlDrop> } impl KeyboardUtil { /// Gets the id of the window which currently has keyboard focus. pub fn focused_window_id(&self) -> Option<u32> { let raw = unsafe { ll::SDL_GetKeyboardFocus() }; if raw == ptr::null_mut() { None } else
} pub fn mod_state(&self) -> Mod { unsafe { Mod::from_bits(ll::SDL_GetModState()).unwrap() } } pub fn set_mod_state(&self, flags: Mod) { unsafe { ll::SDL_SetModState(flags.bits()); } } } /// Text input utility functions. Access with `VideoSubsystem::text_input()`. /// /// These functions require the video subsystem to be initialized and are not thread-safe. /// /// ```no_run /// let sdl_context = sdl2::init().unwrap(); /// let video_subsystem = sdl_context.video().unwrap(); /// /// // Start accepting text input events... /// video_subsystem.text_input().start(); /// ``` pub struct TextInputUtil { _subsystem: ::VideoSubsystem } impl TextInputUtil { pub fn start(&self) { unsafe { ll::SDL_StartTextInput(); } } pub fn is_active(&self, ) -> bool { unsafe { ll::SDL_IsTextInputActive() == 1 } } pub fn stop(&self) { unsafe { ll::SDL_StopTextInput(); } } pub fn set_rect(&self, rect: &Rect) { unsafe { ll::SDL_SetTextInputRect(rect.raw()); } } pub fn has_screen_keyboard_support(&self) -> bool { unsafe { ll::SDL_HasScreenKeyboardSupport() == 1 } } pub fn is_screen_keyboard_shown(&self, window: &Window) -> bool { unsafe { ll::SDL_IsScreenKeyboardShown(window.raw()) == 1 } } }
{ let id = unsafe { ::sys::video::SDL_GetWindowID(raw) }; Some(id) }
conditional_block
main.rs
// // gash.rs // // Starting code for PS2 // Running on Rust 0.9 // // University of Virginia - cs4414 Spring 2014 // Weilin Xu, David Evans // Version 0.4 // extern crate getopts; use getopts::{optopt, getopts}; use std::io::BufferedReader; use std::io::Command; use std::io::stdin; use std::{io, os}; use std::str; struct Shell<'a> { cmd_prompt: &'a str, } impl <'a>Shell<'a> { fn new(prompt_str: &'a str) -> Shell<'a> { Shell { cmd_prompt: prompt_str } } fn run(&self) { let mut stdin = BufferedReader::new(stdin()); loop { io::stdio::print(self.cmd_prompt.as_slice()); io::stdio::flush(); let line = stdin.read_line().unwrap(); let cmd_line = line.trim(); let program = cmd_line.splitn(1,'').nth(0).expect("no program"); match program { "" => { continue; } "exit" => { return; } _ => { self.run_cmdline(cmd_line); } } } } fn run_cmdline(&self, cmd_line: &str) { let argv: Vec<&str> = cmd_line.split(' ').filter_map(|x| { if x == "" { None } else { Some(x) } }).collect(); match argv.first() { Some(&program) => self.run_cmd(program, argv.tail()), None => (), }; } fn run_cmd(&self, program: &str, argv: &[&str]) { if self.cmd_exists(program) { io::stdio::print(str::from_utf8(Command::new(program).args(argv).output().unwrap().output.as_slice()).unwrap()); } else { println!("{}: command not found", program); } } fn cmd_exists(&self, cmd_path: &str) -> bool
} fn get_cmdline_from_args() -> Option<String> { /* Begin processing program arguments and initiate the parameters. */ let args = os::args(); let opts = &[ getopts::optopt("c", "", "", "") ]; getopts::getopts(args.tail(), opts).unwrap().opt_str("c") } fn main() { let opt_cmd_line = get_cmdline_from_args(); match opt_cmd_line { Some(cmd_line) => Shell::new("").run_cmdline(cmd_line.as_slice()), None => Shell::new("gash > ").run(), } }
{ Command::new("which").arg(cmd_path).status().unwrap().success() }
identifier_body
main.rs
// // gash.rs // // Starting code for PS2 // Running on Rust 0.9 // // University of Virginia - cs4414 Spring 2014 // Weilin Xu, David Evans // Version 0.4 // extern crate getopts; use getopts::{optopt, getopts}; use std::io::BufferedReader; use std::io::Command; use std::io::stdin; use std::{io, os}; use std::str; struct Shell<'a> { cmd_prompt: &'a str, } impl <'a>Shell<'a> { fn new(prompt_str: &'a str) -> Shell<'a> { Shell { cmd_prompt: prompt_str } } fn run(&self) { let mut stdin = BufferedReader::new(stdin()); loop { io::stdio::print(self.cmd_prompt.as_slice()); io::stdio::flush(); let line = stdin.read_line().unwrap(); let cmd_line = line.trim(); let program = cmd_line.splitn(1,'').nth(0).expect("no program"); match program { "" => { continue; } "exit" => { return; } _ =>
} } } fn run_cmdline(&self, cmd_line: &str) { let argv: Vec<&str> = cmd_line.split(' ').filter_map(|x| { if x == "" { None } else { Some(x) } }).collect(); match argv.first() { Some(&program) => self.run_cmd(program, argv.tail()), None => (), }; } fn run_cmd(&self, program: &str, argv: &[&str]) { if self.cmd_exists(program) { io::stdio::print(str::from_utf8(Command::new(program).args(argv).output().unwrap().output.as_slice()).unwrap()); } else { println!("{}: command not found", program); } } fn cmd_exists(&self, cmd_path: &str) -> bool { Command::new("which").arg(cmd_path).status().unwrap().success() } } fn get_cmdline_from_args() -> Option<String> { /* Begin processing program arguments and initiate the parameters. */ let args = os::args(); let opts = &[ getopts::optopt("c", "", "", "") ]; getopts::getopts(args.tail(), opts).unwrap().opt_str("c") } fn main() { let opt_cmd_line = get_cmdline_from_args(); match opt_cmd_line { Some(cmd_line) => Shell::new("").run_cmdline(cmd_line.as_slice()), None => Shell::new("gash > ").run(), } }
{ self.run_cmdline(cmd_line); }
conditional_block
main.rs
// // gash.rs // // Starting code for PS2 // Running on Rust 0.9 // // University of Virginia - cs4414 Spring 2014 // Weilin Xu, David Evans // Version 0.4 // extern crate getopts; use getopts::{optopt, getopts}; use std::io::BufferedReader; use std::io::Command; use std::io::stdin; use std::{io, os}; use std::str; struct Shell<'a> { cmd_prompt: &'a str, } impl <'a>Shell<'a> { fn new(prompt_str: &'a str) -> Shell<'a> { Shell { cmd_prompt: prompt_str } } fn run(&self) { let mut stdin = BufferedReader::new(stdin()); loop { io::stdio::print(self.cmd_prompt.as_slice()); io::stdio::flush(); let line = stdin.read_line().unwrap(); let cmd_line = line.trim(); let program = cmd_line.splitn(1,'').nth(0).expect("no program"); match program { "" => { continue; } "exit" => { return; } _ => { self.run_cmdline(cmd_line); } } } } fn run_cmdline(&self, cmd_line: &str) { let argv: Vec<&str> = cmd_line.split(' ').filter_map(|x| { if x == "" { None } else { Some(x) } }).collect(); match argv.first() { Some(&program) => self.run_cmd(program, argv.tail()), None => (), }; } fn run_cmd(&self, program: &str, argv: &[&str]) { if self.cmd_exists(program) { io::stdio::print(str::from_utf8(Command::new(program).args(argv).output().unwrap().output.as_slice()).unwrap()); } else { println!("{}: command not found", program); } }
} fn get_cmdline_from_args() -> Option<String> { /* Begin processing program arguments and initiate the parameters. */ let args = os::args(); let opts = &[ getopts::optopt("c", "", "", "") ]; getopts::getopts(args.tail(), opts).unwrap().opt_str("c") } fn main() { let opt_cmd_line = get_cmdline_from_args(); match opt_cmd_line { Some(cmd_line) => Shell::new("").run_cmdline(cmd_line.as_slice()), None => Shell::new("gash > ").run(), } }
fn cmd_exists(&self, cmd_path: &str) -> bool { Command::new("which").arg(cmd_path).status().unwrap().success() }
random_line_split
main.rs
// // gash.rs // // Starting code for PS2 // Running on Rust 0.9 // // University of Virginia - cs4414 Spring 2014 // Weilin Xu, David Evans // Version 0.4 // extern crate getopts; use getopts::{optopt, getopts}; use std::io::BufferedReader; use std::io::Command; use std::io::stdin; use std::{io, os}; use std::str; struct Shell<'a> { cmd_prompt: &'a str, } impl <'a>Shell<'a> { fn new(prompt_str: &'a str) -> Shell<'a> { Shell { cmd_prompt: prompt_str } } fn run(&self) { let mut stdin = BufferedReader::new(stdin()); loop { io::stdio::print(self.cmd_prompt.as_slice()); io::stdio::flush(); let line = stdin.read_line().unwrap(); let cmd_line = line.trim(); let program = cmd_line.splitn(1,'').nth(0).expect("no program"); match program { "" => { continue; } "exit" => { return; } _ => { self.run_cmdline(cmd_line); } } } } fn
(&self, cmd_line: &str) { let argv: Vec<&str> = cmd_line.split(' ').filter_map(|x| { if x == "" { None } else { Some(x) } }).collect(); match argv.first() { Some(&program) => self.run_cmd(program, argv.tail()), None => (), }; } fn run_cmd(&self, program: &str, argv: &[&str]) { if self.cmd_exists(program) { io::stdio::print(str::from_utf8(Command::new(program).args(argv).output().unwrap().output.as_slice()).unwrap()); } else { println!("{}: command not found", program); } } fn cmd_exists(&self, cmd_path: &str) -> bool { Command::new("which").arg(cmd_path).status().unwrap().success() } } fn get_cmdline_from_args() -> Option<String> { /* Begin processing program arguments and initiate the parameters. */ let args = os::args(); let opts = &[ getopts::optopt("c", "", "", "") ]; getopts::getopts(args.tail(), opts).unwrap().opt_str("c") } fn main() { let opt_cmd_line = get_cmdline_from_args(); match opt_cmd_line { Some(cmd_line) => Shell::new("").run_cmdline(cmd_line.as_slice()), None => Shell::new("gash > ").run(), } }
run_cmdline
identifier_name
query.rs
use common::{ApiError, Body, Credentials, Query, QueryParams, discovery_api}; use hyper::method::Method::Get; use serde_json::Value; pub fn query(creds: &Credentials, env_id: &str, collection_id: &str, query: QueryParams) -> Result<Value, ApiError> { let path = "/v1/environments/".to_string() + env_id + "/collections/" + collection_id + "/query"; Ok(discovery_api(creds, Get, &path, Query::Query(query), &Body::None)?) } pub fn
(creds: &Credentials, env_id: &str, collection_id: &str, query: QueryParams) -> Result<Value, ApiError> { let path = "/v1/environments/".to_string() + env_id + "/collections/" + collection_id + "/notices"; Ok(discovery_api(creds, Get, &path, Query::Query(query), &Body::None)?) }
notices
identifier_name
query.rs
use common::{ApiError, Body, Credentials, Query, QueryParams, discovery_api}; use hyper::method::Method::Get; use serde_json::Value; pub fn query(creds: &Credentials, env_id: &str, collection_id: &str, query: QueryParams) -> Result<Value, ApiError>
pub fn notices(creds: &Credentials, env_id: &str, collection_id: &str, query: QueryParams) -> Result<Value, ApiError> { let path = "/v1/environments/".to_string() + env_id + "/collections/" + collection_id + "/notices"; Ok(discovery_api(creds, Get, &path, Query::Query(query), &Body::None)?) }
{ let path = "/v1/environments/".to_string() + env_id + "/collections/" + collection_id + "/query"; Ok(discovery_api(creds, Get, &path, Query::Query(query), &Body::None)?) }
identifier_body
query.rs
use common::{ApiError, Body, Credentials, Query, QueryParams, discovery_api}; use hyper::method::Method::Get; use serde_json::Value; pub fn query(creds: &Credentials, env_id: &str, collection_id: &str, query: QueryParams) -> Result<Value, ApiError> { let path = "/v1/environments/".to_string() + env_id + "/collections/" + collection_id + "/query"; Ok(discovery_api(creds, Get, &path, Query::Query(query), &Body::None)?) } pub fn notices(creds: &Credentials, env_id: &str, collection_id: &str, query: QueryParams)
-> Result<Value, ApiError> { let path = "/v1/environments/".to_string() + env_id + "/collections/" + collection_id + "/notices"; Ok(discovery_api(creds, Get, &path, Query::Query(query), &Body::None)?) }
random_line_split
xy_pad.rs
use { Backend, Color, Colorable, Frameable, FramedRectangle, FontSize, IndexSlot, Labelable, Line, Mouse, Positionable, Scalar, Sizeable, Text, Widget, }; use num::Float; use widget; use utils::{map_range, val_to_string}; /// Used for displaying and controlling a 2D point on a cartesian plane within a given range. /// /// Its reaction is triggered when the value is updated or if the mouse button is released while /// the cursor is above the rectangle. pub struct XYPad<'a, X, Y, F> { common: widget::CommonBuilder, x: X, min_x: X, max_x: X, y: Y, min_y: Y, max_y: Y, maybe_label: Option<&'a str>, /// The reaction function for the XYPad. /// /// It will be triggered when the value is updated or if the mouse button is released while the /// cursor is above the rectangle. pub maybe_react: Option<F>, style: Style, /// Indicates whether the XYPad will respond to user input. pub enabled: bool, } /// Unique kind for the widget type. pub const KIND: widget::Kind = "XYPad"; widget_style!{ KIND; /// Unique graphical styling for the XYPad. style Style { /// The color of the XYPad's rectangle. - color: Color { theme.shape_color } /// The width of the frame surrounding the rectangle. - frame: Scalar { theme.frame_width } /// The color of the surrounding rectangle frame. - frame_color: Color { theme.frame_color } /// The color of the XYPad's label and value label text. - label_color: Color { theme.label_color } /// The font size for the XYPad's label. - label_font_size: FontSize { theme.font_size_medium } /// The font size for the XYPad's *value* label. - value_font_size: FontSize { 14 } /// The thickness of the XYPad's crosshair lines. - line_thickness: Scalar { 2.0 } } } /// The state of the XYPad. #[derive(Clone, Debug, PartialEq)] pub struct State<X, Y> { x: X, min_x: X, max_x: X, y: Y, min_y: Y, max_y: Y, interaction: Interaction, rectangle_idx: IndexSlot, label_idx: IndexSlot, h_line_idx: IndexSlot, v_line_idx: IndexSlot, value_label_idx: IndexSlot, } /// The interaction state of the XYPad. #[derive(Debug, PartialEq, Clone, Copy)] pub enum Interaction { Normal, Highlighted, Clicked, } impl Interaction { /// The color associated with the current state. fn color(&self, color: Color) -> Color { match *self { Interaction::Normal => color, Interaction::Highlighted => color.highlighted(), Interaction::Clicked => color.clicked(), } } } /// Check the current state of the button. fn get_new_interaction(is_over: bool, prev: Interaction, mouse: Mouse) -> Interaction { use mouse::ButtonPosition::{Down, Up}; use self::Interaction::{Normal, Highlighted, Clicked}; match (is_over, prev, mouse.left.position) { (true, Normal, Down) => Normal, (true, _, Down) => Clicked, (true, _, Up) => Highlighted, (false, Clicked, Down) => Clicked, _ => Normal, } } impl<'a, X, Y, F> XYPad<'a, X, Y, F> { /// Build a new XYPad widget. pub fn new(x_val: X, min_x: X, max_x: X, y_val: Y, min_y: Y, max_y: Y) -> Self { XYPad { common: widget::CommonBuilder::new(), x: x_val, min_x: min_x, max_x: max_x, y: y_val, min_y: min_y, max_y: max_y, maybe_react: None, maybe_label: None, style: Style::new(), enabled: true, } } builder_methods!{ pub line_thickness { style.line_thickness = Some(Scalar) } pub value_font_size { style.value_font_size = Some(FontSize) } pub react { maybe_react = Some(F) } pub enabled { enabled = bool } } } impl<'a, X, Y, F> Widget for XYPad<'a, X, Y, F> where X: Float + ToString + ::std::fmt::Debug + ::std::any::Any, Y: Float + ToString + ::std::fmt::Debug + ::std::any::Any, F: FnOnce(X, Y), { type State = State<X, Y>; type Style = Style; fn common(&self) -> &widget::CommonBuilder { &self.common } fn common_mut(&mut self) -> &mut widget::CommonBuilder { &mut self.common } fn unique_kind(&self) -> &'static str { KIND } fn
(&self) -> Self::State { State { interaction: Interaction::Normal, x: self.x, min_x: self.min_x, max_x: self.max_x, y: self.y, min_y: self.min_y, max_y: self.max_y, rectangle_idx: IndexSlot::new(), label_idx: IndexSlot::new(), h_line_idx: IndexSlot::new(), v_line_idx: IndexSlot::new(), value_label_idx: IndexSlot::new(), } } fn style(&self) -> Style { self.style.clone() } /// Update the XYPad's cached state. fn update<B: Backend>(self, args: widget::UpdateArgs<Self, B>) { use position::{Direction, Edge}; use self::Interaction::{Clicked, Highlighted, Normal}; let widget::UpdateArgs { idx, state, rect, style, mut ui,.. } = args; let XYPad { enabled, x, min_x, max_x, y, min_y, max_y, maybe_label, maybe_react, .. } = self; let maybe_mouse = ui.input(idx).maybe_mouse; let frame = style.frame(ui.theme()); let inner_rect = rect.pad(frame); let interaction = state.view().interaction; let new_interaction = match (enabled, maybe_mouse) { (false, _) | (true, None) => Normal, (true, Some(mouse)) => { let is_over_inner = inner_rect.is_over(mouse.xy); get_new_interaction(is_over_inner, interaction, mouse) }, }; // Capture the mouse if clicked, uncapture if released. match (interaction, new_interaction) { (Highlighted, Clicked) => { ui.capture_mouse(idx); }, (Clicked, Highlighted) | (Clicked, Normal) => { ui.uncapture_mouse(idx); }, _ => (), } // Determine new values from the mouse position over the pad. let (new_x, new_y) = match (maybe_mouse, new_interaction) { (None, _) | (_, Normal) | (_, Highlighted) => (x, y), (Some(mouse), Clicked) => { let clamped_x = inner_rect.x.clamp_value(mouse.xy[0]); let clamped_y = inner_rect.y.clamp_value(mouse.xy[1]); let (l, r, b, t) = inner_rect.l_r_b_t(); let new_x = map_range(clamped_x, l, r, min_x, max_x); let new_y = map_range(clamped_y, b, t, min_y, max_y); (new_x, new_y) }, }; // React if value is changed or the pad is clicked/released. if let Some(react) = maybe_react { let should_react = x!= new_x || y!= new_y || (interaction == Highlighted && new_interaction == Clicked) || (interaction == Clicked && new_interaction == Highlighted); if should_react { react(new_x, new_y); } } if interaction!= new_interaction { state.update(|state| state.interaction = new_interaction); } let value_or_bounds_have_changed = { let v = state.view(); v.x!= x || v.y!= y || v.min_x!= min_x || v.max_x!= max_x || v.min_y!= min_y || v.max_y!= max_y }; if value_or_bounds_have_changed { state.update(|state| { state.x = x; state.y = y; state.min_x = min_x; state.max_x = max_x; state.min_y = min_y; state.max_y = max_y; }) } // The backdrop **FramedRectangle** widget. let dim = rect.dim(); let color = new_interaction.color(style.color(ui.theme())); let frame = style.frame(ui.theme()); let frame_color = style.frame_color(ui.theme()); let rectangle_idx = state.view().rectangle_idx.get(&mut ui); FramedRectangle::new(dim) .middle_of(idx) .graphics_for(idx) .color(color) .frame(frame) .frame_color(frame_color) .set(rectangle_idx, &mut ui); // Label **Text** widget. let label_color = style.label_color(ui.theme()); if let Some(label) = maybe_label { let label_idx = state.view().label_idx.get(&mut ui); let label_font_size = style.label_font_size(ui.theme()); Text::new(label) .middle_of(rectangle_idx) .graphics_for(idx) .color(label_color) .font_size(label_font_size) .set(label_idx, &mut ui); } // Crosshair **Line** widgets. let (w, h) = inner_rect.w_h(); let half_w = w / 2.0; let half_h = h / 2.0; let v_line_x = map_range(new_x, min_x, max_x, -half_w, half_w); let h_line_y = map_range(new_y, min_y, max_y, -half_h, half_h); let thickness = style.line_thickness(ui.theme()); let line_color = label_color.with_alpha(1.0); let v_line_start = [0.0, -half_h]; let v_line_end = [0.0, half_h]; let v_line_idx = state.view().v_line_idx.get(&mut ui); Line::centred(v_line_start, v_line_end) .color(line_color) .thickness(thickness) .x_y_relative_to(idx, v_line_x, 0.0) .graphics_for(idx) .parent(idx) .set(v_line_idx, &mut ui); let h_line_start = [-half_w, 0.0]; let h_line_end = [half_w, 0.0]; let h_line_idx = state.view().h_line_idx.get(&mut ui); Line::centred(h_line_start, h_line_end) .color(line_color) .thickness(thickness) .x_y_relative_to(idx, 0.0, h_line_y) .graphics_for(idx) .parent(idx) .set(h_line_idx, &mut ui); // Crosshair value label **Text** widget. let x_string = val_to_string(new_x, max_x, max_x - min_x, rect.w() as usize); let y_string = val_to_string(new_y, max_y, max_y - min_y, rect.h() as usize); let value_string = format!("{}, {}", x_string, y_string); let cross_hair_xy = [inner_rect.x() + v_line_x, inner_rect.y() + h_line_y]; const VALUE_TEXT_PAD: f64 = 5.0; let x_direction = match inner_rect.x.closest_edge(cross_hair_xy[0]) { Edge::End => Direction::Backwards, Edge::Start => Direction::Forwards, }; let y_direction = match inner_rect.y.closest_edge(cross_hair_xy[1]) { Edge::End => Direction::Backwards, Edge::Start => Direction::Forwards, }; let value_font_size = style.value_font_size(ui.theme()); let value_label_idx = state.view().value_label_idx.get(&mut ui); Text::new(&value_string) .x_direction_from(v_line_idx, x_direction, VALUE_TEXT_PAD) .y_direction_from(h_line_idx, y_direction, VALUE_TEXT_PAD) .color(line_color) .graphics_for(idx) .parent(idx) .font_size(value_font_size) .set(value_label_idx, &mut ui); } } impl<'a, X, Y, F> Colorable for XYPad<'a, X, Y, F> { builder_method!(color { style.color = Some(Color) }); } impl<'a, X, Y, F> Frameable for XYPad<'a, X, Y, F> { builder_methods!{ frame { style.frame = Some(Scalar) } frame_color { style.frame_color = Some(Color) } } } impl<'a, X, Y, F> Labelable<'a> for XYPad<'a, X, Y, F> { builder_methods!{ label { maybe_label = Some(&'a str) } label_color { style.label_color = Some(Color) } label_font_size { style.label_font_size = Some(FontSize) } } }
init_state
identifier_name
xy_pad.rs
use { Backend, Color, Colorable, Frameable, FramedRectangle, FontSize, IndexSlot, Labelable, Line, Mouse, Positionable, Scalar, Sizeable, Text, Widget, }; use num::Float; use widget; use utils::{map_range, val_to_string}; /// Used for displaying and controlling a 2D point on a cartesian plane within a given range. /// /// Its reaction is triggered when the value is updated or if the mouse button is released while /// the cursor is above the rectangle. pub struct XYPad<'a, X, Y, F> { common: widget::CommonBuilder, x: X, min_x: X, max_x: X, y: Y, min_y: Y, max_y: Y, maybe_label: Option<&'a str>, /// The reaction function for the XYPad. /// /// It will be triggered when the value is updated or if the mouse button is released while the /// cursor is above the rectangle. pub maybe_react: Option<F>, style: Style, /// Indicates whether the XYPad will respond to user input. pub enabled: bool, } /// Unique kind for the widget type. pub const KIND: widget::Kind = "XYPad"; widget_style!{ KIND; /// Unique graphical styling for the XYPad. style Style { /// The color of the XYPad's rectangle. - color: Color { theme.shape_color } /// The width of the frame surrounding the rectangle. - frame: Scalar { theme.frame_width } /// The color of the surrounding rectangle frame. - frame_color: Color { theme.frame_color } /// The color of the XYPad's label and value label text. - label_color: Color { theme.label_color } /// The font size for the XYPad's label. - label_font_size: FontSize { theme.font_size_medium } /// The font size for the XYPad's *value* label. - value_font_size: FontSize { 14 } /// The thickness of the XYPad's crosshair lines. - line_thickness: Scalar { 2.0 } } } /// The state of the XYPad. #[derive(Clone, Debug, PartialEq)] pub struct State<X, Y> { x: X, min_x: X, max_x: X, y: Y, min_y: Y, max_y: Y, interaction: Interaction, rectangle_idx: IndexSlot, label_idx: IndexSlot, h_line_idx: IndexSlot, v_line_idx: IndexSlot, value_label_idx: IndexSlot, } /// The interaction state of the XYPad. #[derive(Debug, PartialEq, Clone, Copy)] pub enum Interaction { Normal, Highlighted, Clicked, } impl Interaction { /// The color associated with the current state. fn color(&self, color: Color) -> Color { match *self { Interaction::Normal => color, Interaction::Highlighted => color.highlighted(), Interaction::Clicked => color.clicked(), } } } /// Check the current state of the button. fn get_new_interaction(is_over: bool, prev: Interaction, mouse: Mouse) -> Interaction { use mouse::ButtonPosition::{Down, Up}; use self::Interaction::{Normal, Highlighted, Clicked}; match (is_over, prev, mouse.left.position) { (true, Normal, Down) => Normal, (true, _, Down) => Clicked, (true, _, Up) => Highlighted, (false, Clicked, Down) => Clicked, _ => Normal, } } impl<'a, X, Y, F> XYPad<'a, X, Y, F> { /// Build a new XYPad widget. pub fn new(x_val: X, min_x: X, max_x: X, y_val: Y, min_y: Y, max_y: Y) -> Self { XYPad { common: widget::CommonBuilder::new(), x: x_val, min_x: min_x, max_x: max_x, y: y_val, min_y: min_y, max_y: max_y, maybe_react: None, maybe_label: None, style: Style::new(), enabled: true, } } builder_methods!{ pub line_thickness { style.line_thickness = Some(Scalar) } pub value_font_size { style.value_font_size = Some(FontSize) } pub react { maybe_react = Some(F) } pub enabled { enabled = bool } } } impl<'a, X, Y, F> Widget for XYPad<'a, X, Y, F> where X: Float + ToString + ::std::fmt::Debug + ::std::any::Any, Y: Float + ToString + ::std::fmt::Debug + ::std::any::Any, F: FnOnce(X, Y), { type State = State<X, Y>; type Style = Style; fn common(&self) -> &widget::CommonBuilder { &self.common } fn common_mut(&mut self) -> &mut widget::CommonBuilder
fn unique_kind(&self) -> &'static str { KIND } fn init_state(&self) -> Self::State { State { interaction: Interaction::Normal, x: self.x, min_x: self.min_x, max_x: self.max_x, y: self.y, min_y: self.min_y, max_y: self.max_y, rectangle_idx: IndexSlot::new(), label_idx: IndexSlot::new(), h_line_idx: IndexSlot::new(), v_line_idx: IndexSlot::new(), value_label_idx: IndexSlot::new(), } } fn style(&self) -> Style { self.style.clone() } /// Update the XYPad's cached state. fn update<B: Backend>(self, args: widget::UpdateArgs<Self, B>) { use position::{Direction, Edge}; use self::Interaction::{Clicked, Highlighted, Normal}; let widget::UpdateArgs { idx, state, rect, style, mut ui,.. } = args; let XYPad { enabled, x, min_x, max_x, y, min_y, max_y, maybe_label, maybe_react, .. } = self; let maybe_mouse = ui.input(idx).maybe_mouse; let frame = style.frame(ui.theme()); let inner_rect = rect.pad(frame); let interaction = state.view().interaction; let new_interaction = match (enabled, maybe_mouse) { (false, _) | (true, None) => Normal, (true, Some(mouse)) => { let is_over_inner = inner_rect.is_over(mouse.xy); get_new_interaction(is_over_inner, interaction, mouse) }, }; // Capture the mouse if clicked, uncapture if released. match (interaction, new_interaction) { (Highlighted, Clicked) => { ui.capture_mouse(idx); }, (Clicked, Highlighted) | (Clicked, Normal) => { ui.uncapture_mouse(idx); }, _ => (), } // Determine new values from the mouse position over the pad. let (new_x, new_y) = match (maybe_mouse, new_interaction) { (None, _) | (_, Normal) | (_, Highlighted) => (x, y), (Some(mouse), Clicked) => { let clamped_x = inner_rect.x.clamp_value(mouse.xy[0]); let clamped_y = inner_rect.y.clamp_value(mouse.xy[1]); let (l, r, b, t) = inner_rect.l_r_b_t(); let new_x = map_range(clamped_x, l, r, min_x, max_x); let new_y = map_range(clamped_y, b, t, min_y, max_y); (new_x, new_y) }, }; // React if value is changed or the pad is clicked/released. if let Some(react) = maybe_react { let should_react = x!= new_x || y!= new_y || (interaction == Highlighted && new_interaction == Clicked) || (interaction == Clicked && new_interaction == Highlighted); if should_react { react(new_x, new_y); } } if interaction!= new_interaction { state.update(|state| state.interaction = new_interaction); } let value_or_bounds_have_changed = { let v = state.view(); v.x!= x || v.y!= y || v.min_x!= min_x || v.max_x!= max_x || v.min_y!= min_y || v.max_y!= max_y }; if value_or_bounds_have_changed { state.update(|state| { state.x = x; state.y = y; state.min_x = min_x; state.max_x = max_x; state.min_y = min_y; state.max_y = max_y; }) } // The backdrop **FramedRectangle** widget. let dim = rect.dim(); let color = new_interaction.color(style.color(ui.theme())); let frame = style.frame(ui.theme()); let frame_color = style.frame_color(ui.theme()); let rectangle_idx = state.view().rectangle_idx.get(&mut ui); FramedRectangle::new(dim) .middle_of(idx) .graphics_for(idx) .color(color) .frame(frame) .frame_color(frame_color) .set(rectangle_idx, &mut ui); // Label **Text** widget. let label_color = style.label_color(ui.theme()); if let Some(label) = maybe_label { let label_idx = state.view().label_idx.get(&mut ui); let label_font_size = style.label_font_size(ui.theme()); Text::new(label) .middle_of(rectangle_idx) .graphics_for(idx) .color(label_color) .font_size(label_font_size) .set(label_idx, &mut ui); } // Crosshair **Line** widgets. let (w, h) = inner_rect.w_h(); let half_w = w / 2.0; let half_h = h / 2.0; let v_line_x = map_range(new_x, min_x, max_x, -half_w, half_w); let h_line_y = map_range(new_y, min_y, max_y, -half_h, half_h); let thickness = style.line_thickness(ui.theme()); let line_color = label_color.with_alpha(1.0); let v_line_start = [0.0, -half_h]; let v_line_end = [0.0, half_h]; let v_line_idx = state.view().v_line_idx.get(&mut ui); Line::centred(v_line_start, v_line_end) .color(line_color) .thickness(thickness) .x_y_relative_to(idx, v_line_x, 0.0) .graphics_for(idx) .parent(idx) .set(v_line_idx, &mut ui); let h_line_start = [-half_w, 0.0]; let h_line_end = [half_w, 0.0]; let h_line_idx = state.view().h_line_idx.get(&mut ui); Line::centred(h_line_start, h_line_end) .color(line_color) .thickness(thickness) .x_y_relative_to(idx, 0.0, h_line_y) .graphics_for(idx) .parent(idx) .set(h_line_idx, &mut ui); // Crosshair value label **Text** widget. let x_string = val_to_string(new_x, max_x, max_x - min_x, rect.w() as usize); let y_string = val_to_string(new_y, max_y, max_y - min_y, rect.h() as usize); let value_string = format!("{}, {}", x_string, y_string); let cross_hair_xy = [inner_rect.x() + v_line_x, inner_rect.y() + h_line_y]; const VALUE_TEXT_PAD: f64 = 5.0; let x_direction = match inner_rect.x.closest_edge(cross_hair_xy[0]) { Edge::End => Direction::Backwards, Edge::Start => Direction::Forwards, }; let y_direction = match inner_rect.y.closest_edge(cross_hair_xy[1]) { Edge::End => Direction::Backwards, Edge::Start => Direction::Forwards, }; let value_font_size = style.value_font_size(ui.theme()); let value_label_idx = state.view().value_label_idx.get(&mut ui); Text::new(&value_string) .x_direction_from(v_line_idx, x_direction, VALUE_TEXT_PAD) .y_direction_from(h_line_idx, y_direction, VALUE_TEXT_PAD) .color(line_color) .graphics_for(idx) .parent(idx) .font_size(value_font_size) .set(value_label_idx, &mut ui); } } impl<'a, X, Y, F> Colorable for XYPad<'a, X, Y, F> { builder_method!(color { style.color = Some(Color) }); } impl<'a, X, Y, F> Frameable for XYPad<'a, X, Y, F> { builder_methods!{ frame { style.frame = Some(Scalar) } frame_color { style.frame_color = Some(Color) } } } impl<'a, X, Y, F> Labelable<'a> for XYPad<'a, X, Y, F> { builder_methods!{ label { maybe_label = Some(&'a str) } label_color { style.label_color = Some(Color) } label_font_size { style.label_font_size = Some(FontSize) } } }
{ &mut self.common }
identifier_body
xy_pad.rs
use { Backend, Color, Colorable, Frameable, FramedRectangle, FontSize, IndexSlot, Labelable, Line, Mouse, Positionable, Scalar, Sizeable, Text, Widget, }; use num::Float; use widget; use utils::{map_range, val_to_string}; /// Used for displaying and controlling a 2D point on a cartesian plane within a given range. /// /// Its reaction is triggered when the value is updated or if the mouse button is released while /// the cursor is above the rectangle. pub struct XYPad<'a, X, Y, F> { common: widget::CommonBuilder, x: X, min_x: X, max_x: X, y: Y, min_y: Y, max_y: Y, maybe_label: Option<&'a str>, /// The reaction function for the XYPad. /// /// It will be triggered when the value is updated or if the mouse button is released while the /// cursor is above the rectangle. pub maybe_react: Option<F>, style: Style, /// Indicates whether the XYPad will respond to user input. pub enabled: bool, } /// Unique kind for the widget type. pub const KIND: widget::Kind = "XYPad"; widget_style!{ KIND; /// Unique graphical styling for the XYPad. style Style { /// The color of the XYPad's rectangle. - color: Color { theme.shape_color } /// The width of the frame surrounding the rectangle. - frame: Scalar { theme.frame_width } /// The color of the surrounding rectangle frame. - frame_color: Color { theme.frame_color } /// The color of the XYPad's label and value label text. - label_color: Color { theme.label_color } /// The font size for the XYPad's label. - label_font_size: FontSize { theme.font_size_medium } /// The font size for the XYPad's *value* label. - value_font_size: FontSize { 14 } /// The thickness of the XYPad's crosshair lines. - line_thickness: Scalar { 2.0 } } } /// The state of the XYPad. #[derive(Clone, Debug, PartialEq)] pub struct State<X, Y> { x: X, min_x: X, max_x: X, y: Y, min_y: Y, max_y: Y, interaction: Interaction, rectangle_idx: IndexSlot, label_idx: IndexSlot, h_line_idx: IndexSlot,
#[derive(Debug, PartialEq, Clone, Copy)] pub enum Interaction { Normal, Highlighted, Clicked, } impl Interaction { /// The color associated with the current state. fn color(&self, color: Color) -> Color { match *self { Interaction::Normal => color, Interaction::Highlighted => color.highlighted(), Interaction::Clicked => color.clicked(), } } } /// Check the current state of the button. fn get_new_interaction(is_over: bool, prev: Interaction, mouse: Mouse) -> Interaction { use mouse::ButtonPosition::{Down, Up}; use self::Interaction::{Normal, Highlighted, Clicked}; match (is_over, prev, mouse.left.position) { (true, Normal, Down) => Normal, (true, _, Down) => Clicked, (true, _, Up) => Highlighted, (false, Clicked, Down) => Clicked, _ => Normal, } } impl<'a, X, Y, F> XYPad<'a, X, Y, F> { /// Build a new XYPad widget. pub fn new(x_val: X, min_x: X, max_x: X, y_val: Y, min_y: Y, max_y: Y) -> Self { XYPad { common: widget::CommonBuilder::new(), x: x_val, min_x: min_x, max_x: max_x, y: y_val, min_y: min_y, max_y: max_y, maybe_react: None, maybe_label: None, style: Style::new(), enabled: true, } } builder_methods!{ pub line_thickness { style.line_thickness = Some(Scalar) } pub value_font_size { style.value_font_size = Some(FontSize) } pub react { maybe_react = Some(F) } pub enabled { enabled = bool } } } impl<'a, X, Y, F> Widget for XYPad<'a, X, Y, F> where X: Float + ToString + ::std::fmt::Debug + ::std::any::Any, Y: Float + ToString + ::std::fmt::Debug + ::std::any::Any, F: FnOnce(X, Y), { type State = State<X, Y>; type Style = Style; fn common(&self) -> &widget::CommonBuilder { &self.common } fn common_mut(&mut self) -> &mut widget::CommonBuilder { &mut self.common } fn unique_kind(&self) -> &'static str { KIND } fn init_state(&self) -> Self::State { State { interaction: Interaction::Normal, x: self.x, min_x: self.min_x, max_x: self.max_x, y: self.y, min_y: self.min_y, max_y: self.max_y, rectangle_idx: IndexSlot::new(), label_idx: IndexSlot::new(), h_line_idx: IndexSlot::new(), v_line_idx: IndexSlot::new(), value_label_idx: IndexSlot::new(), } } fn style(&self) -> Style { self.style.clone() } /// Update the XYPad's cached state. fn update<B: Backend>(self, args: widget::UpdateArgs<Self, B>) { use position::{Direction, Edge}; use self::Interaction::{Clicked, Highlighted, Normal}; let widget::UpdateArgs { idx, state, rect, style, mut ui,.. } = args; let XYPad { enabled, x, min_x, max_x, y, min_y, max_y, maybe_label, maybe_react, .. } = self; let maybe_mouse = ui.input(idx).maybe_mouse; let frame = style.frame(ui.theme()); let inner_rect = rect.pad(frame); let interaction = state.view().interaction; let new_interaction = match (enabled, maybe_mouse) { (false, _) | (true, None) => Normal, (true, Some(mouse)) => { let is_over_inner = inner_rect.is_over(mouse.xy); get_new_interaction(is_over_inner, interaction, mouse) }, }; // Capture the mouse if clicked, uncapture if released. match (interaction, new_interaction) { (Highlighted, Clicked) => { ui.capture_mouse(idx); }, (Clicked, Highlighted) | (Clicked, Normal) => { ui.uncapture_mouse(idx); }, _ => (), } // Determine new values from the mouse position over the pad. let (new_x, new_y) = match (maybe_mouse, new_interaction) { (None, _) | (_, Normal) | (_, Highlighted) => (x, y), (Some(mouse), Clicked) => { let clamped_x = inner_rect.x.clamp_value(mouse.xy[0]); let clamped_y = inner_rect.y.clamp_value(mouse.xy[1]); let (l, r, b, t) = inner_rect.l_r_b_t(); let new_x = map_range(clamped_x, l, r, min_x, max_x); let new_y = map_range(clamped_y, b, t, min_y, max_y); (new_x, new_y) }, }; // React if value is changed or the pad is clicked/released. if let Some(react) = maybe_react { let should_react = x!= new_x || y!= new_y || (interaction == Highlighted && new_interaction == Clicked) || (interaction == Clicked && new_interaction == Highlighted); if should_react { react(new_x, new_y); } } if interaction!= new_interaction { state.update(|state| state.interaction = new_interaction); } let value_or_bounds_have_changed = { let v = state.view(); v.x!= x || v.y!= y || v.min_x!= min_x || v.max_x!= max_x || v.min_y!= min_y || v.max_y!= max_y }; if value_or_bounds_have_changed { state.update(|state| { state.x = x; state.y = y; state.min_x = min_x; state.max_x = max_x; state.min_y = min_y; state.max_y = max_y; }) } // The backdrop **FramedRectangle** widget. let dim = rect.dim(); let color = new_interaction.color(style.color(ui.theme())); let frame = style.frame(ui.theme()); let frame_color = style.frame_color(ui.theme()); let rectangle_idx = state.view().rectangle_idx.get(&mut ui); FramedRectangle::new(dim) .middle_of(idx) .graphics_for(idx) .color(color) .frame(frame) .frame_color(frame_color) .set(rectangle_idx, &mut ui); // Label **Text** widget. let label_color = style.label_color(ui.theme()); if let Some(label) = maybe_label { let label_idx = state.view().label_idx.get(&mut ui); let label_font_size = style.label_font_size(ui.theme()); Text::new(label) .middle_of(rectangle_idx) .graphics_for(idx) .color(label_color) .font_size(label_font_size) .set(label_idx, &mut ui); } // Crosshair **Line** widgets. let (w, h) = inner_rect.w_h(); let half_w = w / 2.0; let half_h = h / 2.0; let v_line_x = map_range(new_x, min_x, max_x, -half_w, half_w); let h_line_y = map_range(new_y, min_y, max_y, -half_h, half_h); let thickness = style.line_thickness(ui.theme()); let line_color = label_color.with_alpha(1.0); let v_line_start = [0.0, -half_h]; let v_line_end = [0.0, half_h]; let v_line_idx = state.view().v_line_idx.get(&mut ui); Line::centred(v_line_start, v_line_end) .color(line_color) .thickness(thickness) .x_y_relative_to(idx, v_line_x, 0.0) .graphics_for(idx) .parent(idx) .set(v_line_idx, &mut ui); let h_line_start = [-half_w, 0.0]; let h_line_end = [half_w, 0.0]; let h_line_idx = state.view().h_line_idx.get(&mut ui); Line::centred(h_line_start, h_line_end) .color(line_color) .thickness(thickness) .x_y_relative_to(idx, 0.0, h_line_y) .graphics_for(idx) .parent(idx) .set(h_line_idx, &mut ui); // Crosshair value label **Text** widget. let x_string = val_to_string(new_x, max_x, max_x - min_x, rect.w() as usize); let y_string = val_to_string(new_y, max_y, max_y - min_y, rect.h() as usize); let value_string = format!("{}, {}", x_string, y_string); let cross_hair_xy = [inner_rect.x() + v_line_x, inner_rect.y() + h_line_y]; const VALUE_TEXT_PAD: f64 = 5.0; let x_direction = match inner_rect.x.closest_edge(cross_hair_xy[0]) { Edge::End => Direction::Backwards, Edge::Start => Direction::Forwards, }; let y_direction = match inner_rect.y.closest_edge(cross_hair_xy[1]) { Edge::End => Direction::Backwards, Edge::Start => Direction::Forwards, }; let value_font_size = style.value_font_size(ui.theme()); let value_label_idx = state.view().value_label_idx.get(&mut ui); Text::new(&value_string) .x_direction_from(v_line_idx, x_direction, VALUE_TEXT_PAD) .y_direction_from(h_line_idx, y_direction, VALUE_TEXT_PAD) .color(line_color) .graphics_for(idx) .parent(idx) .font_size(value_font_size) .set(value_label_idx, &mut ui); } } impl<'a, X, Y, F> Colorable for XYPad<'a, X, Y, F> { builder_method!(color { style.color = Some(Color) }); } impl<'a, X, Y, F> Frameable for XYPad<'a, X, Y, F> { builder_methods!{ frame { style.frame = Some(Scalar) } frame_color { style.frame_color = Some(Color) } } } impl<'a, X, Y, F> Labelable<'a> for XYPad<'a, X, Y, F> { builder_methods!{ label { maybe_label = Some(&'a str) } label_color { style.label_color = Some(Color) } label_font_size { style.label_font_size = Some(FontSize) } } }
v_line_idx: IndexSlot, value_label_idx: IndexSlot, } /// The interaction state of the XYPad.
random_line_split
TestRemainder.rs
/* * Copyright (C) 2016 The Android Open Source Project * * 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
* limitations under the License. */ // Don't edit this file! It is auto-generated by frameworks/rs/api/generate.sh. #pragma version(1) #pragma rs java_package_name(android.renderscript.cts) rs_allocation gAllocInDenominator; float __attribute__((kernel)) testRemainderFloatFloatFloat(float inNumerator, unsigned int x) { float inDenominator = rsGetElementAt_float(gAllocInDenominator, x); return remainder(inNumerator, inDenominator); } float2 __attribute__((kernel)) testRemainderFloat2Float2Float2(float2 inNumerator, unsigned int x) { float2 inDenominator = rsGetElementAt_float2(gAllocInDenominator, x); return remainder(inNumerator, inDenominator); } float3 __attribute__((kernel)) testRemainderFloat3Float3Float3(float3 inNumerator, unsigned int x) { float3 inDenominator = rsGetElementAt_float3(gAllocInDenominator, x); return remainder(inNumerator, inDenominator); } float4 __attribute__((kernel)) testRemainderFloat4Float4Float4(float4 inNumerator, unsigned int x) { float4 inDenominator = rsGetElementAt_float4(gAllocInDenominator, x); return remainder(inNumerator, inDenominator); } half __attribute__((kernel)) testRemainderHalfHalfHalf(half inNumerator, unsigned int x) { half inDenominator = rsGetElementAt_half(gAllocInDenominator, x); return remainder(inNumerator, inDenominator); } half2 __attribute__((kernel)) testRemainderHalf2Half2Half2(half2 inNumerator, unsigned int x) { half2 inDenominator = rsGetElementAt_half2(gAllocInDenominator, x); return remainder(inNumerator, inDenominator); } half3 __attribute__((kernel)) testRemainderHalf3Half3Half3(half3 inNumerator, unsigned int x) { half3 inDenominator = rsGetElementAt_half3(gAllocInDenominator, x); return remainder(inNumerator, inDenominator); } half4 __attribute__((kernel)) testRemainderHalf4Half4Half4(half4 inNumerator, unsigned int x) { half4 inDenominator = rsGetElementAt_half4(gAllocInDenominator, x); return remainder(inNumerator, inDenominator); }
* 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
random_line_split
test.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. extern crate testcrate; use std::mem; extern { fn give_back(tu: testcrate::TestUnion) -> u64; } fn
() { let magic: u64 = 0xDEADBEEF; // Let's test calling it cross crate let back = unsafe { testcrate::give_back(mem::transmute(magic)) }; assert_eq!(magic, back); // And just within this crate let back = unsafe { give_back(mem::transmute(magic)) }; assert_eq!(magic, back); }
main
identifier_name
test.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. extern crate testcrate; use std::mem; extern { fn give_back(tu: testcrate::TestUnion) -> u64; } fn main() { let magic: u64 = 0xDEADBEEF; // Let's test calling it cross crate let back = unsafe { testcrate::give_back(mem::transmute(magic)) }; assert_eq!(magic, back); // And just within this crate let back = unsafe { give_back(mem::transmute(magic)) }; assert_eq!(magic, back); }
random_line_split
test.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. extern crate testcrate; use std::mem; extern { fn give_back(tu: testcrate::TestUnion) -> u64; } fn main()
{ let magic: u64 = 0xDEADBEEF; // Let's test calling it cross crate let back = unsafe { testcrate::give_back(mem::transmute(magic)) }; assert_eq!(magic, back); // And just within this crate let back = unsafe { give_back(mem::transmute(magic)) }; assert_eq!(magic, back); }
identifier_body
configuration.rs
use clingo::*; use std::env; fn print_prefix(depth: u8) { println!(); for _ in 0..depth { print!(" "); } } // recursively print the configuartion object fn print_configuration(conf: &Configuration, key: Id, depth: u8)
// print array offset (with prefix for readability) let subkey = conf .array_at(key, i) .expect("Failed to retrieve statistics array."); print_prefix(depth); print!("{}:", i); // recursively print subentry print_configuration(conf, subkey, depth + 1); } } // print maps ConfigurationType::MAP => { // loop over map elements let size = conf.map_size(key).unwrap(); for i in 0..size { // get and print map name (with prefix for readability) let name = conf.map_subkey_name(key, i).unwrap(); let subkey = conf.map_at(key, name).unwrap(); print_prefix(depth); print!("{}:", name); // recursively print subentry print_configuration(conf, subkey, depth + 1); } } // this case won't occur if the configuration are traversed like this _ => { let bla = conf.value_get(key).unwrap(); print!(" {}", bla); // println!("Unknown ConfigurationType"); } } } fn print_model(model: &Model) { // retrieve the symbols in the model let atoms = model .symbols(ShowType::SHOWN) .expect("Failed to retrieve symbols in the model."); print!("Model:"); for atom in atoms { // retrieve and print the symbol's string print!(" {}", atom.to_string().unwrap()); } println!(); } fn solve(ctl: &mut Control) { // get a solve handle let mut handle = ctl .solve(SolveMode::YIELD, &[]) .expect("Failed retrieving solve handle."); // loop over all models loop { handle.resume().expect("Failed resume on solve handle."); match handle.model() { // print the model Ok(Some(model)) => print_model(model), // stop if there are no more models Ok(None) => break, Err(e) => panic!("Error: {}", e), } } // close the solve handle handle .get() .expect("Failed to get result from solve handle."); handle.close().expect("Failed to close solve handle."); } fn main() { // collect clingo options from the command line let options = env::args().skip(1).collect(); // create a control object and pass command line arguments let mut ctl = Control::new(options).expect("Failed creating Control."); { // get the configuration object and its root key let conf = ctl.configuration_mut().unwrap(); let root_key = conf.root().unwrap(); print_configuration(conf, root_key, 0); let mut sub_key; // configure to enumerate all models sub_key = conf.map_at(root_key, "solve.models").unwrap(); conf.value_set(sub_key, "0") .expect("Failed to set solve.models to 0."); // configure the first solver to use the berkmin heuristic sub_key = conf.map_at(root_key, "solver").unwrap(); sub_key = conf.array_at(sub_key, 0).unwrap(); sub_key = conf.map_at(sub_key, "heuristic").unwrap(); conf.value_set(sub_key, "berkmin") .expect("Failed to set heuristic to berkmin."); } // note that the solver entry can be used both as an array and a map // if used as a map, this simply sets the configuration of the first solver and // is equivalent to the code above // add a logic program to the base part ctl.add("base", &[], "a :- not b. b :- not a.") .expect("Failed to add a logic program."); // ground the base part let part = Part::new("base", &[]).unwrap(); let parts = vec![part]; ctl.ground(&parts) .expect("Failed to ground a logic program."); // solve solve(&mut ctl); }
{ // get the type of an entry and switch over its various values let configuration_type = conf.configuration_type(key).unwrap(); match configuration_type { // print values ConfigurationType::VALUE => { let value = conf .value_get(key) .expect("Failed to retrieve statistics value."); println!("{}", value); } // print arrays ConfigurationType::ARRAY => { // loop over array elements let size = conf .array_size(key) .expect("Failed to retrieve statistics array size."); for i in 0..size {
identifier_body
configuration.rs
use clingo::*; use std::env; fn print_prefix(depth: u8) { println!(); for _ in 0..depth { print!(" "); } } // recursively print the configuartion object fn print_configuration(conf: &Configuration, key: Id, depth: u8) { // get the type of an entry and switch over its various values let configuration_type = conf.configuration_type(key).unwrap(); match configuration_type { // print values ConfigurationType::VALUE => { let value = conf .value_get(key) .expect("Failed to retrieve statistics value."); println!("{}", value); } // print arrays ConfigurationType::ARRAY => { // loop over array elements let size = conf .array_size(key) .expect("Failed to retrieve statistics array size."); for i in 0..size { // print array offset (with prefix for readability) let subkey = conf .array_at(key, i) .expect("Failed to retrieve statistics array."); print_prefix(depth); print!("{}:", i); // recursively print subentry print_configuration(conf, subkey, depth + 1); } } // print maps ConfigurationType::MAP => { // loop over map elements let size = conf.map_size(key).unwrap(); for i in 0..size { // get and print map name (with prefix for readability) let name = conf.map_subkey_name(key, i).unwrap(); let subkey = conf.map_at(key, name).unwrap(); print_prefix(depth); print!("{}:", name); // recursively print subentry print_configuration(conf, subkey, depth + 1); } } // this case won't occur if the configuration are traversed like this _ => { let bla = conf.value_get(key).unwrap(); print!(" {}", bla); // println!("Unknown ConfigurationType"); } } } fn print_model(model: &Model) { // retrieve the symbols in the model let atoms = model .symbols(ShowType::SHOWN) .expect("Failed to retrieve symbols in the model."); print!("Model:"); for atom in atoms { // retrieve and print the symbol's string print!(" {}", atom.to_string().unwrap()); } println!(); } fn solve(ctl: &mut Control) { // get a solve handle let mut handle = ctl .solve(SolveMode::YIELD, &[]) .expect("Failed retrieving solve handle."); // loop over all models loop { handle.resume().expect("Failed resume on solve handle."); match handle.model() { // print the model Ok(Some(model)) => print_model(model), // stop if there are no more models Ok(None) => break, Err(e) => panic!("Error: {}", e), } } // close the solve handle handle .get() .expect("Failed to get result from solve handle."); handle.close().expect("Failed to close solve handle."); } fn main() { // collect clingo options from the command line let options = env::args().skip(1).collect(); // create a control object and pass command line arguments let mut ctl = Control::new(options).expect("Failed creating Control."); { // get the configuration object and its root key let conf = ctl.configuration_mut().unwrap(); let root_key = conf.root().unwrap(); print_configuration(conf, root_key, 0); let mut sub_key; // configure to enumerate all models sub_key = conf.map_at(root_key, "solve.models").unwrap(); conf.value_set(sub_key, "0") .expect("Failed to set solve.models to 0."); // configure the first solver to use the berkmin heuristic sub_key = conf.map_at(root_key, "solver").unwrap(); sub_key = conf.array_at(sub_key, 0).unwrap(); sub_key = conf.map_at(sub_key, "heuristic").unwrap(); conf.value_set(sub_key, "berkmin") .expect("Failed to set heuristic to berkmin."); } // note that the solver entry can be used both as an array and a map // if used as a map, this simply sets the configuration of the first solver and // is equivalent to the code above // add a logic program to the base part ctl.add("base", &[], "a :- not b. b :- not a.") .expect("Failed to add a logic program.");
.expect("Failed to ground a logic program."); // solve solve(&mut ctl); }
// ground the base part let part = Part::new("base", &[]).unwrap(); let parts = vec![part]; ctl.ground(&parts)
random_line_split
configuration.rs
use clingo::*; use std::env; fn print_prefix(depth: u8) { println!(); for _ in 0..depth { print!(" "); } } // recursively print the configuartion object fn print_configuration(conf: &Configuration, key: Id, depth: u8) { // get the type of an entry and switch over its various values let configuration_type = conf.configuration_type(key).unwrap(); match configuration_type { // print values ConfigurationType::VALUE => { let value = conf .value_get(key) .expect("Failed to retrieve statistics value."); println!("{}", value); } // print arrays ConfigurationType::ARRAY => { // loop over array elements let size = conf .array_size(key) .expect("Failed to retrieve statistics array size."); for i in 0..size { // print array offset (with prefix for readability) let subkey = conf .array_at(key, i) .expect("Failed to retrieve statistics array."); print_prefix(depth); print!("{}:", i); // recursively print subentry print_configuration(conf, subkey, depth + 1); } } // print maps ConfigurationType::MAP => { // loop over map elements let size = conf.map_size(key).unwrap(); for i in 0..size { // get and print map name (with prefix for readability) let name = conf.map_subkey_name(key, i).unwrap(); let subkey = conf.map_at(key, name).unwrap(); print_prefix(depth); print!("{}:", name); // recursively print subentry print_configuration(conf, subkey, depth + 1); } } // this case won't occur if the configuration are traversed like this _ => { let bla = conf.value_get(key).unwrap(); print!(" {}", bla); // println!("Unknown ConfigurationType"); } } } fn print_model(model: &Model) { // retrieve the symbols in the model let atoms = model .symbols(ShowType::SHOWN) .expect("Failed to retrieve symbols in the model."); print!("Model:"); for atom in atoms { // retrieve and print the symbol's string print!(" {}", atom.to_string().unwrap()); } println!(); } fn
(ctl: &mut Control) { // get a solve handle let mut handle = ctl .solve(SolveMode::YIELD, &[]) .expect("Failed retrieving solve handle."); // loop over all models loop { handle.resume().expect("Failed resume on solve handle."); match handle.model() { // print the model Ok(Some(model)) => print_model(model), // stop if there are no more models Ok(None) => break, Err(e) => panic!("Error: {}", e), } } // close the solve handle handle .get() .expect("Failed to get result from solve handle."); handle.close().expect("Failed to close solve handle."); } fn main() { // collect clingo options from the command line let options = env::args().skip(1).collect(); // create a control object and pass command line arguments let mut ctl = Control::new(options).expect("Failed creating Control."); { // get the configuration object and its root key let conf = ctl.configuration_mut().unwrap(); let root_key = conf.root().unwrap(); print_configuration(conf, root_key, 0); let mut sub_key; // configure to enumerate all models sub_key = conf.map_at(root_key, "solve.models").unwrap(); conf.value_set(sub_key, "0") .expect("Failed to set solve.models to 0."); // configure the first solver to use the berkmin heuristic sub_key = conf.map_at(root_key, "solver").unwrap(); sub_key = conf.array_at(sub_key, 0).unwrap(); sub_key = conf.map_at(sub_key, "heuristic").unwrap(); conf.value_set(sub_key, "berkmin") .expect("Failed to set heuristic to berkmin."); } // note that the solver entry can be used both as an array and a map // if used as a map, this simply sets the configuration of the first solver and // is equivalent to the code above // add a logic program to the base part ctl.add("base", &[], "a :- not b. b :- not a.") .expect("Failed to add a logic program."); // ground the base part let part = Part::new("base", &[]).unwrap(); let parts = vec![part]; ctl.ground(&parts) .expect("Failed to ground a logic program."); // solve solve(&mut ctl); }
solve
identifier_name
text.rs
impl specs::Component for FixedCamera { type Storage = specs::NullStorage<Self>; } pub struct FixedCameraText { pub string: String, } impl specs::Component for FixedCameraText { type Storage = specs::VecStorage<Self>; } impl FixedCameraText { pub fn new(s: String) -> Self { FixedCameraText { string: s, } } } pub struct Text { pub string: String, pub x: f32, pub y: f32, pub scale: f32, } impl specs::Component for Text { type Storage = specs::VecStorage<Self>; } impl Text { pub fn new(x: f32, y: f32, scale: f32, text: String) -> Self { Text { string: text, scale: scale, x: x, y: y, } } }
use specs; #[derive(Clone,Default)] pub struct FixedCamera;
random_line_split
text.rs
use specs; #[derive(Clone,Default)] pub struct FixedCamera; impl specs::Component for FixedCamera { type Storage = specs::NullStorage<Self>; } pub struct FixedCameraText { pub string: String, } impl specs::Component for FixedCameraText { type Storage = specs::VecStorage<Self>; } impl FixedCameraText { pub fn
(s: String) -> Self { FixedCameraText { string: s, } } } pub struct Text { pub string: String, pub x: f32, pub y: f32, pub scale: f32, } impl specs::Component for Text { type Storage = specs::VecStorage<Self>; } impl Text { pub fn new(x: f32, y: f32, scale: f32, text: String) -> Self { Text { string: text, scale: scale, x: x, y: y, } } }
new
identifier_name
trade.rs
use types::deserialize::*; use std::fmt; use std::cmp::{Ord, Ordering}; #[derive(Debug, PartialEq, Serialize, Clone, Copy)] pub enum TradeApi { BTC, LTC, ETH, ETC, } impl fmt::Display for TradeApi { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { match self { &TradeApi::BTC => write!(f, "btc_usd"), &TradeApi::LTC => write!(f, "ltc_usd"), &TradeApi::ETC => write!(f, "etc_usd"), &TradeApi::ETH => write!(f, "eth_usd"), } } } impl<T> From<T> for TradeApi where T: Into<String>{ fn from(val: T) -> Self { let x = val.into(); match x.as_ref() { "BTC" => TradeApi::BTC, "ETH" => TradeApi::ETH, "ETC" => TradeApi::ETC, "LTC" => TradeApi::LTC, _ => TradeApi::BTC, } } } #[derive(PartialEq, Deserialize, Debug, Serialize)] pub enum TradeType { #[serde(rename = "ask")] Ask, #[serde(rename = "bid")] Bid, #[serde(rename = "sell")] Sell, #[serde(rename = "buy")] Buy, #[serde(rename = "sell_market")] MarketSell, #[serde(rename = "buy_market")] MarketBuy, } impl fmt::Display for TradeType { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { match self { &TradeType::Ask => write!(f, "ask"), &TradeType::Bid => write!(f, "bid"), &TradeType::Sell => write!(f, "sell"), &TradeType::Buy => write!(f, "buy"), &TradeType::MarketBuy => write!(f, "buy_market"), &TradeType::MarketSell => write!(f, "sell_market"), } } } impl<T> From<T> for TradeType where T: Into<String>{ fn from(val: T) -> Self { let x = val.into(); match x.as_ref() { "ask" => TradeType::Ask, "bid" => TradeType::Bid, "sell" => TradeType::Sell, "buy" => TradeType::Buy, "buy_market" => TradeType::MarketBuy, "sell_market" => TradeType::MarketSell, _ => TradeType::Buy, } } } #[derive(Deserialize, Debug, Serialize)] pub struct Trade { pub date: u64, pub date_ms: u64, #[serde(deserialize_with = "string_to_f64")] pub price: f64, #[serde(deserialize_with = "string_to_f64")] pub amount: f64, pub tid: u64, #[serde(rename = "type")] pub trade_type: TradeType, } impl PartialEq for Trade { fn eq(&self, other: &Trade) -> bool { self.tid == other.tid } } impl Ord for Trade {
fn cmp(&self, other: &Trade) -> Ordering { self.tid.cmp(&other.tid) } } impl PartialOrd for Trade { fn partial_cmp(&self, other: &Trade) -> Option<Ordering> { Some(self.tid.cmp(&other.tid)) } } impl Eq for Trade {} #[derive(Deserialize, Debug, Serialize)] pub struct TradeResponse { order_id: u64, result: bool, }
random_line_split
trade.rs
use types::deserialize::*; use std::fmt; use std::cmp::{Ord, Ordering}; #[derive(Debug, PartialEq, Serialize, Clone, Copy)] pub enum TradeApi { BTC, LTC, ETH, ETC, } impl fmt::Display for TradeApi { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { match self { &TradeApi::BTC => write!(f, "btc_usd"), &TradeApi::LTC => write!(f, "ltc_usd"), &TradeApi::ETC => write!(f, "etc_usd"), &TradeApi::ETH => write!(f, "eth_usd"), } } } impl<T> From<T> for TradeApi where T: Into<String>{ fn from(val: T) -> Self { let x = val.into(); match x.as_ref() { "BTC" => TradeApi::BTC, "ETH" => TradeApi::ETH, "ETC" => TradeApi::ETC, "LTC" => TradeApi::LTC, _ => TradeApi::BTC, } } } #[derive(PartialEq, Deserialize, Debug, Serialize)] pub enum TradeType { #[serde(rename = "ask")] Ask, #[serde(rename = "bid")] Bid, #[serde(rename = "sell")] Sell, #[serde(rename = "buy")] Buy, #[serde(rename = "sell_market")] MarketSell, #[serde(rename = "buy_market")] MarketBuy, } impl fmt::Display for TradeType { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { match self { &TradeType::Ask => write!(f, "ask"), &TradeType::Bid => write!(f, "bid"), &TradeType::Sell => write!(f, "sell"), &TradeType::Buy => write!(f, "buy"), &TradeType::MarketBuy => write!(f, "buy_market"), &TradeType::MarketSell => write!(f, "sell_market"), } } } impl<T> From<T> for TradeType where T: Into<String>{ fn from(val: T) -> Self { let x = val.into(); match x.as_ref() { "ask" => TradeType::Ask, "bid" => TradeType::Bid, "sell" => TradeType::Sell, "buy" => TradeType::Buy, "buy_market" => TradeType::MarketBuy, "sell_market" => TradeType::MarketSell, _ => TradeType::Buy, } } } #[derive(Deserialize, Debug, Serialize)] pub struct Trade { pub date: u64, pub date_ms: u64, #[serde(deserialize_with = "string_to_f64")] pub price: f64, #[serde(deserialize_with = "string_to_f64")] pub amount: f64, pub tid: u64, #[serde(rename = "type")] pub trade_type: TradeType, } impl PartialEq for Trade { fn eq(&self, other: &Trade) -> bool { self.tid == other.tid } } impl Ord for Trade { fn
(&self, other: &Trade) -> Ordering { self.tid.cmp(&other.tid) } } impl PartialOrd for Trade { fn partial_cmp(&self, other: &Trade) -> Option<Ordering> { Some(self.tid.cmp(&other.tid)) } } impl Eq for Trade {} #[derive(Deserialize, Debug, Serialize)] pub struct TradeResponse { order_id: u64, result: bool, }
cmp
identifier_name
var-captured-in-nested-closure.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. // xfail-win32: FIXME #10474 // xfail-android: FIXME(#10381) // compile-flags:-Z extra-debug-info // debugger:rbreak zzz // debugger:run // debugger:finish // debugger:print variable // check:$1 = 1 // debugger:print constant // check:$2 = 2 // debugger:print a_struct // check:$3 = {a = -3, b = 4.5, c = 5} // debugger:print *struct_ref // check:$4 = {a = -3, b = 4.5, c = 5} // debugger:print *owned // check:$5 = 6 // debugger:print managed->val // check:$6 = 7 // debugger:print closure_local // check:$7 = 8 // debugger:continue // debugger:finish // debugger:print variable // check:$8 = 1 // debugger:print constant // check:$9 = 2 // debugger:print a_struct // check:$10 = {a = -3, b = 4.5, c = 5} // debugger:print *struct_ref // check:$11 = {a = -3, b = 4.5, c = 5} // debugger:print *owned // check:$12 = 6 // debugger:print managed->val // check:$13 = 7 // debugger:print closure_local // check:$14 = 8 // debugger:continue #[allow(unused_variable)]; struct Struct { a: int, b: f64, c: uint
fn main() { let mut variable = 1; let constant = 2; let a_struct = Struct { a: -3, b: 4.5, c: 5 }; let struct_ref = &a_struct; let owned = ~6; let managed = @7; let closure = || { let closure_local = 8; let nested_closure = || { zzz(); variable = constant + a_struct.a + struct_ref.a + *owned + *managed + closure_local; }; zzz(); nested_closure(); }; closure(); } fn zzz() {()}
}
random_line_split
var-captured-in-nested-closure.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. // xfail-win32: FIXME #10474 // xfail-android: FIXME(#10381) // compile-flags:-Z extra-debug-info // debugger:rbreak zzz // debugger:run // debugger:finish // debugger:print variable // check:$1 = 1 // debugger:print constant // check:$2 = 2 // debugger:print a_struct // check:$3 = {a = -3, b = 4.5, c = 5} // debugger:print *struct_ref // check:$4 = {a = -3, b = 4.5, c = 5} // debugger:print *owned // check:$5 = 6 // debugger:print managed->val // check:$6 = 7 // debugger:print closure_local // check:$7 = 8 // debugger:continue // debugger:finish // debugger:print variable // check:$8 = 1 // debugger:print constant // check:$9 = 2 // debugger:print a_struct // check:$10 = {a = -3, b = 4.5, c = 5} // debugger:print *struct_ref // check:$11 = {a = -3, b = 4.5, c = 5} // debugger:print *owned // check:$12 = 6 // debugger:print managed->val // check:$13 = 7 // debugger:print closure_local // check:$14 = 8 // debugger:continue #[allow(unused_variable)]; struct Struct { a: int, b: f64, c: uint } fn
() { let mut variable = 1; let constant = 2; let a_struct = Struct { a: -3, b: 4.5, c: 5 }; let struct_ref = &a_struct; let owned = ~6; let managed = @7; let closure = || { let closure_local = 8; let nested_closure = || { zzz(); variable = constant + a_struct.a + struct_ref.a + *owned + *managed + closure_local; }; zzz(); nested_closure(); }; closure(); } fn zzz() {()}
main
identifier_name
mod.rs
use std::path::Path; use std::process::{Command, Stdio}; use url::Url; use ::consts::*; pub mod errors; pub mod ipv4; pub mod md5sum; pub mod notify; pub mod url; use self::errors::*; use self::ipv4::IPv4; macro_rules! xE { ( $x:expr ) => { xE!($x,) }; ( $x:expr, $($k:ident => $v:expr),* ) => { xml::Element::new($x.into(), None, vec![ $( (stringify!($k).into(), None, $v.into()), )*]) } } macro_rules! rawCharPtr { ( $x:expr ) => {{ use std::ffi::CString; CString::new(format!("{}", $x)).unwrap().as_ptr() }} } macro_rules! cmd { ( $x:expr ) => {{ let vec = $x.split(" ").collect::<Vec<&str>>(); let (ref head, ref tail) = vec.split_first().unwrap(); Command::new(head).args(tail) }} } // Update /etc/hosts file on host side (where the entire programme // is running) to enable ssh login guest node just specifying its // hostname. pub fn
(path: Option<&Path>, ip: &IPv4, hostname: &str) -> Result<()> { let hosts_path: &str = match path { Some(v) => v.to_str().unwrap(), None => "/etc/hosts", }; // create autogenerated part if not exists. { let pat = format!("/# autogenerated by {}/{{:a;$!{{N;ba}};q;}};$ a\\\\n# \ autogenerated by {}\\n# >>>>\\n# <<<<\\n", PROGNAME.as_str(), PROGNAME.as_str()); let mut cmd = Command::new("sed"); cmd.args(&["-i", &pat, hosts_path]); info!("pat: {}", pat); info!("{:?}", cmd); if!cmd.status().expect("failed to execute sed on hosts file").success() { return Err("sed on hosts file returned non-zero".into()); } } // update entry. { let pat = format!("x;/^$/{{x;h;ba;}};/.*/{{x;H;}};:a;/^$/{{x;\ /# autogenerate/{{\ s/^\\(.*\\n\\){}[^\\n]*\\n\\(.*\\)$/\\1\\2/;\ s/^\\(.*\\n\\)\\(# <<<<.*\\)$/\\1{} {}\\n\\2/;\ }};p;d;h;}};d", ip.ip().as_str(), ip.ip().as_str(), hostname); let mut cmd = Command::new("sed"); cmd.args(&["-i", &pat, hosts_path]); info!("pat: {}", pat); info!("{:?}", cmd); if cmd.status().expect("failed to execute sed on hosts file").success() { Ok(()) } else { Err("sed on hosts file returned non-zero".into()) } } } pub fn download_file<'a>(remote_url: &Url, local_path: &Path) -> Result<()> { let option = if local_path.is_dir() { "-P" } else { "-O" }; match Command::new("wget") .args(&[remote_url.as_str(), option, local_path.to_str().unwrap()]) .stderr(Stdio::null()) .status() { Ok(status) if status.success() => Ok(()), Ok(status) => { Err(format!("`wget {} {} {}` failed [error: {}]", remote_url.as_str(), option, local_path.to_str().unwrap(), status.code().unwrap()) .into()) } Err(e) => Err(format!("failed to execute command wget: {}", e).into()), } } #[cfg(test)] mod tests { use difference::diff; use difference::Difference; use std::env; use std::fs; use std::fs::File; use std::io::prelude::*; use super::*; use ::consts::*; use ::util::ipv4::IPv4; #[test] fn test_update_etc_hosts() { let temp_file = env::temp_dir().join(".test_update_etc_hosts"); let mut f = File::create(&temp_file).expect("failed to create file"); let orig1 = "\ # The following lines are desirable for IPv4 capable hosts\n\ 127.0.0.1 localhost.localdomain localhost\n\ 127.0.0.1 localhost4.localdomain4 localhost4\n\ # The following lines are desirable for IPv6 capable hosts\n\ ::1 test\n\ ::1 localhost.localdomain localhost\n\ ::1 localhost6.localdomain6 localhost6\n\ \n\ 10.10.10.10 test1\n\ 20.20.20.20 test2"; macro_rules! inserted { ( $e:expr ) => {{ format!("\n\n# autogenerated by {}\n\ # >>>>\n{} {}\n# <<<<\n\n", PROGNAME.as_str(), $e.0.ip(), $e.1) }} } f.write(orig1.as_bytes()).expect("write into temp hosts file failed"); // pattern 1. { let ip1 = IPv4::from_cidr_notation("11.11.11.11/24").unwrap(); let entry1 = (&ip1, &"test11".to_string()); // "3" is just an arbitrary num. to show idempotence for _ in 0..3 { update_etc_hosts(Some(temp_file.as_path()), &entry1.0, &entry1.1) .expect("failed to update temp hosts file"); let mut f = File::open(&temp_file).expect("File open failed"); let mut buffer = Vec::new(); f.read_to_end(&mut buffer).expect("read_to_end failed"); let (_, changeset) = diff(&orig1, &String::from_utf8(buffer).unwrap(), ""); assert_eq!(changeset.len(), 2); match (&changeset[0], &changeset[1]) { (&Difference::Same(_), &Difference::Add(ref add)) => { assert_eq!(add, inserted!(&entry1).as_str()); } _ => { assert!(false); } } } } fs::remove_file(temp_file.as_path()).expect("failed to remove file"); } }
update_etc_hosts
identifier_name
mod.rs
use std::path::Path; use std::process::{Command, Stdio}; use url::Url; use ::consts::*; pub mod errors; pub mod ipv4; pub mod md5sum; pub mod notify; pub mod url; use self::errors::*; use self::ipv4::IPv4; macro_rules! xE { ( $x:expr ) => { xE!($x,) }; ( $x:expr, $($k:ident => $v:expr),* ) => { xml::Element::new($x.into(), None, vec![ $( (stringify!($k).into(), None, $v.into()), )*]) } } macro_rules! rawCharPtr { ( $x:expr ) => {{ use std::ffi::CString; CString::new(format!("{}", $x)).unwrap().as_ptr() }} } macro_rules! cmd { ( $x:expr ) => {{ let vec = $x.split(" ").collect::<Vec<&str>>(); let (ref head, ref tail) = vec.split_first().unwrap(); Command::new(head).args(tail) }} } // Update /etc/hosts file on host side (where the entire programme // is running) to enable ssh login guest node just specifying its // hostname. pub fn update_etc_hosts(path: Option<&Path>, ip: &IPv4, hostname: &str) -> Result<()> { let hosts_path: &str = match path { Some(v) => v.to_str().unwrap(), None => "/etc/hosts", }; // create autogenerated part if not exists. { let pat = format!("/# autogenerated by {}/{{:a;$!{{N;ba}};q;}};$ a\\\\n# \ autogenerated by {}\\n# >>>>\\n# <<<<\\n", PROGNAME.as_str(), PROGNAME.as_str()); let mut cmd = Command::new("sed"); cmd.args(&["-i", &pat, hosts_path]); info!("pat: {}", pat); info!("{:?}", cmd); if!cmd.status().expect("failed to execute sed on hosts file").success() { return Err("sed on hosts file returned non-zero".into()); } } // update entry. { let pat = format!("x;/^$/{{x;h;ba;}};/.*/{{x;H;}};:a;/^$/{{x;\ /# autogenerate/{{\ s/^\\(.*\\n\\){}[^\\n]*\\n\\(.*\\)$/\\1\\2/;\ s/^\\(.*\\n\\)\\(# <<<<.*\\)$/\\1{} {}\\n\\2/;\ }};p;d;h;}};d", ip.ip().as_str(), ip.ip().as_str(), hostname); let mut cmd = Command::new("sed"); cmd.args(&["-i", &pat, hosts_path]); info!("pat: {}", pat); info!("{:?}", cmd); if cmd.status().expect("failed to execute sed on hosts file").success() { Ok(()) } else { Err("sed on hosts file returned non-zero".into()) } } } pub fn download_file<'a>(remote_url: &Url, local_path: &Path) -> Result<()> { let option = if local_path.is_dir() { "-P" } else { "-O" }; match Command::new("wget") .args(&[remote_url.as_str(), option, local_path.to_str().unwrap()]) .stderr(Stdio::null()) .status() { Ok(status) if status.success() => Ok(()), Ok(status) => { Err(format!("`wget {} {} {}` failed [error: {}]", remote_url.as_str(), option, local_path.to_str().unwrap(), status.code().unwrap()) .into()) } Err(e) => Err(format!("failed to execute command wget: {}", e).into()), } } #[cfg(test)] mod tests { use difference::diff; use difference::Difference; use std::env; use std::fs; use std::fs::File; use std::io::prelude::*; use super::*; use ::consts::*; use ::util::ipv4::IPv4; #[test] fn test_update_etc_hosts()
f.write(orig1.as_bytes()).expect("write into temp hosts file failed"); // pattern 1. { let ip1 = IPv4::from_cidr_notation("11.11.11.11/24").unwrap(); let entry1 = (&ip1, &"test11".to_string()); // "3" is just an arbitrary num. to show idempotence for _ in 0..3 { update_etc_hosts(Some(temp_file.as_path()), &entry1.0, &entry1.1) .expect("failed to update temp hosts file"); let mut f = File::open(&temp_file).expect("File open failed"); let mut buffer = Vec::new(); f.read_to_end(&mut buffer).expect("read_to_end failed"); let (_, changeset) = diff(&orig1, &String::from_utf8(buffer).unwrap(), ""); assert_eq!(changeset.len(), 2); match (&changeset[0], &changeset[1]) { (&Difference::Same(_), &Difference::Add(ref add)) => { assert_eq!(add, inserted!(&entry1).as_str()); } _ => { assert!(false); } } } } fs::remove_file(temp_file.as_path()).expect("failed to remove file"); } }
{ let temp_file = env::temp_dir().join(".test_update_etc_hosts"); let mut f = File::create(&temp_file).expect("failed to create file"); let orig1 = "\ # The following lines are desirable for IPv4 capable hosts\n\ 127.0.0.1 localhost.localdomain localhost\n\ 127.0.0.1 localhost4.localdomain4 localhost4\n\ # The following lines are desirable for IPv6 capable hosts\n\ ::1 test\n\ ::1 localhost.localdomain localhost\n\ ::1 localhost6.localdomain6 localhost6\n\ \n\ 10.10.10.10 test1\n\ 20.20.20.20 test2"; macro_rules! inserted { ( $e:expr ) => {{ format!("\n\n# autogenerated by {}\n\ # >>>>\n{} {}\n# <<<<\n\n", PROGNAME.as_str(), $e.0.ip(), $e.1) }} }
identifier_body
mod.rs
use std::path::Path; use std::process::{Command, Stdio}; use url::Url; use ::consts::*; pub mod errors; pub mod ipv4; pub mod md5sum; pub mod notify; pub mod url; use self::errors::*; use self::ipv4::IPv4; macro_rules! xE { ( $x:expr ) => { xE!($x,) }; ( $x:expr, $($k:ident => $v:expr),* ) => { xml::Element::new($x.into(), None, vec![ $( (stringify!($k).into(), None, $v.into()), )*]) } } macro_rules! rawCharPtr { ( $x:expr ) => {{ use std::ffi::CString; CString::new(format!("{}", $x)).unwrap().as_ptr() }} } macro_rules! cmd { ( $x:expr ) => {{ let vec = $x.split(" ").collect::<Vec<&str>>(); let (ref head, ref tail) = vec.split_first().unwrap(); Command::new(head).args(tail) }} } // Update /etc/hosts file on host side (where the entire programme // is running) to enable ssh login guest node just specifying its // hostname. pub fn update_etc_hosts(path: Option<&Path>, ip: &IPv4, hostname: &str) -> Result<()> { let hosts_path: &str = match path { Some(v) => v.to_str().unwrap(), None => "/etc/hosts", }; // create autogenerated part if not exists. { let pat = format!("/# autogenerated by {}/{{:a;$!{{N;ba}};q;}};$ a\\\\n# \ autogenerated by {}\\n# >>>>\\n# <<<<\\n", PROGNAME.as_str(), PROGNAME.as_str()); let mut cmd = Command::new("sed"); cmd.args(&["-i", &pat, hosts_path]); info!("pat: {}", pat); info!("{:?}", cmd); if!cmd.status().expect("failed to execute sed on hosts file").success() { return Err("sed on hosts file returned non-zero".into()); } } // update entry. { let pat = format!("x;/^$/{{x;h;ba;}};/.*/{{x;H;}};:a;/^$/{{x;\ /# autogenerate/{{\ s/^\\(.*\\n\\){}[^\\n]*\\n\\(.*\\)$/\\1\\2/;\ s/^\\(.*\\n\\)\\(# <<<<.*\\)$/\\1{} {}\\n\\2/;\ }};p;d;h;}};d", ip.ip().as_str(), ip.ip().as_str(), hostname); let mut cmd = Command::new("sed"); cmd.args(&["-i", &pat, hosts_path]); info!("pat: {}", pat); info!("{:?}", cmd); if cmd.status().expect("failed to execute sed on hosts file").success() { Ok(()) } else { Err("sed on hosts file returned non-zero".into()) } } } pub fn download_file<'a>(remote_url: &Url, local_path: &Path) -> Result<()> { let option = if local_path.is_dir() { "-P" } else
; match Command::new("wget") .args(&[remote_url.as_str(), option, local_path.to_str().unwrap()]) .stderr(Stdio::null()) .status() { Ok(status) if status.success() => Ok(()), Ok(status) => { Err(format!("`wget {} {} {}` failed [error: {}]", remote_url.as_str(), option, local_path.to_str().unwrap(), status.code().unwrap()) .into()) } Err(e) => Err(format!("failed to execute command wget: {}", e).into()), } } #[cfg(test)] mod tests { use difference::diff; use difference::Difference; use std::env; use std::fs; use std::fs::File; use std::io::prelude::*; use super::*; use ::consts::*; use ::util::ipv4::IPv4; #[test] fn test_update_etc_hosts() { let temp_file = env::temp_dir().join(".test_update_etc_hosts"); let mut f = File::create(&temp_file).expect("failed to create file"); let orig1 = "\ # The following lines are desirable for IPv4 capable hosts\n\ 127.0.0.1 localhost.localdomain localhost\n\ 127.0.0.1 localhost4.localdomain4 localhost4\n\ # The following lines are desirable for IPv6 capable hosts\n\ ::1 test\n\ ::1 localhost.localdomain localhost\n\ ::1 localhost6.localdomain6 localhost6\n\ \n\ 10.10.10.10 test1\n\ 20.20.20.20 test2"; macro_rules! inserted { ( $e:expr ) => {{ format!("\n\n# autogenerated by {}\n\ # >>>>\n{} {}\n# <<<<\n\n", PROGNAME.as_str(), $e.0.ip(), $e.1) }} } f.write(orig1.as_bytes()).expect("write into temp hosts file failed"); // pattern 1. { let ip1 = IPv4::from_cidr_notation("11.11.11.11/24").unwrap(); let entry1 = (&ip1, &"test11".to_string()); // "3" is just an arbitrary num. to show idempotence for _ in 0..3 { update_etc_hosts(Some(temp_file.as_path()), &entry1.0, &entry1.1) .expect("failed to update temp hosts file"); let mut f = File::open(&temp_file).expect("File open failed"); let mut buffer = Vec::new(); f.read_to_end(&mut buffer).expect("read_to_end failed"); let (_, changeset) = diff(&orig1, &String::from_utf8(buffer).unwrap(), ""); assert_eq!(changeset.len(), 2); match (&changeset[0], &changeset[1]) { (&Difference::Same(_), &Difference::Add(ref add)) => { assert_eq!(add, inserted!(&entry1).as_str()); } _ => { assert!(false); } } } } fs::remove_file(temp_file.as_path()).expect("failed to remove file"); } }
{ "-O" }
conditional_block
mod.rs
use std::path::Path; use std::process::{Command, Stdio}; use url::Url; use ::consts::*; pub mod errors; pub mod ipv4; pub mod md5sum; pub mod notify; pub mod url; use self::errors::*; use self::ipv4::IPv4; macro_rules! xE { ( $x:expr ) => { xE!($x,) }; ( $x:expr, $($k:ident => $v:expr),* ) => { xml::Element::new($x.into(), None, vec![ $( (stringify!($k).into(), None, $v.into()), )*]) } } macro_rules! rawCharPtr { ( $x:expr ) => {{ use std::ffi::CString; CString::new(format!("{}", $x)).unwrap().as_ptr()
} macro_rules! cmd { ( $x:expr ) => {{ let vec = $x.split(" ").collect::<Vec<&str>>(); let (ref head, ref tail) = vec.split_first().unwrap(); Command::new(head).args(tail) }} } // Update /etc/hosts file on host side (where the entire programme // is running) to enable ssh login guest node just specifying its // hostname. pub fn update_etc_hosts(path: Option<&Path>, ip: &IPv4, hostname: &str) -> Result<()> { let hosts_path: &str = match path { Some(v) => v.to_str().unwrap(), None => "/etc/hosts", }; // create autogenerated part if not exists. { let pat = format!("/# autogenerated by {}/{{:a;$!{{N;ba}};q;}};$ a\\\\n# \ autogenerated by {}\\n# >>>>\\n# <<<<\\n", PROGNAME.as_str(), PROGNAME.as_str()); let mut cmd = Command::new("sed"); cmd.args(&["-i", &pat, hosts_path]); info!("pat: {}", pat); info!("{:?}", cmd); if!cmd.status().expect("failed to execute sed on hosts file").success() { return Err("sed on hosts file returned non-zero".into()); } } // update entry. { let pat = format!("x;/^$/{{x;h;ba;}};/.*/{{x;H;}};:a;/^$/{{x;\ /# autogenerate/{{\ s/^\\(.*\\n\\){}[^\\n]*\\n\\(.*\\)$/\\1\\2/;\ s/^\\(.*\\n\\)\\(# <<<<.*\\)$/\\1{} {}\\n\\2/;\ }};p;d;h;}};d", ip.ip().as_str(), ip.ip().as_str(), hostname); let mut cmd = Command::new("sed"); cmd.args(&["-i", &pat, hosts_path]); info!("pat: {}", pat); info!("{:?}", cmd); if cmd.status().expect("failed to execute sed on hosts file").success() { Ok(()) } else { Err("sed on hosts file returned non-zero".into()) } } } pub fn download_file<'a>(remote_url: &Url, local_path: &Path) -> Result<()> { let option = if local_path.is_dir() { "-P" } else { "-O" }; match Command::new("wget") .args(&[remote_url.as_str(), option, local_path.to_str().unwrap()]) .stderr(Stdio::null()) .status() { Ok(status) if status.success() => Ok(()), Ok(status) => { Err(format!("`wget {} {} {}` failed [error: {}]", remote_url.as_str(), option, local_path.to_str().unwrap(), status.code().unwrap()) .into()) } Err(e) => Err(format!("failed to execute command wget: {}", e).into()), } } #[cfg(test)] mod tests { use difference::diff; use difference::Difference; use std::env; use std::fs; use std::fs::File; use std::io::prelude::*; use super::*; use ::consts::*; use ::util::ipv4::IPv4; #[test] fn test_update_etc_hosts() { let temp_file = env::temp_dir().join(".test_update_etc_hosts"); let mut f = File::create(&temp_file).expect("failed to create file"); let orig1 = "\ # The following lines are desirable for IPv4 capable hosts\n\ 127.0.0.1 localhost.localdomain localhost\n\ 127.0.0.1 localhost4.localdomain4 localhost4\n\ # The following lines are desirable for IPv6 capable hosts\n\ ::1 test\n\ ::1 localhost.localdomain localhost\n\ ::1 localhost6.localdomain6 localhost6\n\ \n\ 10.10.10.10 test1\n\ 20.20.20.20 test2"; macro_rules! inserted { ( $e:expr ) => {{ format!("\n\n# autogenerated by {}\n\ # >>>>\n{} {}\n# <<<<\n\n", PROGNAME.as_str(), $e.0.ip(), $e.1) }} } f.write(orig1.as_bytes()).expect("write into temp hosts file failed"); // pattern 1. { let ip1 = IPv4::from_cidr_notation("11.11.11.11/24").unwrap(); let entry1 = (&ip1, &"test11".to_string()); // "3" is just an arbitrary num. to show idempotence for _ in 0..3 { update_etc_hosts(Some(temp_file.as_path()), &entry1.0, &entry1.1) .expect("failed to update temp hosts file"); let mut f = File::open(&temp_file).expect("File open failed"); let mut buffer = Vec::new(); f.read_to_end(&mut buffer).expect("read_to_end failed"); let (_, changeset) = diff(&orig1, &String::from_utf8(buffer).unwrap(), ""); assert_eq!(changeset.len(), 2); match (&changeset[0], &changeset[1]) { (&Difference::Same(_), &Difference::Add(ref add)) => { assert_eq!(add, inserted!(&entry1).as_str()); } _ => { assert!(false); } } } } fs::remove_file(temp_file.as_path()).expect("failed to remove file"); } }
}}
random_line_split
sync-rwlock-read-mode-shouldnt-escape.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
// error-pattern: cannot infer an appropriate lifetime extern mod extra; use extra::sync; fn main() { let x = ~sync::RWlock(); let mut y = None; do x.write_downgrade |write_mode| { y = Some(x.downgrade(write_mode)); } // Adding this line causes a method unification failure instead // do (&option::unwrap(y)).read { } }
// <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.
random_line_split
sync-rwlock-read-mode-shouldnt-escape.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. // error-pattern: cannot infer an appropriate lifetime extern mod extra; use extra::sync; fn
() { let x = ~sync::RWlock(); let mut y = None; do x.write_downgrade |write_mode| { y = Some(x.downgrade(write_mode)); } // Adding this line causes a method unification failure instead // do (&option::unwrap(y)).read { } }
main
identifier_name
sync-rwlock-read-mode-shouldnt-escape.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. // error-pattern: cannot infer an appropriate lifetime extern mod extra; use extra::sync; fn main()
{ let x = ~sync::RWlock(); let mut y = None; do x.write_downgrade |write_mode| { y = Some(x.downgrade(write_mode)); } // Adding this line causes a method unification failure instead // do (&option::unwrap(y)).read { } }
identifier_body
console.rs
// Copyright © 2018 Cormac O'Brien
// Software is furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all copies or // substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING // BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. use std::{cell::RefCell, rc::Rc}; use crate::common::console::Console; use failure::Error; use winit::event::{ElementState, Event, KeyboardInput, VirtualKeyCode as Key, WindowEvent}; pub struct ConsoleInput { console: Rc<RefCell<Console>>, } impl ConsoleInput { pub fn new(console: Rc<RefCell<Console>>) -> ConsoleInput { ConsoleInput { console } } pub fn handle_event<T>(&self, event: Event<T>) -> Result<(), Error> { match event { Event::WindowEvent { event,.. } => match event { WindowEvent::ReceivedCharacter(c) => self.console.borrow_mut().send_char(c), WindowEvent::KeyboardInput { input: KeyboardInput { virtual_keycode: Some(key), state: ElementState::Pressed, .. }, .. } => match key { Key::Up => self.console.borrow_mut().history_up(), Key::Down => self.console.borrow_mut().history_down(), Key::Left => self.console.borrow_mut().cursor_left(), Key::Right => self.console.borrow_mut().cursor_right(), Key::Grave => self.console.borrow_mut().stuff_text("toggleconsole\n"), _ => (), }, _ => (), }, _ => (), } Ok(()) } }
// // Permission is hereby granted, free of charge, to any person obtaining a copy of this software // and associated documentation files (the "Software"), to deal in the Software without // restriction, including without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the
random_line_split
console.rs
// Copyright © 2018 Cormac O'Brien // // Permission is hereby granted, free of charge, to any person obtaining a copy of this software // and associated documentation files (the "Software"), to deal in the Software without // restriction, including without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the // Software is furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all copies or // substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING // BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. use std::{cell::RefCell, rc::Rc}; use crate::common::console::Console; use failure::Error; use winit::event::{ElementState, Event, KeyboardInput, VirtualKeyCode as Key, WindowEvent}; pub struct ConsoleInput { console: Rc<RefCell<Console>>, } impl ConsoleInput { pub fn new(console: Rc<RefCell<Console>>) -> ConsoleInput { ConsoleInput { console } } pub fn handle_event<T>(&self, event: Event<T>) -> Result<(), Error> {
}, _ => (), }, _ => (), } Ok(()) } }
match event { Event::WindowEvent { event, .. } => match event { WindowEvent::ReceivedCharacter(c) => self.console.borrow_mut().send_char(c), WindowEvent::KeyboardInput { input: KeyboardInput { virtual_keycode: Some(key), state: ElementState::Pressed, .. }, .. } => match key { Key::Up => self.console.borrow_mut().history_up(), Key::Down => self.console.borrow_mut().history_down(), Key::Left => self.console.borrow_mut().cursor_left(), Key::Right => self.console.borrow_mut().cursor_right(), Key::Grave => self.console.borrow_mut().stuff_text("toggleconsole\n"), _ => (),
identifier_body
console.rs
// Copyright © 2018 Cormac O'Brien // // Permission is hereby granted, free of charge, to any person obtaining a copy of this software // and associated documentation files (the "Software"), to deal in the Software without // restriction, including without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the // Software is furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all copies or // substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING // BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. use std::{cell::RefCell, rc::Rc}; use crate::common::console::Console; use failure::Error; use winit::event::{ElementState, Event, KeyboardInput, VirtualKeyCode as Key, WindowEvent}; pub struct C
{ console: Rc<RefCell<Console>>, } impl ConsoleInput { pub fn new(console: Rc<RefCell<Console>>) -> ConsoleInput { ConsoleInput { console } } pub fn handle_event<T>(&self, event: Event<T>) -> Result<(), Error> { match event { Event::WindowEvent { event,.. } => match event { WindowEvent::ReceivedCharacter(c) => self.console.borrow_mut().send_char(c), WindowEvent::KeyboardInput { input: KeyboardInput { virtual_keycode: Some(key), state: ElementState::Pressed, .. }, .. } => match key { Key::Up => self.console.borrow_mut().history_up(), Key::Down => self.console.borrow_mut().history_down(), Key::Left => self.console.borrow_mut().cursor_left(), Key::Right => self.console.borrow_mut().cursor_right(), Key::Grave => self.console.borrow_mut().stuff_text("toggleconsole\n"), _ => (), }, _ => (), }, _ => (), } Ok(()) } }
onsoleInput
identifier_name
main.rs
#[macro_use] extern crate gfx; extern crate gfx_support; extern crate image; use std::io::Cursor; use std::time::Instant; use gfx::format::Rgba8; use gfx_support::{BackbufferView, ColorFormat}; use gfx::{Bundle, GraphicsPoolExt}; gfx_defines!{ vertex Vertex { pos: [f32; 2] = "a_Pos", uv: [f32; 2] = "a_Uv", } constant Locals { offsets: [f32; 2] = "u_Offsets", } pipeline pipe { vbuf: gfx::VertexBuffer<Vertex> = (), color: gfx::TextureSampler<[f32; 4]> = "t_Color", flow: gfx::TextureSampler<[f32; 4]> = "t_Flow", noise: gfx::TextureSampler<[f32; 4]> = "t_Noise", offset0: gfx::Global<f32> = "f_Offset0", offset1: gfx::Global<f32> = "f_Offset1", locals: gfx::ConstantBuffer<Locals> = "Locals", out: gfx::RenderTarget<ColorFormat> = "Target0", } } impl Vertex { fn new(p: [f32; 2], u: [f32; 2]) -> Vertex { Vertex { pos: p, uv: u, } } } fn load_texture<R, D>(device: &mut D, data: &[u8]) -> Result<gfx::handle::ShaderResourceView<R, [f32; 4]>, String> where R: gfx::Resources, D: gfx::Device<R> { use gfx::texture as t; let img = image::load(Cursor::new(data), image::PNG).unwrap().to_rgba(); let (width, height) = img.dimensions(); let kind = t::Kind::D2(width as t::Size, height as t::Size, t::AaMode::Single); let (_, view) = device.create_texture_immutable_u8::<Rgba8>(kind, &[&img]).unwrap(); Ok(view) } struct App<B: gfx::Backend> { views: Vec<BackbufferView<B::Resources>>, bundle: Bundle<B, pipe::Data<B::Resources>>, cycles: [f32; 2], time_start: Instant, } impl<B: gfx::Backend> gfx_support::Application<B> for App<B> { fn new(device: &mut B::Device, _: &mut gfx::queue::GraphicsQueue<B>, backend: gfx_support::shade::Backend, window_targets: gfx_support::WindowTargets<B::Resources>) -> Self
Vertex::new([ 1.0, -1.0], [1.0, 0.0]), Vertex::new([ 1.0, 1.0], [1.0, 1.0]), Vertex::new([-1.0, -1.0], [0.0, 0.0]), Vertex::new([ 1.0, 1.0], [1.0, 1.0]), Vertex::new([-1.0, 1.0], [0.0, 1.0]), ]; let (vbuf, slice) = device.create_vertex_buffer_with_slice(&vertex_data, ()); let water_texture = load_texture(device, &include_bytes!("image/water.png")[..]).unwrap(); let flow_texture = load_texture(device, &include_bytes!("image/flow.png")[..]).unwrap(); let noise_texture = load_texture(device, &include_bytes!("image/noise.png")[..]).unwrap(); let sampler = device.create_sampler_linear(); let pso = device.create_pipeline_simple( vs.select(backend).unwrap(), ps.select(backend).unwrap(), pipe::new() ).unwrap(); let data = pipe::Data { vbuf: vbuf, color: (water_texture, sampler.clone()), flow: (flow_texture, sampler.clone()), noise: (noise_texture, sampler.clone()), offset0: 0.0, offset1: 0.0, locals: device.create_constant_buffer(1), out: window_targets.views[0].0.clone(), }; App { views: window_targets.views, bundle: Bundle::new(slice, pso, data), cycles: [0.0, 0.5], time_start: Instant::now(), } } fn render(&mut self, (frame, sync): (gfx::Frame, &gfx_support::SyncPrimitives<B::Resources>), pool: &mut gfx::GraphicsCommandPool<B>, queue: &mut gfx::queue::GraphicsQueue<B>) { let delta = self.time_start.elapsed(); self.time_start = Instant::now(); let delta = delta.as_secs() as f32 + delta.subsec_nanos() as f32 / 1000_000_000.0; // since we sample our diffuse texture twice we need to lerp between // them to get a smooth transition (shouldn't even be noticeable). // They start half a cycle apart (0.5) and is later used to calculate // the interpolation amount via `2.0 * abs(cycle0 -.5f)` self.cycles[0] += 0.25 * delta; if self.cycles[0] > 1.0 { self.cycles[0] -= 1.0; } self.cycles[1] += 0.25 * delta; if self.cycles[1] > 1.0 { self.cycles[1] -= 1.0; } let (cur_color, _) = self.views[frame.id()].clone(); self.bundle.data.out = cur_color; let mut encoder = pool.acquire_graphics_encoder(); self.bundle.data.offset0 = self.cycles[0]; self.bundle.data.offset1 = self.cycles[1]; let locals = Locals { offsets: self.cycles }; encoder.update_constant_buffer(&self.bundle.data.locals, &locals); encoder.clear(&self.bundle.data.out, [0.3, 0.3, 0.3, 1.0]); self.bundle.encode(&mut encoder); encoder.synced_flush(queue, &[&sync.rendering], &[], Some(&sync.frame_fence)) .expect("Could not flush encoder"); } fn on_resize(&mut self, window_targets: gfx_support::WindowTargets<B::Resources>) { self.views = window_targets.views; } } pub fn main() { use gfx_support::Application; App::launch_simple("Flowmap example"); }
{ use gfx::traits::DeviceExt; let vs = gfx_support::shade::Source { glsl_120: include_bytes!("shader/flowmap_120.glslv"), glsl_150: include_bytes!("shader/flowmap_150.glslv"), hlsl_40: include_bytes!("data/vertex.fx"), msl_11: include_bytes!("shader/flowmap_vertex.metal"), .. gfx_support::shade::Source::empty() }; let ps = gfx_support::shade::Source { glsl_120: include_bytes!("shader/flowmap_120.glslf"), glsl_150: include_bytes!("shader/flowmap_150.glslf"), hlsl_40: include_bytes!("data/pixel.fx"), msl_11: include_bytes!("shader/flowmap_frag.metal"), .. gfx_support::shade::Source::empty() }; let vertex_data = [ Vertex::new([-1.0, -1.0], [0.0, 0.0]),
identifier_body
main.rs
#[macro_use] extern crate gfx; extern crate gfx_support; extern crate image; use std::io::Cursor; use std::time::Instant; use gfx::format::Rgba8; use gfx_support::{BackbufferView, ColorFormat}; use gfx::{Bundle, GraphicsPoolExt}; gfx_defines!{ vertex Vertex { pos: [f32; 2] = "a_Pos", uv: [f32; 2] = "a_Uv", } constant Locals { offsets: [f32; 2] = "u_Offsets", } pipeline pipe { vbuf: gfx::VertexBuffer<Vertex> = (), color: gfx::TextureSampler<[f32; 4]> = "t_Color", flow: gfx::TextureSampler<[f32; 4]> = "t_Flow", noise: gfx::TextureSampler<[f32; 4]> = "t_Noise", offset0: gfx::Global<f32> = "f_Offset0", offset1: gfx::Global<f32> = "f_Offset1", locals: gfx::ConstantBuffer<Locals> = "Locals", out: gfx::RenderTarget<ColorFormat> = "Target0", } } impl Vertex { fn new(p: [f32; 2], u: [f32; 2]) -> Vertex { Vertex { pos: p, uv: u, } } } fn load_texture<R, D>(device: &mut D, data: &[u8]) -> Result<gfx::handle::ShaderResourceView<R, [f32; 4]>, String> where R: gfx::Resources, D: gfx::Device<R> { use gfx::texture as t; let img = image::load(Cursor::new(data), image::PNG).unwrap().to_rgba(); let (width, height) = img.dimensions(); let kind = t::Kind::D2(width as t::Size, height as t::Size, t::AaMode::Single); let (_, view) = device.create_texture_immutable_u8::<Rgba8>(kind, &[&img]).unwrap(); Ok(view) } struct App<B: gfx::Backend> { views: Vec<BackbufferView<B::Resources>>, bundle: Bundle<B, pipe::Data<B::Resources>>, cycles: [f32; 2], time_start: Instant, } impl<B: gfx::Backend> gfx_support::Application<B> for App<B> { fn new(device: &mut B::Device, _: &mut gfx::queue::GraphicsQueue<B>, backend: gfx_support::shade::Backend, window_targets: gfx_support::WindowTargets<B::Resources>) -> Self { use gfx::traits::DeviceExt; let vs = gfx_support::shade::Source { glsl_120: include_bytes!("shader/flowmap_120.glslv"), glsl_150: include_bytes!("shader/flowmap_150.glslv"), hlsl_40: include_bytes!("data/vertex.fx"), msl_11: include_bytes!("shader/flowmap_vertex.metal"), .. gfx_support::shade::Source::empty() }; let ps = gfx_support::shade::Source { glsl_120: include_bytes!("shader/flowmap_120.glslf"), glsl_150: include_bytes!("shader/flowmap_150.glslf"), hlsl_40: include_bytes!("data/pixel.fx"), msl_11: include_bytes!("shader/flowmap_frag.metal"), .. gfx_support::shade::Source::empty() }; let vertex_data = [ Vertex::new([-1.0, -1.0], [0.0, 0.0]), Vertex::new([ 1.0, -1.0], [1.0, 0.0]), Vertex::new([ 1.0, 1.0], [1.0, 1.0]), Vertex::new([-1.0, -1.0], [0.0, 0.0]), Vertex::new([ 1.0, 1.0], [1.0, 1.0]), Vertex::new([-1.0, 1.0], [0.0, 1.0]), ]; let (vbuf, slice) = device.create_vertex_buffer_with_slice(&vertex_data, ()); let water_texture = load_texture(device, &include_bytes!("image/water.png")[..]).unwrap(); let flow_texture = load_texture(device, &include_bytes!("image/flow.png")[..]).unwrap(); let noise_texture = load_texture(device, &include_bytes!("image/noise.png")[..]).unwrap(); let sampler = device.create_sampler_linear(); let pso = device.create_pipeline_simple( vs.select(backend).unwrap(), ps.select(backend).unwrap(), pipe::new() ).unwrap(); let data = pipe::Data { vbuf: vbuf, color: (water_texture, sampler.clone()), flow: (flow_texture, sampler.clone()), noise: (noise_texture, sampler.clone()), offset0: 0.0, offset1: 0.0, locals: device.create_constant_buffer(1), out: window_targets.views[0].0.clone(), }; App { views: window_targets.views, bundle: Bundle::new(slice, pso, data), cycles: [0.0, 0.5], time_start: Instant::now(), } } fn render(&mut self, (frame, sync): (gfx::Frame, &gfx_support::SyncPrimitives<B::Resources>), pool: &mut gfx::GraphicsCommandPool<B>, queue: &mut gfx::queue::GraphicsQueue<B>) { let delta = self.time_start.elapsed(); self.time_start = Instant::now(); let delta = delta.as_secs() as f32 + delta.subsec_nanos() as f32 / 1000_000_000.0; // since we sample our diffuse texture twice we need to lerp between // them to get a smooth transition (shouldn't even be noticeable). // They start half a cycle apart (0.5) and is later used to calculate // the interpolation amount via `2.0 * abs(cycle0 -.5f)` self.cycles[0] += 0.25 * delta; if self.cycles[0] > 1.0
self.cycles[1] += 0.25 * delta; if self.cycles[1] > 1.0 { self.cycles[1] -= 1.0; } let (cur_color, _) = self.views[frame.id()].clone(); self.bundle.data.out = cur_color; let mut encoder = pool.acquire_graphics_encoder(); self.bundle.data.offset0 = self.cycles[0]; self.bundle.data.offset1 = self.cycles[1]; let locals = Locals { offsets: self.cycles }; encoder.update_constant_buffer(&self.bundle.data.locals, &locals); encoder.clear(&self.bundle.data.out, [0.3, 0.3, 0.3, 1.0]); self.bundle.encode(&mut encoder); encoder.synced_flush(queue, &[&sync.rendering], &[], Some(&sync.frame_fence)) .expect("Could not flush encoder"); } fn on_resize(&mut self, window_targets: gfx_support::WindowTargets<B::Resources>) { self.views = window_targets.views; } } pub fn main() { use gfx_support::Application; App::launch_simple("Flowmap example"); }
{ self.cycles[0] -= 1.0; }
conditional_block
main.rs
#[macro_use] extern crate gfx; extern crate gfx_support; extern crate image; use std::io::Cursor; use std::time::Instant; use gfx::format::Rgba8; use gfx_support::{BackbufferView, ColorFormat}; use gfx::{Bundle, GraphicsPoolExt}; gfx_defines!{ vertex Vertex { pos: [f32; 2] = "a_Pos", uv: [f32; 2] = "a_Uv", } constant Locals { offsets: [f32; 2] = "u_Offsets", } pipeline pipe { vbuf: gfx::VertexBuffer<Vertex> = (), color: gfx::TextureSampler<[f32; 4]> = "t_Color", flow: gfx::TextureSampler<[f32; 4]> = "t_Flow", noise: gfx::TextureSampler<[f32; 4]> = "t_Noise", offset0: gfx::Global<f32> = "f_Offset0", offset1: gfx::Global<f32> = "f_Offset1", locals: gfx::ConstantBuffer<Locals> = "Locals", out: gfx::RenderTarget<ColorFormat> = "Target0", } } impl Vertex { fn new(p: [f32; 2], u: [f32; 2]) -> Vertex { Vertex { pos: p, uv: u, } } } fn load_texture<R, D>(device: &mut D, data: &[u8]) -> Result<gfx::handle::ShaderResourceView<R, [f32; 4]>, String> where R: gfx::Resources, D: gfx::Device<R> { use gfx::texture as t; let img = image::load(Cursor::new(data), image::PNG).unwrap().to_rgba(); let (width, height) = img.dimensions(); let kind = t::Kind::D2(width as t::Size, height as t::Size, t::AaMode::Single); let (_, view) = device.create_texture_immutable_u8::<Rgba8>(kind, &[&img]).unwrap(); Ok(view) } struct App<B: gfx::Backend> { views: Vec<BackbufferView<B::Resources>>, bundle: Bundle<B, pipe::Data<B::Resources>>, cycles: [f32; 2], time_start: Instant,
impl<B: gfx::Backend> gfx_support::Application<B> for App<B> { fn new(device: &mut B::Device, _: &mut gfx::queue::GraphicsQueue<B>, backend: gfx_support::shade::Backend, window_targets: gfx_support::WindowTargets<B::Resources>) -> Self { use gfx::traits::DeviceExt; let vs = gfx_support::shade::Source { glsl_120: include_bytes!("shader/flowmap_120.glslv"), glsl_150: include_bytes!("shader/flowmap_150.glslv"), hlsl_40: include_bytes!("data/vertex.fx"), msl_11: include_bytes!("shader/flowmap_vertex.metal"), .. gfx_support::shade::Source::empty() }; let ps = gfx_support::shade::Source { glsl_120: include_bytes!("shader/flowmap_120.glslf"), glsl_150: include_bytes!("shader/flowmap_150.glslf"), hlsl_40: include_bytes!("data/pixel.fx"), msl_11: include_bytes!("shader/flowmap_frag.metal"), .. gfx_support::shade::Source::empty() }; let vertex_data = [ Vertex::new([-1.0, -1.0], [0.0, 0.0]), Vertex::new([ 1.0, -1.0], [1.0, 0.0]), Vertex::new([ 1.0, 1.0], [1.0, 1.0]), Vertex::new([-1.0, -1.0], [0.0, 0.0]), Vertex::new([ 1.0, 1.0], [1.0, 1.0]), Vertex::new([-1.0, 1.0], [0.0, 1.0]), ]; let (vbuf, slice) = device.create_vertex_buffer_with_slice(&vertex_data, ()); let water_texture = load_texture(device, &include_bytes!("image/water.png")[..]).unwrap(); let flow_texture = load_texture(device, &include_bytes!("image/flow.png")[..]).unwrap(); let noise_texture = load_texture(device, &include_bytes!("image/noise.png")[..]).unwrap(); let sampler = device.create_sampler_linear(); let pso = device.create_pipeline_simple( vs.select(backend).unwrap(), ps.select(backend).unwrap(), pipe::new() ).unwrap(); let data = pipe::Data { vbuf: vbuf, color: (water_texture, sampler.clone()), flow: (flow_texture, sampler.clone()), noise: (noise_texture, sampler.clone()), offset0: 0.0, offset1: 0.0, locals: device.create_constant_buffer(1), out: window_targets.views[0].0.clone(), }; App { views: window_targets.views, bundle: Bundle::new(slice, pso, data), cycles: [0.0, 0.5], time_start: Instant::now(), } } fn render(&mut self, (frame, sync): (gfx::Frame, &gfx_support::SyncPrimitives<B::Resources>), pool: &mut gfx::GraphicsCommandPool<B>, queue: &mut gfx::queue::GraphicsQueue<B>) { let delta = self.time_start.elapsed(); self.time_start = Instant::now(); let delta = delta.as_secs() as f32 + delta.subsec_nanos() as f32 / 1000_000_000.0; // since we sample our diffuse texture twice we need to lerp between // them to get a smooth transition (shouldn't even be noticeable). // They start half a cycle apart (0.5) and is later used to calculate // the interpolation amount via `2.0 * abs(cycle0 -.5f)` self.cycles[0] += 0.25 * delta; if self.cycles[0] > 1.0 { self.cycles[0] -= 1.0; } self.cycles[1] += 0.25 * delta; if self.cycles[1] > 1.0 { self.cycles[1] -= 1.0; } let (cur_color, _) = self.views[frame.id()].clone(); self.bundle.data.out = cur_color; let mut encoder = pool.acquire_graphics_encoder(); self.bundle.data.offset0 = self.cycles[0]; self.bundle.data.offset1 = self.cycles[1]; let locals = Locals { offsets: self.cycles }; encoder.update_constant_buffer(&self.bundle.data.locals, &locals); encoder.clear(&self.bundle.data.out, [0.3, 0.3, 0.3, 1.0]); self.bundle.encode(&mut encoder); encoder.synced_flush(queue, &[&sync.rendering], &[], Some(&sync.frame_fence)) .expect("Could not flush encoder"); } fn on_resize(&mut self, window_targets: gfx_support::WindowTargets<B::Resources>) { self.views = window_targets.views; } } pub fn main() { use gfx_support::Application; App::launch_simple("Flowmap example"); }
}
random_line_split
main.rs
#[macro_use] extern crate gfx; extern crate gfx_support; extern crate image; use std::io::Cursor; use std::time::Instant; use gfx::format::Rgba8; use gfx_support::{BackbufferView, ColorFormat}; use gfx::{Bundle, GraphicsPoolExt}; gfx_defines!{ vertex Vertex { pos: [f32; 2] = "a_Pos", uv: [f32; 2] = "a_Uv", } constant Locals { offsets: [f32; 2] = "u_Offsets", } pipeline pipe { vbuf: gfx::VertexBuffer<Vertex> = (), color: gfx::TextureSampler<[f32; 4]> = "t_Color", flow: gfx::TextureSampler<[f32; 4]> = "t_Flow", noise: gfx::TextureSampler<[f32; 4]> = "t_Noise", offset0: gfx::Global<f32> = "f_Offset0", offset1: gfx::Global<f32> = "f_Offset1", locals: gfx::ConstantBuffer<Locals> = "Locals", out: gfx::RenderTarget<ColorFormat> = "Target0", } } impl Vertex { fn
(p: [f32; 2], u: [f32; 2]) -> Vertex { Vertex { pos: p, uv: u, } } } fn load_texture<R, D>(device: &mut D, data: &[u8]) -> Result<gfx::handle::ShaderResourceView<R, [f32; 4]>, String> where R: gfx::Resources, D: gfx::Device<R> { use gfx::texture as t; let img = image::load(Cursor::new(data), image::PNG).unwrap().to_rgba(); let (width, height) = img.dimensions(); let kind = t::Kind::D2(width as t::Size, height as t::Size, t::AaMode::Single); let (_, view) = device.create_texture_immutable_u8::<Rgba8>(kind, &[&img]).unwrap(); Ok(view) } struct App<B: gfx::Backend> { views: Vec<BackbufferView<B::Resources>>, bundle: Bundle<B, pipe::Data<B::Resources>>, cycles: [f32; 2], time_start: Instant, } impl<B: gfx::Backend> gfx_support::Application<B> for App<B> { fn new(device: &mut B::Device, _: &mut gfx::queue::GraphicsQueue<B>, backend: gfx_support::shade::Backend, window_targets: gfx_support::WindowTargets<B::Resources>) -> Self { use gfx::traits::DeviceExt; let vs = gfx_support::shade::Source { glsl_120: include_bytes!("shader/flowmap_120.glslv"), glsl_150: include_bytes!("shader/flowmap_150.glslv"), hlsl_40: include_bytes!("data/vertex.fx"), msl_11: include_bytes!("shader/flowmap_vertex.metal"), .. gfx_support::shade::Source::empty() }; let ps = gfx_support::shade::Source { glsl_120: include_bytes!("shader/flowmap_120.glslf"), glsl_150: include_bytes!("shader/flowmap_150.glslf"), hlsl_40: include_bytes!("data/pixel.fx"), msl_11: include_bytes!("shader/flowmap_frag.metal"), .. gfx_support::shade::Source::empty() }; let vertex_data = [ Vertex::new([-1.0, -1.0], [0.0, 0.0]), Vertex::new([ 1.0, -1.0], [1.0, 0.0]), Vertex::new([ 1.0, 1.0], [1.0, 1.0]), Vertex::new([-1.0, -1.0], [0.0, 0.0]), Vertex::new([ 1.0, 1.0], [1.0, 1.0]), Vertex::new([-1.0, 1.0], [0.0, 1.0]), ]; let (vbuf, slice) = device.create_vertex_buffer_with_slice(&vertex_data, ()); let water_texture = load_texture(device, &include_bytes!("image/water.png")[..]).unwrap(); let flow_texture = load_texture(device, &include_bytes!("image/flow.png")[..]).unwrap(); let noise_texture = load_texture(device, &include_bytes!("image/noise.png")[..]).unwrap(); let sampler = device.create_sampler_linear(); let pso = device.create_pipeline_simple( vs.select(backend).unwrap(), ps.select(backend).unwrap(), pipe::new() ).unwrap(); let data = pipe::Data { vbuf: vbuf, color: (water_texture, sampler.clone()), flow: (flow_texture, sampler.clone()), noise: (noise_texture, sampler.clone()), offset0: 0.0, offset1: 0.0, locals: device.create_constant_buffer(1), out: window_targets.views[0].0.clone(), }; App { views: window_targets.views, bundle: Bundle::new(slice, pso, data), cycles: [0.0, 0.5], time_start: Instant::now(), } } fn render(&mut self, (frame, sync): (gfx::Frame, &gfx_support::SyncPrimitives<B::Resources>), pool: &mut gfx::GraphicsCommandPool<B>, queue: &mut gfx::queue::GraphicsQueue<B>) { let delta = self.time_start.elapsed(); self.time_start = Instant::now(); let delta = delta.as_secs() as f32 + delta.subsec_nanos() as f32 / 1000_000_000.0; // since we sample our diffuse texture twice we need to lerp between // them to get a smooth transition (shouldn't even be noticeable). // They start half a cycle apart (0.5) and is later used to calculate // the interpolation amount via `2.0 * abs(cycle0 -.5f)` self.cycles[0] += 0.25 * delta; if self.cycles[0] > 1.0 { self.cycles[0] -= 1.0; } self.cycles[1] += 0.25 * delta; if self.cycles[1] > 1.0 { self.cycles[1] -= 1.0; } let (cur_color, _) = self.views[frame.id()].clone(); self.bundle.data.out = cur_color; let mut encoder = pool.acquire_graphics_encoder(); self.bundle.data.offset0 = self.cycles[0]; self.bundle.data.offset1 = self.cycles[1]; let locals = Locals { offsets: self.cycles }; encoder.update_constant_buffer(&self.bundle.data.locals, &locals); encoder.clear(&self.bundle.data.out, [0.3, 0.3, 0.3, 1.0]); self.bundle.encode(&mut encoder); encoder.synced_flush(queue, &[&sync.rendering], &[], Some(&sync.frame_fence)) .expect("Could not flush encoder"); } fn on_resize(&mut self, window_targets: gfx_support::WindowTargets<B::Resources>) { self.views = window_targets.views; } } pub fn main() { use gfx_support::Application; App::launch_simple("Flowmap example"); }
new
identifier_name
test_default_bytes.rs
// Copyright 2014-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. extern crate rand; extern crate regex; macro_rules! regex_new { ($re:expr) => {{ use regex::bytes::Regex; Regex::new($re) }} } macro_rules! regex_set_new { ($res:expr) => {{ use regex::bytes::RegexSet; RegexSet::new($res) }}
} } macro_rules! regex_set { ($res:expr) => { regex_set_new!($res).unwrap() } } // Must come before other module definitions. include!("macros_bytes.rs"); include!("macros.rs"); mod api; mod bytes; mod crazy; mod flags; mod fowler; mod multiline; mod noparse; mod regression; mod replace; mod set; mod shortest_match; mod suffix_reverse; mod unicode; mod word_boundary; mod word_boundary_ascii;
} macro_rules! regex { ($re:expr) => { regex_new!($re).unwrap()
random_line_split
regions-mock-trans-impls.rs
// xfail-fast // 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. extern mod std; use core::libc; use core::sys; use core::cast; use std::arena::Arena; struct Bcx<'self> { fcx: &'self Fcx<'self> } struct Fcx<'self> { arena: &'self Arena, ccx: &'self Ccx } struct Ccx { x: int } fn h<'r>(bcx : &'r Bcx<'r>) -> &'r Bcx<'r> { return bcx.fcx.arena.alloc(|| Bcx { fcx: bcx.fcx }); } fn g(fcx : &Fcx) { let bcx = Bcx { fcx: fcx }; h(&bcx); } fn f(ccx : &Ccx) { let a = Arena(); let fcx = &Fcx { arena: &a, ccx: ccx }; return g(fcx); } pub fn
() { let ccx = Ccx { x: 0 }; f(&ccx); }
main
identifier_name
regions-mock-trans-impls.rs
// xfail-fast // 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. extern mod std; use core::libc; use core::sys; use core::cast; use std::arena::Arena; struct Bcx<'self> {
arena: &'self Arena, ccx: &'self Ccx } struct Ccx { x: int } fn h<'r>(bcx : &'r Bcx<'r>) -> &'r Bcx<'r> { return bcx.fcx.arena.alloc(|| Bcx { fcx: bcx.fcx }); } fn g(fcx : &Fcx) { let bcx = Bcx { fcx: fcx }; h(&bcx); } fn f(ccx : &Ccx) { let a = Arena(); let fcx = &Fcx { arena: &a, ccx: ccx }; return g(fcx); } pub fn main() { let ccx = Ccx { x: 0 }; f(&ccx); }
fcx: &'self Fcx<'self> } struct Fcx<'self> {
random_line_split
unboxed-closures-manual-impl.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. #![feature(unboxed_closures, core)] use std::ops::FnMut; struct S;
impl FnOnce<(i32,)> for S { type Output = i32; extern "rust-call" fn call_once(mut self, args: (i32,)) -> i32 { self.call_mut(args) } } fn call_it<F:FnMut(i32)->i32>(mut f: F, x: i32) -> i32 { f(x) + 3 } fn call_box(f: &mut FnMut(i32) -> i32, x: i32) -> i32 { f(x) + 3 } fn main() { let x = call_it(S, 1); let y = call_box(&mut S, 1); assert_eq!(x, 4); assert_eq!(y, 4); }
impl FnMut<(i32,)> for S { extern "rust-call" fn call_mut(&mut self, (x,): (i32,)) -> i32 { x * x } }
random_line_split
unboxed-closures-manual-impl.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. #![feature(unboxed_closures, core)] use std::ops::FnMut; struct S; impl FnMut<(i32,)> for S { extern "rust-call" fn call_mut(&mut self, (x,): (i32,)) -> i32 { x * x } } impl FnOnce<(i32,)> for S { type Output = i32; extern "rust-call" fn
(mut self, args: (i32,)) -> i32 { self.call_mut(args) } } fn call_it<F:FnMut(i32)->i32>(mut f: F, x: i32) -> i32 { f(x) + 3 } fn call_box(f: &mut FnMut(i32) -> i32, x: i32) -> i32 { f(x) + 3 } fn main() { let x = call_it(S, 1); let y = call_box(&mut S, 1); assert_eq!(x, 4); assert_eq!(y, 4); }
call_once
identifier_name
unboxed-closures-manual-impl.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. #![feature(unboxed_closures, core)] use std::ops::FnMut; struct S; impl FnMut<(i32,)> for S { extern "rust-call" fn call_mut(&mut self, (x,): (i32,)) -> i32
} impl FnOnce<(i32,)> for S { type Output = i32; extern "rust-call" fn call_once(mut self, args: (i32,)) -> i32 { self.call_mut(args) } } fn call_it<F:FnMut(i32)->i32>(mut f: F, x: i32) -> i32 { f(x) + 3 } fn call_box(f: &mut FnMut(i32) -> i32, x: i32) -> i32 { f(x) + 3 } fn main() { let x = call_it(S, 1); let y = call_box(&mut S, 1); assert_eq!(x, 4); assert_eq!(y, 4); }
{ x * x }
identifier_body
text_buffer.rs
// Copyright 2013-2016, The Gtk-rs Project Developers. // See the COPYRIGHT file at the top-level directory of this distribution. // Licensed under the MIT license, see the LICENSE file or <http://opensource.org/licenses/MIT> use libc::{c_char, c_int}; use std::boxed::Box as Box_; use std::mem::transmute; use std::{slice, str}; use ffi; use glib; use glib::object::IsA; use glib::translate::*; use glib::signal::{SignalHandlerId, connect}; use glib_ffi; use TextBuffer; use TextIter; pub trait TextBufferExtManual { fn connect_insert_text<F: Fn(&TextBuffer, &mut TextIter, &str) +'static>(&self, f: F) -> SignalHandlerId; } impl<O: IsA<TextBuffer> + IsA<glib::object::Object>> TextBufferExtManual for O { fn
<F: Fn(&TextBuffer, &mut TextIter, &str) +'static>(&self, f: F) -> SignalHandlerId { unsafe { let f: Box_<Box_<Fn(&TextBuffer, &mut TextIter, &str) +'static>> = Box_::new(Box_::new(f)); connect(self.to_glib_none().0, "insert-text", transmute(insert_text_trampoline as usize), Box_::into_raw(f) as *mut _) } } } unsafe extern "C" fn insert_text_trampoline(this: *mut ffi::GtkTextBuffer, location: *mut ffi::GtkTextIter, text: *mut c_char, len: c_int, f: glib_ffi::gpointer) { let f: &&(Fn(&TextBuffer, &TextIter, &str) +'static) = transmute(f); f(&from_glib_borrow(this), &mut from_glib_borrow(location), str::from_utf8(slice::from_raw_parts(text as *const u8, len as usize)).unwrap()) }
connect_insert_text
identifier_name
text_buffer.rs
// Copyright 2013-2016, The Gtk-rs Project Developers. // See the COPYRIGHT file at the top-level directory of this distribution. // Licensed under the MIT license, see the LICENSE file or <http://opensource.org/licenses/MIT> use libc::{c_char, c_int}; use std::boxed::Box as Box_; use std::mem::transmute; use std::{slice, str}; use ffi; use glib; use glib::object::IsA; use glib::translate::*; use glib::signal::{SignalHandlerId, connect}; use glib_ffi; use TextBuffer; use TextIter; pub trait TextBufferExtManual { fn connect_insert_text<F: Fn(&TextBuffer, &mut TextIter, &str) +'static>(&self, f: F) -> SignalHandlerId; } impl<O: IsA<TextBuffer> + IsA<glib::object::Object>> TextBufferExtManual for O { fn connect_insert_text<F: Fn(&TextBuffer, &mut TextIter, &str) +'static>(&self, f: F) -> SignalHandlerId { unsafe { let f: Box_<Box_<Fn(&TextBuffer, &mut TextIter, &str) +'static>> = Box_::new(Box_::new(f)); connect(self.to_glib_none().0, "insert-text", transmute(insert_text_trampoline as usize), Box_::into_raw(f) as *mut _) } } } unsafe extern "C" fn insert_text_trampoline(this: *mut ffi::GtkTextBuffer, location: *mut ffi::GtkTextIter, text: *mut c_char, len: c_int, f: glib_ffi::gpointer) { let f: &&(Fn(&TextBuffer, &TextIter, &str) +'static) = transmute(f); f(&from_glib_borrow(this),
&mut from_glib_borrow(location), str::from_utf8(slice::from_raw_parts(text as *const u8, len as usize)).unwrap()) }
random_line_split
text_buffer.rs
// Copyright 2013-2016, The Gtk-rs Project Developers. // See the COPYRIGHT file at the top-level directory of this distribution. // Licensed under the MIT license, see the LICENSE file or <http://opensource.org/licenses/MIT> use libc::{c_char, c_int}; use std::boxed::Box as Box_; use std::mem::transmute; use std::{slice, str}; use ffi; use glib; use glib::object::IsA; use glib::translate::*; use glib::signal::{SignalHandlerId, connect}; use glib_ffi; use TextBuffer; use TextIter; pub trait TextBufferExtManual { fn connect_insert_text<F: Fn(&TextBuffer, &mut TextIter, &str) +'static>(&self, f: F) -> SignalHandlerId; } impl<O: IsA<TextBuffer> + IsA<glib::object::Object>> TextBufferExtManual for O { fn connect_insert_text<F: Fn(&TextBuffer, &mut TextIter, &str) +'static>(&self, f: F) -> SignalHandlerId
} unsafe extern "C" fn insert_text_trampoline(this: *mut ffi::GtkTextBuffer, location: *mut ffi::GtkTextIter, text: *mut c_char, len: c_int, f: glib_ffi::gpointer) { let f: &&(Fn(&TextBuffer, &TextIter, &str) +'static) = transmute(f); f(&from_glib_borrow(this), &mut from_glib_borrow(location), str::from_utf8(slice::from_raw_parts(text as *const u8, len as usize)).unwrap()) }
{ unsafe { let f: Box_<Box_<Fn(&TextBuffer, &mut TextIter, &str) + 'static>> = Box_::new(Box_::new(f)); connect(self.to_glib_none().0, "insert-text", transmute(insert_text_trampoline as usize), Box_::into_raw(f) as *mut _) } }
identifier_body
ssl.rs
// #![feature(plugin)] // #![plugin(clippy)] extern crate cassandra_sys; use std::mem; use std::io::Result as IoResult; use std::io::Read; use std::fs::File; use cassandra_sys::*; use std::ffi::CString; fn load_trusted_cert_file(file: &str, ssl: &mut CassSsl) -> IoResult<()> { unsafe { let mut file = try!(File::open(file)); let cert_size = try!(file.metadata()).len() as usize; let mut cert: Vec<u8> = Vec::with_capacity(cert_size); let byte_len = try!(file.read_to_end(&mut cert)); match byte_len == cert_size { true => { let rc = cass_ssl_add_trusted_cert_n(ssl, cert.as_ptr() as *const i8, cert_size); match rc { CASS_OK => Ok(()), rc => { panic!("Error loading SSL certificate: {:?}", cass_error_desc(rc)); } } } false => { println!("Error loading SSL certificate. Not enough bytes read"); Ok(()) } } } } fn main() { unsafe { // Setup and connect to cluster let cluster = cass_cluster_new(); let session = cass_session_new(); let ssl = cass_ssl_new(); cass_cluster_set_contact_points(cluster, CString::new("127.0.0.1").unwrap().as_ptr()); // Only verify the certification and not the identity cass_ssl_set_verify_flags(ssl, CASS_SSL_VERIFY_PEER_CERT as i32); match load_trusted_cert_file("cert.pem", &mut *ssl) { Ok(_) =>
rc => { println!("Failed to load certificate disabling peer verification: {:?}", rc); cass_ssl_set_verify_flags(ssl, CASS_SSL_VERIFY_NONE as i32); } } cass_cluster_set_ssl(cluster, ssl); let connect_future = cass_session_connect(session, cluster); match cass_future_error_code(connect_future) { CASS_OK => { // Build statement and execute query let query = "SELECT keyspace_name FROM system.schema_keyspaces;"; let statement = cass_statement_new(CString::new(query).unwrap().as_ptr(), 0); let result_future = cass_session_execute(session, statement); if cass_future_error_code(result_future) == CASS_OK { // Retrieve result set and iterator over the rows let result = cass_future_get_result(result_future); let rows = cass_iterator_from_result(result); while cass_iterator_next(rows) == cass_true { let row = cass_iterator_get_row(rows); let value = cass_row_get_column_by_name(row, CString::new("keyspace_name").unwrap().as_ptr()); let mut keyspace_name = mem::zeroed(); let mut keyspace_name_length = mem::zeroed(); cass_value_get_string(value, &mut keyspace_name, &mut keyspace_name_length); println!("keyspace_name: {:?}", raw2utf8(keyspace_name, keyspace_name_length)); } cass_result_free(result); cass_iterator_free(rows); } else { // Handle error let mut message = mem::zeroed(); let mut message_length = mem::zeroed(); cass_future_error_message(result_future, &mut message, &mut message_length); println!("Unable to run query: {:?}", raw2utf8(message, message_length)); } cass_statement_free(statement); cass_future_free(result_future); // Close the session let close_future = cass_session_close(session); cass_future_wait(close_future); cass_future_free(close_future); } _ => { // Handle error let mut message = mem::zeroed(); let mut message_length = mem::zeroed(); cass_future_error_message(connect_future, &mut message, &mut message_length); println!("Unable to connect: : {:?}", raw2utf8(message, message_length)); } } cass_future_free(connect_future); cass_cluster_free(cluster); cass_session_free(session); cass_ssl_free(ssl); } }
{}
conditional_block
ssl.rs
// #![feature(plugin)] // #![plugin(clippy)] extern crate cassandra_sys; use std::mem; use std::io::Result as IoResult; use std::io::Read; use std::fs::File; use cassandra_sys::*; use std::ffi::CString; fn load_trusted_cert_file(file: &str, ssl: &mut CassSsl) -> IoResult<()> { unsafe { let mut file = try!(File::open(file)); let cert_size = try!(file.metadata()).len() as usize; let mut cert: Vec<u8> = Vec::with_capacity(cert_size); let byte_len = try!(file.read_to_end(&mut cert)); match byte_len == cert_size { true => { let rc = cass_ssl_add_trusted_cert_n(ssl, cert.as_ptr() as *const i8, cert_size); match rc { CASS_OK => Ok(()), rc => { panic!("Error loading SSL certificate: {:?}", cass_error_desc(rc)); } } } false => { println!("Error loading SSL certificate. Not enough bytes read"); Ok(()) } } } }
unsafe { // Setup and connect to cluster let cluster = cass_cluster_new(); let session = cass_session_new(); let ssl = cass_ssl_new(); cass_cluster_set_contact_points(cluster, CString::new("127.0.0.1").unwrap().as_ptr()); // Only verify the certification and not the identity cass_ssl_set_verify_flags(ssl, CASS_SSL_VERIFY_PEER_CERT as i32); match load_trusted_cert_file("cert.pem", &mut *ssl) { Ok(_) => {} rc => { println!("Failed to load certificate disabling peer verification: {:?}", rc); cass_ssl_set_verify_flags(ssl, CASS_SSL_VERIFY_NONE as i32); } } cass_cluster_set_ssl(cluster, ssl); let connect_future = cass_session_connect(session, cluster); match cass_future_error_code(connect_future) { CASS_OK => { // Build statement and execute query let query = "SELECT keyspace_name FROM system.schema_keyspaces;"; let statement = cass_statement_new(CString::new(query).unwrap().as_ptr(), 0); let result_future = cass_session_execute(session, statement); if cass_future_error_code(result_future) == CASS_OK { // Retrieve result set and iterator over the rows let result = cass_future_get_result(result_future); let rows = cass_iterator_from_result(result); while cass_iterator_next(rows) == cass_true { let row = cass_iterator_get_row(rows); let value = cass_row_get_column_by_name(row, CString::new("keyspace_name").unwrap().as_ptr()); let mut keyspace_name = mem::zeroed(); let mut keyspace_name_length = mem::zeroed(); cass_value_get_string(value, &mut keyspace_name, &mut keyspace_name_length); println!("keyspace_name: {:?}", raw2utf8(keyspace_name, keyspace_name_length)); } cass_result_free(result); cass_iterator_free(rows); } else { // Handle error let mut message = mem::zeroed(); let mut message_length = mem::zeroed(); cass_future_error_message(result_future, &mut message, &mut message_length); println!("Unable to run query: {:?}", raw2utf8(message, message_length)); } cass_statement_free(statement); cass_future_free(result_future); // Close the session let close_future = cass_session_close(session); cass_future_wait(close_future); cass_future_free(close_future); } _ => { // Handle error let mut message = mem::zeroed(); let mut message_length = mem::zeroed(); cass_future_error_message(connect_future, &mut message, &mut message_length); println!("Unable to connect: : {:?}", raw2utf8(message, message_length)); } } cass_future_free(connect_future); cass_cluster_free(cluster); cass_session_free(session); cass_ssl_free(ssl); } }
fn main() {
random_line_split
ssl.rs
// #![feature(plugin)] // #![plugin(clippy)] extern crate cassandra_sys; use std::mem; use std::io::Result as IoResult; use std::io::Read; use std::fs::File; use cassandra_sys::*; use std::ffi::CString; fn load_trusted_cert_file(file: &str, ssl: &mut CassSsl) -> IoResult<()>
} } } fn main() { unsafe { // Setup and connect to cluster let cluster = cass_cluster_new(); let session = cass_session_new(); let ssl = cass_ssl_new(); cass_cluster_set_contact_points(cluster, CString::new("127.0.0.1").unwrap().as_ptr()); // Only verify the certification and not the identity cass_ssl_set_verify_flags(ssl, CASS_SSL_VERIFY_PEER_CERT as i32); match load_trusted_cert_file("cert.pem", &mut *ssl) { Ok(_) => {} rc => { println!("Failed to load certificate disabling peer verification: {:?}", rc); cass_ssl_set_verify_flags(ssl, CASS_SSL_VERIFY_NONE as i32); } } cass_cluster_set_ssl(cluster, ssl); let connect_future = cass_session_connect(session, cluster); match cass_future_error_code(connect_future) { CASS_OK => { // Build statement and execute query let query = "SELECT keyspace_name FROM system.schema_keyspaces;"; let statement = cass_statement_new(CString::new(query).unwrap().as_ptr(), 0); let result_future = cass_session_execute(session, statement); if cass_future_error_code(result_future) == CASS_OK { // Retrieve result set and iterator over the rows let result = cass_future_get_result(result_future); let rows = cass_iterator_from_result(result); while cass_iterator_next(rows) == cass_true { let row = cass_iterator_get_row(rows); let value = cass_row_get_column_by_name(row, CString::new("keyspace_name").unwrap().as_ptr()); let mut keyspace_name = mem::zeroed(); let mut keyspace_name_length = mem::zeroed(); cass_value_get_string(value, &mut keyspace_name, &mut keyspace_name_length); println!("keyspace_name: {:?}", raw2utf8(keyspace_name, keyspace_name_length)); } cass_result_free(result); cass_iterator_free(rows); } else { // Handle error let mut message = mem::zeroed(); let mut message_length = mem::zeroed(); cass_future_error_message(result_future, &mut message, &mut message_length); println!("Unable to run query: {:?}", raw2utf8(message, message_length)); } cass_statement_free(statement); cass_future_free(result_future); // Close the session let close_future = cass_session_close(session); cass_future_wait(close_future); cass_future_free(close_future); } _ => { // Handle error let mut message = mem::zeroed(); let mut message_length = mem::zeroed(); cass_future_error_message(connect_future, &mut message, &mut message_length); println!("Unable to connect: : {:?}", raw2utf8(message, message_length)); } } cass_future_free(connect_future); cass_cluster_free(cluster); cass_session_free(session); cass_ssl_free(ssl); } }
{ unsafe { let mut file = try!(File::open(file)); let cert_size = try!(file.metadata()).len() as usize; let mut cert: Vec<u8> = Vec::with_capacity(cert_size); let byte_len = try!(file.read_to_end(&mut cert)); match byte_len == cert_size { true => { let rc = cass_ssl_add_trusted_cert_n(ssl, cert.as_ptr() as *const i8, cert_size); match rc { CASS_OK => Ok(()), rc => { panic!("Error loading SSL certificate: {:?}", cass_error_desc(rc)); } } } false => { println!("Error loading SSL certificate. Not enough bytes read"); Ok(()) }
identifier_body
ssl.rs
// #![feature(plugin)] // #![plugin(clippy)] extern crate cassandra_sys; use std::mem; use std::io::Result as IoResult; use std::io::Read; use std::fs::File; use cassandra_sys::*; use std::ffi::CString; fn load_trusted_cert_file(file: &str, ssl: &mut CassSsl) -> IoResult<()> { unsafe { let mut file = try!(File::open(file)); let cert_size = try!(file.metadata()).len() as usize; let mut cert: Vec<u8> = Vec::with_capacity(cert_size); let byte_len = try!(file.read_to_end(&mut cert)); match byte_len == cert_size { true => { let rc = cass_ssl_add_trusted_cert_n(ssl, cert.as_ptr() as *const i8, cert_size); match rc { CASS_OK => Ok(()), rc => { panic!("Error loading SSL certificate: {:?}", cass_error_desc(rc)); } } } false => { println!("Error loading SSL certificate. Not enough bytes read"); Ok(()) } } } } fn
() { unsafe { // Setup and connect to cluster let cluster = cass_cluster_new(); let session = cass_session_new(); let ssl = cass_ssl_new(); cass_cluster_set_contact_points(cluster, CString::new("127.0.0.1").unwrap().as_ptr()); // Only verify the certification and not the identity cass_ssl_set_verify_flags(ssl, CASS_SSL_VERIFY_PEER_CERT as i32); match load_trusted_cert_file("cert.pem", &mut *ssl) { Ok(_) => {} rc => { println!("Failed to load certificate disabling peer verification: {:?}", rc); cass_ssl_set_verify_flags(ssl, CASS_SSL_VERIFY_NONE as i32); } } cass_cluster_set_ssl(cluster, ssl); let connect_future = cass_session_connect(session, cluster); match cass_future_error_code(connect_future) { CASS_OK => { // Build statement and execute query let query = "SELECT keyspace_name FROM system.schema_keyspaces;"; let statement = cass_statement_new(CString::new(query).unwrap().as_ptr(), 0); let result_future = cass_session_execute(session, statement); if cass_future_error_code(result_future) == CASS_OK { // Retrieve result set and iterator over the rows let result = cass_future_get_result(result_future); let rows = cass_iterator_from_result(result); while cass_iterator_next(rows) == cass_true { let row = cass_iterator_get_row(rows); let value = cass_row_get_column_by_name(row, CString::new("keyspace_name").unwrap().as_ptr()); let mut keyspace_name = mem::zeroed(); let mut keyspace_name_length = mem::zeroed(); cass_value_get_string(value, &mut keyspace_name, &mut keyspace_name_length); println!("keyspace_name: {:?}", raw2utf8(keyspace_name, keyspace_name_length)); } cass_result_free(result); cass_iterator_free(rows); } else { // Handle error let mut message = mem::zeroed(); let mut message_length = mem::zeroed(); cass_future_error_message(result_future, &mut message, &mut message_length); println!("Unable to run query: {:?}", raw2utf8(message, message_length)); } cass_statement_free(statement); cass_future_free(result_future); // Close the session let close_future = cass_session_close(session); cass_future_wait(close_future); cass_future_free(close_future); } _ => { // Handle error let mut message = mem::zeroed(); let mut message_length = mem::zeroed(); cass_future_error_message(connect_future, &mut message, &mut message_length); println!("Unable to connect: : {:?}", raw2utf8(message, message_length)); } } cass_future_free(connect_future); cass_cluster_free(cluster); cass_session_free(session); cass_ssl_free(ssl); } }
main
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/. */ //! Animated values. //! //! Some values, notably colors, cannot be interpolated directly with their //! computed values and need yet another intermediate representation. This //! module's raison d'être is to ultimately contain all these types. use app_units::Au; use euclid::{Point2D, Size2D}; use properties::PropertyId; use smallvec::SmallVec; use std::cmp; use values::computed::length::CalcLengthOrPercentage; use values::computed::url::ComputedUrl; use values::computed::Angle as ComputedAngle; use values::computed::BorderCornerRadius as ComputedBorderCornerRadius; pub mod color; pub mod effects; mod font; mod length; mod svg; /// The category a property falls into for ordering purposes. /// /// https://drafts.csswg.org/web-animations/#calculating-computed-keyframes #[derive(Clone, Copy, Eq, Ord, PartialEq, PartialOrd)] enum PropertyCategory { Custom, PhysicalLonghand, LogicalLonghand, Shorthand, } impl PropertyCategory { fn of(id: &PropertyId) -> Self { match *id { PropertyId::Shorthand(..) | PropertyId::ShorthandAlias(..) => { PropertyCategory::Shorthand }, PropertyId::Longhand(id) | PropertyId::LonghandAlias(id,..) => { if id.is_logical() { PropertyCategory::LogicalLonghand } else { PropertyCategory::PhysicalLonghand } }, PropertyId::Custom(..) => PropertyCategory::Custom, } } } /// A comparator to sort PropertyIds such that physical longhands are sorted /// before logical longhands and shorthands, shorthands with fewer components /// are sorted before shorthands with more components, and otherwise shorthands /// are sorted by IDL name as defined by [Web Animations][property-order]. /// /// Using this allows us to prioritize values specified by longhands (or smaller /// shorthand subsets) when longhands and shorthands are both specified on the /// one keyframe. /// /// [property-order] https://drafts.csswg.org/web-animations/#calculating-computed-keyframes pub fn compare_property_priority(a: &PropertyId, b: &PropertyId) -> cmp::Ordering { let a_category = PropertyCategory::of(a); let b_category = PropertyCategory::of(b); if a_category!= b_category { return a_category.cmp(&b_category); } if a_category!= PropertyCategory::Shorthand { return cmp::Ordering::Equal; } let a = a.as_shorthand().unwrap(); let b = b.as_shorthand().unwrap(); // Within shorthands, sort by the number of subproperties, then by IDL // name. let subprop_count_a = a.longhands().count(); let subprop_count_b = b.longhands().count(); subprop_count_a .cmp(&subprop_count_b) .then_with(|| a.idl_name_sort_order().cmp(&b.idl_name_sort_order())) } /// Animate from one value to another. /// /// This trait is derivable with `#[derive(Animate)]`. The derived /// implementation uses a `match` expression with identical patterns for both /// `self` and `other`, calling `Animate::animate` on each fields of the values. /// If a field is annotated with `#[animation(constant)]`, the two values should /// be equal or an error is returned. /// /// If a variant is annotated with `#[animation(error)]`, the corresponding /// `match` arm is not generated. /// /// If the two values are not similar, an error is returned unless a fallback /// function has been specified through `#[animate(fallback)]`. /// /// Trait bounds for type parameter `Foo` can be opted out of with /// `#[animation(no_bound(Foo))]` on the type definition. pub trait Animate: Sized { /// Animate a value towards another one, given an animation procedure. fn animate(&self, other: &Self, procedure: Procedure) -> Result<Self, ()>; } /// An animation procedure. /// /// <https://drafts.csswg.org/web-animations/#procedures-for-animating-properties> #[allow(missing_docs)] #[derive(Clone, Copy, Debug, PartialEq)] pub enum Procedure { /// <https://drafts.csswg.org/web-animations/#animation-interpolation> Interpolate { progress: f64 }, /// <https://drafts.csswg.org/web-animations/#animation-addition> Add, /// <https://drafts.csswg.org/web-animations/#animation-accumulation> Accumulate { count: u64 },
/// /// This trait is derivable with `#[derive(ToAnimatedValue)]`. pub trait ToAnimatedValue { /// The type of the animated value. type AnimatedValue; /// Converts this value to an animated value. fn to_animated_value(self) -> Self::AnimatedValue; /// Converts back an animated value into a computed value. fn from_animated_value(animated: Self::AnimatedValue) -> Self; } /// Returns a value similar to `self` that represents zero. /// /// This trait is derivable with `#[derive(ToAnimatedValue)]`. If a field is /// annotated with `#[animation(constant)]`, a clone of its value will be used /// instead of calling `ToAnimatedZero::to_animated_zero` on it. /// /// If a variant is annotated with `#[animation(error)]`, the corresponding /// `match` arm is not generated. /// /// Trait bounds for type parameter `Foo` can be opted out of with /// `#[animation(no_bound(Foo))]` on the type definition. pub trait ToAnimatedZero: Sized { /// Returns a value that, when added with an underlying value, will produce the underlying /// value. This is used for SMIL animation's "by-animation" where SMIL first interpolates from /// the zero value to the 'by' value, and then adds the result to the underlying value. /// /// This is not the necessarily the same as the initial value of a property. For example, the /// initial value of'stroke-width' is 1, but the zero value is 0, since adding 1 to the /// underlying value will not produce the underlying value. fn to_animated_zero(&self) -> Result<Self, ()>; } impl Procedure { /// Returns this procedure as a pair of weights. /// /// This is useful for animations that don't animate differently /// depending on the used procedure. #[inline] pub fn weights(self) -> (f64, f64) { match self { Procedure::Interpolate { progress } => (1. - progress, progress), Procedure::Add => (1., 1.), Procedure::Accumulate { count } => (count as f64, 1.), } } } /// <https://drafts.csswg.org/css-transitions/#animtype-number> impl Animate for i32 { #[inline] fn animate(&self, other: &Self, procedure: Procedure) -> Result<Self, ()> { Ok(((*self as f64).animate(&(*other as f64), procedure)? + 0.5).floor() as i32) } } /// <https://drafts.csswg.org/css-transitions/#animtype-number> impl Animate for f32 { #[inline] fn animate(&self, other: &Self, procedure: Procedure) -> Result<Self, ()> { use std::f32; let ret = (*self as f64).animate(&(*other as f64), procedure)?; Ok(ret.min(f32::MAX as f64).max(f32::MIN as f64) as f32) } } /// <https://drafts.csswg.org/css-transitions/#animtype-number> impl Animate for f64 { #[inline] fn animate(&self, other: &Self, procedure: Procedure) -> Result<Self, ()> { use std::f64; let (self_weight, other_weight) = procedure.weights(); let ret = *self * self_weight + *other * other_weight; Ok(ret.min(f64::MAX).max(f64::MIN)) } } impl<T> Animate for Option<T> where T: Animate, { #[inline] fn animate(&self, other: &Self, procedure: Procedure) -> Result<Self, ()> { match (self.as_ref(), other.as_ref()) { (Some(ref this), Some(ref other)) => Ok(Some(this.animate(other, procedure)?)), (None, None) => Ok(None), _ => Err(()), } } } impl Animate for Au { #[inline] fn animate(&self, other: &Self, procedure: Procedure) -> Result<Self, ()> { Ok(Au::new(self.0.animate(&other.0, procedure)?)) } } impl<T> Animate for Size2D<T> where T: Animate, { #[inline] fn animate(&self, other: &Self, procedure: Procedure) -> Result<Self, ()> { Ok(Size2D::new( self.width.animate(&other.width, procedure)?, self.height.animate(&other.height, procedure)?, )) } } impl<T> Animate for Point2D<T> where T: Animate, { #[inline] fn animate(&self, other: &Self, procedure: Procedure) -> Result<Self, ()> { Ok(Point2D::new( self.x.animate(&other.x, procedure)?, self.y.animate(&other.y, procedure)?, )) } } impl<T> ToAnimatedValue for Option<T> where T: ToAnimatedValue, { type AnimatedValue = Option<<T as ToAnimatedValue>::AnimatedValue>; #[inline] fn to_animated_value(self) -> Self::AnimatedValue { self.map(T::to_animated_value) } #[inline] fn from_animated_value(animated: Self::AnimatedValue) -> Self { animated.map(T::from_animated_value) } } impl<T> ToAnimatedValue for Vec<T> where T: ToAnimatedValue, { type AnimatedValue = Vec<<T as ToAnimatedValue>::AnimatedValue>; #[inline] fn to_animated_value(self) -> Self::AnimatedValue { self.into_iter().map(T::to_animated_value).collect() } #[inline] fn from_animated_value(animated: Self::AnimatedValue) -> Self { animated.into_iter().map(T::from_animated_value).collect() } } impl<T> ToAnimatedValue for SmallVec<[T; 1]> where T: ToAnimatedValue, { type AnimatedValue = SmallVec<[T::AnimatedValue; 1]>; #[inline] fn to_animated_value(self) -> Self::AnimatedValue { self.into_iter().map(T::to_animated_value).collect() } #[inline] fn from_animated_value(animated: Self::AnimatedValue) -> Self { animated.into_iter().map(T::from_animated_value).collect() } } macro_rules! trivial_to_animated_value { ($ty:ty) => { impl $crate::values::animated::ToAnimatedValue for $ty { type AnimatedValue = Self; #[inline] fn to_animated_value(self) -> Self { self } #[inline] fn from_animated_value(animated: Self::AnimatedValue) -> Self { animated } } }; } trivial_to_animated_value!(Au); trivial_to_animated_value!(CalcLengthOrPercentage); trivial_to_animated_value!(ComputedAngle); trivial_to_animated_value!(ComputedUrl); trivial_to_animated_value!(bool); trivial_to_animated_value!(f32); impl ToAnimatedValue for ComputedBorderCornerRadius { type AnimatedValue = Self; #[inline] fn to_animated_value(self) -> Self { self } #[inline] fn from_animated_value(animated: Self::AnimatedValue) -> Self { ComputedBorderCornerRadius::new( (animated.0).0.width.clamp_to_non_negative(), (animated.0).0.height.clamp_to_non_negative(), ) } } impl ToAnimatedZero for Au { #[inline] fn to_animated_zero(&self) -> Result<Self, ()> { Ok(Au(0)) } } impl ToAnimatedZero for f32 { #[inline] fn to_animated_zero(&self) -> Result<Self, ()> { Ok(0.) } } impl ToAnimatedZero for f64 { #[inline] fn to_animated_zero(&self) -> Result<Self, ()> { Ok(0.) } } impl ToAnimatedZero for i32 { #[inline] fn to_animated_zero(&self) -> Result<Self, ()> { Ok(0) } } impl<T> ToAnimatedZero for Option<T> where T: ToAnimatedZero, { #[inline] fn to_animated_zero(&self) -> Result<Self, ()> { match *self { Some(ref value) => Ok(Some(value.to_animated_zero()?)), None => Ok(None), } } } impl<T> ToAnimatedZero for Size2D<T> where T: ToAnimatedZero, { #[inline] fn to_animated_zero(&self) -> Result<Self, ()> { Ok(Size2D::new( self.width.to_animated_zero()?, self.height.to_animated_zero()?, )) } } impl<T> ToAnimatedZero for Box<[T]> where T: ToAnimatedZero, { #[inline] fn to_animated_zero(&self) -> Result<Self, ()> { let v = self .iter() .map(|v| v.to_animated_zero()) .collect::<Result<Vec<_>, _>>()?; Ok(v.into_boxed_slice()) } }
} /// Conversion between computed values and intermediate values for animations. /// /// Notably, colors are represented as four floats during animations.
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/. */ //! Animated values. //! //! Some values, notably colors, cannot be interpolated directly with their //! computed values and need yet another intermediate representation. This //! module's raison d'être is to ultimately contain all these types. use app_units::Au; use euclid::{Point2D, Size2D}; use properties::PropertyId; use smallvec::SmallVec; use std::cmp; use values::computed::length::CalcLengthOrPercentage; use values::computed::url::ComputedUrl; use values::computed::Angle as ComputedAngle; use values::computed::BorderCornerRadius as ComputedBorderCornerRadius; pub mod color; pub mod effects; mod font; mod length; mod svg; /// The category a property falls into for ordering purposes. /// /// https://drafts.csswg.org/web-animations/#calculating-computed-keyframes #[derive(Clone, Copy, Eq, Ord, PartialEq, PartialOrd)] enum PropertyCategory { Custom, PhysicalLonghand, LogicalLonghand, Shorthand, } impl PropertyCategory { fn of(id: &PropertyId) -> Self { match *id { PropertyId::Shorthand(..) | PropertyId::ShorthandAlias(..) => { PropertyCategory::Shorthand }, PropertyId::Longhand(id) | PropertyId::LonghandAlias(id,..) => { if id.is_logical() { PropertyCategory::LogicalLonghand } else { PropertyCategory::PhysicalLonghand } }, PropertyId::Custom(..) => PropertyCategory::Custom, } } } /// A comparator to sort PropertyIds such that physical longhands are sorted /// before logical longhands and shorthands, shorthands with fewer components /// are sorted before shorthands with more components, and otherwise shorthands /// are sorted by IDL name as defined by [Web Animations][property-order]. /// /// Using this allows us to prioritize values specified by longhands (or smaller /// shorthand subsets) when longhands and shorthands are both specified on the /// one keyframe. /// /// [property-order] https://drafts.csswg.org/web-animations/#calculating-computed-keyframes pub fn compare_property_priority(a: &PropertyId, b: &PropertyId) -> cmp::Ordering { let a_category = PropertyCategory::of(a); let b_category = PropertyCategory::of(b); if a_category!= b_category { return a_category.cmp(&b_category); } if a_category!= PropertyCategory::Shorthand {
let a = a.as_shorthand().unwrap(); let b = b.as_shorthand().unwrap(); // Within shorthands, sort by the number of subproperties, then by IDL // name. let subprop_count_a = a.longhands().count(); let subprop_count_b = b.longhands().count(); subprop_count_a .cmp(&subprop_count_b) .then_with(|| a.idl_name_sort_order().cmp(&b.idl_name_sort_order())) } /// Animate from one value to another. /// /// This trait is derivable with `#[derive(Animate)]`. The derived /// implementation uses a `match` expression with identical patterns for both /// `self` and `other`, calling `Animate::animate` on each fields of the values. /// If a field is annotated with `#[animation(constant)]`, the two values should /// be equal or an error is returned. /// /// If a variant is annotated with `#[animation(error)]`, the corresponding /// `match` arm is not generated. /// /// If the two values are not similar, an error is returned unless a fallback /// function has been specified through `#[animate(fallback)]`. /// /// Trait bounds for type parameter `Foo` can be opted out of with /// `#[animation(no_bound(Foo))]` on the type definition. pub trait Animate: Sized { /// Animate a value towards another one, given an animation procedure. fn animate(&self, other: &Self, procedure: Procedure) -> Result<Self, ()>; } /// An animation procedure. /// /// <https://drafts.csswg.org/web-animations/#procedures-for-animating-properties> #[allow(missing_docs)] #[derive(Clone, Copy, Debug, PartialEq)] pub enum Procedure { /// <https://drafts.csswg.org/web-animations/#animation-interpolation> Interpolate { progress: f64 }, /// <https://drafts.csswg.org/web-animations/#animation-addition> Add, /// <https://drafts.csswg.org/web-animations/#animation-accumulation> Accumulate { count: u64 }, } /// Conversion between computed values and intermediate values for animations. /// /// Notably, colors are represented as four floats during animations. /// /// This trait is derivable with `#[derive(ToAnimatedValue)]`. pub trait ToAnimatedValue { /// The type of the animated value. type AnimatedValue; /// Converts this value to an animated value. fn to_animated_value(self) -> Self::AnimatedValue; /// Converts back an animated value into a computed value. fn from_animated_value(animated: Self::AnimatedValue) -> Self; } /// Returns a value similar to `self` that represents zero. /// /// This trait is derivable with `#[derive(ToAnimatedValue)]`. If a field is /// annotated with `#[animation(constant)]`, a clone of its value will be used /// instead of calling `ToAnimatedZero::to_animated_zero` on it. /// /// If a variant is annotated with `#[animation(error)]`, the corresponding /// `match` arm is not generated. /// /// Trait bounds for type parameter `Foo` can be opted out of with /// `#[animation(no_bound(Foo))]` on the type definition. pub trait ToAnimatedZero: Sized { /// Returns a value that, when added with an underlying value, will produce the underlying /// value. This is used for SMIL animation's "by-animation" where SMIL first interpolates from /// the zero value to the 'by' value, and then adds the result to the underlying value. /// /// This is not the necessarily the same as the initial value of a property. For example, the /// initial value of'stroke-width' is 1, but the zero value is 0, since adding 1 to the /// underlying value will not produce the underlying value. fn to_animated_zero(&self) -> Result<Self, ()>; } impl Procedure { /// Returns this procedure as a pair of weights. /// /// This is useful for animations that don't animate differently /// depending on the used procedure. #[inline] pub fn weights(self) -> (f64, f64) { match self { Procedure::Interpolate { progress } => (1. - progress, progress), Procedure::Add => (1., 1.), Procedure::Accumulate { count } => (count as f64, 1.), } } } /// <https://drafts.csswg.org/css-transitions/#animtype-number> impl Animate for i32 { #[inline] fn animate(&self, other: &Self, procedure: Procedure) -> Result<Self, ()> { Ok(((*self as f64).animate(&(*other as f64), procedure)? + 0.5).floor() as i32) } } /// <https://drafts.csswg.org/css-transitions/#animtype-number> impl Animate for f32 { #[inline] fn animate(&self, other: &Self, procedure: Procedure) -> Result<Self, ()> { use std::f32; let ret = (*self as f64).animate(&(*other as f64), procedure)?; Ok(ret.min(f32::MAX as f64).max(f32::MIN as f64) as f32) } } /// <https://drafts.csswg.org/css-transitions/#animtype-number> impl Animate for f64 { #[inline] fn animate(&self, other: &Self, procedure: Procedure) -> Result<Self, ()> { use std::f64; let (self_weight, other_weight) = procedure.weights(); let ret = *self * self_weight + *other * other_weight; Ok(ret.min(f64::MAX).max(f64::MIN)) } } impl<T> Animate for Option<T> where T: Animate, { #[inline] fn animate(&self, other: &Self, procedure: Procedure) -> Result<Self, ()> { match (self.as_ref(), other.as_ref()) { (Some(ref this), Some(ref other)) => Ok(Some(this.animate(other, procedure)?)), (None, None) => Ok(None), _ => Err(()), } } } impl Animate for Au { #[inline] fn animate(&self, other: &Self, procedure: Procedure) -> Result<Self, ()> { Ok(Au::new(self.0.animate(&other.0, procedure)?)) } } impl<T> Animate for Size2D<T> where T: Animate, { #[inline] fn animate(&self, other: &Self, procedure: Procedure) -> Result<Self, ()> { Ok(Size2D::new( self.width.animate(&other.width, procedure)?, self.height.animate(&other.height, procedure)?, )) } } impl<T> Animate for Point2D<T> where T: Animate, { #[inline] fn animate(&self, other: &Self, procedure: Procedure) -> Result<Self, ()> { Ok(Point2D::new( self.x.animate(&other.x, procedure)?, self.y.animate(&other.y, procedure)?, )) } } impl<T> ToAnimatedValue for Option<T> where T: ToAnimatedValue, { type AnimatedValue = Option<<T as ToAnimatedValue>::AnimatedValue>; #[inline] fn to_animated_value(self) -> Self::AnimatedValue { self.map(T::to_animated_value) } #[inline] fn from_animated_value(animated: Self::AnimatedValue) -> Self { animated.map(T::from_animated_value) } } impl<T> ToAnimatedValue for Vec<T> where T: ToAnimatedValue, { type AnimatedValue = Vec<<T as ToAnimatedValue>::AnimatedValue>; #[inline] fn to_animated_value(self) -> Self::AnimatedValue { self.into_iter().map(T::to_animated_value).collect() } #[inline] fn from_animated_value(animated: Self::AnimatedValue) -> Self { animated.into_iter().map(T::from_animated_value).collect() } } impl<T> ToAnimatedValue for SmallVec<[T; 1]> where T: ToAnimatedValue, { type AnimatedValue = SmallVec<[T::AnimatedValue; 1]>; #[inline] fn to_animated_value(self) -> Self::AnimatedValue { self.into_iter().map(T::to_animated_value).collect() } #[inline] fn from_animated_value(animated: Self::AnimatedValue) -> Self { animated.into_iter().map(T::from_animated_value).collect() } } macro_rules! trivial_to_animated_value { ($ty:ty) => { impl $crate::values::animated::ToAnimatedValue for $ty { type AnimatedValue = Self; #[inline] fn to_animated_value(self) -> Self { self } #[inline] fn from_animated_value(animated: Self::AnimatedValue) -> Self { animated } } }; } trivial_to_animated_value!(Au); trivial_to_animated_value!(CalcLengthOrPercentage); trivial_to_animated_value!(ComputedAngle); trivial_to_animated_value!(ComputedUrl); trivial_to_animated_value!(bool); trivial_to_animated_value!(f32); impl ToAnimatedValue for ComputedBorderCornerRadius { type AnimatedValue = Self; #[inline] fn to_animated_value(self) -> Self { self } #[inline] fn from_animated_value(animated: Self::AnimatedValue) -> Self { ComputedBorderCornerRadius::new( (animated.0).0.width.clamp_to_non_negative(), (animated.0).0.height.clamp_to_non_negative(), ) } } impl ToAnimatedZero for Au { #[inline] fn to_animated_zero(&self) -> Result<Self, ()> { Ok(Au(0)) } } impl ToAnimatedZero for f32 { #[inline] fn to_animated_zero(&self) -> Result<Self, ()> { Ok(0.) } } impl ToAnimatedZero for f64 { #[inline] fn to_animated_zero(&self) -> Result<Self, ()> { Ok(0.) } } impl ToAnimatedZero for i32 { #[inline] fn to_animated_zero(&self) -> Result<Self, ()> { Ok(0) } } impl<T> ToAnimatedZero for Option<T> where T: ToAnimatedZero, { #[inline] fn to_animated_zero(&self) -> Result<Self, ()> { match *self { Some(ref value) => Ok(Some(value.to_animated_zero()?)), None => Ok(None), } } } impl<T> ToAnimatedZero for Size2D<T> where T: ToAnimatedZero, { #[inline] fn to_animated_zero(&self) -> Result<Self, ()> { Ok(Size2D::new( self.width.to_animated_zero()?, self.height.to_animated_zero()?, )) } } impl<T> ToAnimatedZero for Box<[T]> where T: ToAnimatedZero, { #[inline] fn to_animated_zero(&self) -> Result<Self, ()> { let v = self .iter() .map(|v| v.to_animated_zero()) .collect::<Result<Vec<_>, _>>()?; Ok(v.into_boxed_slice()) } }
return cmp::Ordering::Equal; }
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/. */ //! Animated values. //! //! Some values, notably colors, cannot be interpolated directly with their //! computed values and need yet another intermediate representation. This //! module's raison d'être is to ultimately contain all these types. use app_units::Au; use euclid::{Point2D, Size2D}; use properties::PropertyId; use smallvec::SmallVec; use std::cmp; use values::computed::length::CalcLengthOrPercentage; use values::computed::url::ComputedUrl; use values::computed::Angle as ComputedAngle; use values::computed::BorderCornerRadius as ComputedBorderCornerRadius; pub mod color; pub mod effects; mod font; mod length; mod svg; /// The category a property falls into for ordering purposes. /// /// https://drafts.csswg.org/web-animations/#calculating-computed-keyframes #[derive(Clone, Copy, Eq, Ord, PartialEq, PartialOrd)] enum PropertyCategory { Custom, PhysicalLonghand, LogicalLonghand, Shorthand, } impl PropertyCategory { fn of(id: &PropertyId) -> Self { match *id { PropertyId::Shorthand(..) | PropertyId::ShorthandAlias(..) => { PropertyCategory::Shorthand }, PropertyId::Longhand(id) | PropertyId::LonghandAlias(id,..) => { if id.is_logical() { PropertyCategory::LogicalLonghand } else { PropertyCategory::PhysicalLonghand } }, PropertyId::Custom(..) => PropertyCategory::Custom, } } } /// A comparator to sort PropertyIds such that physical longhands are sorted /// before logical longhands and shorthands, shorthands with fewer components /// are sorted before shorthands with more components, and otherwise shorthands /// are sorted by IDL name as defined by [Web Animations][property-order]. /// /// Using this allows us to prioritize values specified by longhands (or smaller /// shorthand subsets) when longhands and shorthands are both specified on the /// one keyframe. /// /// [property-order] https://drafts.csswg.org/web-animations/#calculating-computed-keyframes pub fn compare_property_priority(a: &PropertyId, b: &PropertyId) -> cmp::Ordering { let a_category = PropertyCategory::of(a); let b_category = PropertyCategory::of(b); if a_category!= b_category { return a_category.cmp(&b_category); } if a_category!= PropertyCategory::Shorthand { return cmp::Ordering::Equal; } let a = a.as_shorthand().unwrap(); let b = b.as_shorthand().unwrap(); // Within shorthands, sort by the number of subproperties, then by IDL // name. let subprop_count_a = a.longhands().count(); let subprop_count_b = b.longhands().count(); subprop_count_a .cmp(&subprop_count_b) .then_with(|| a.idl_name_sort_order().cmp(&b.idl_name_sort_order())) } /// Animate from one value to another. /// /// This trait is derivable with `#[derive(Animate)]`. The derived /// implementation uses a `match` expression with identical patterns for both /// `self` and `other`, calling `Animate::animate` on each fields of the values. /// If a field is annotated with `#[animation(constant)]`, the two values should /// be equal or an error is returned. /// /// If a variant is annotated with `#[animation(error)]`, the corresponding /// `match` arm is not generated. /// /// If the two values are not similar, an error is returned unless a fallback /// function has been specified through `#[animate(fallback)]`. /// /// Trait bounds for type parameter `Foo` can be opted out of with /// `#[animation(no_bound(Foo))]` on the type definition. pub trait Animate: Sized { /// Animate a value towards another one, given an animation procedure. fn animate(&self, other: &Self, procedure: Procedure) -> Result<Self, ()>; } /// An animation procedure. /// /// <https://drafts.csswg.org/web-animations/#procedures-for-animating-properties> #[allow(missing_docs)] #[derive(Clone, Copy, Debug, PartialEq)] pub enum Procedure { /// <https://drafts.csswg.org/web-animations/#animation-interpolation> Interpolate { progress: f64 }, /// <https://drafts.csswg.org/web-animations/#animation-addition> Add, /// <https://drafts.csswg.org/web-animations/#animation-accumulation> Accumulate { count: u64 }, } /// Conversion between computed values and intermediate values for animations. /// /// Notably, colors are represented as four floats during animations. /// /// This trait is derivable with `#[derive(ToAnimatedValue)]`. pub trait ToAnimatedValue { /// The type of the animated value. type AnimatedValue; /// Converts this value to an animated value. fn to_animated_value(self) -> Self::AnimatedValue; /// Converts back an animated value into a computed value. fn from_animated_value(animated: Self::AnimatedValue) -> Self; } /// Returns a value similar to `self` that represents zero. /// /// This trait is derivable with `#[derive(ToAnimatedValue)]`. If a field is /// annotated with `#[animation(constant)]`, a clone of its value will be used /// instead of calling `ToAnimatedZero::to_animated_zero` on it. /// /// If a variant is annotated with `#[animation(error)]`, the corresponding /// `match` arm is not generated. /// /// Trait bounds for type parameter `Foo` can be opted out of with /// `#[animation(no_bound(Foo))]` on the type definition. pub trait ToAnimatedZero: Sized { /// Returns a value that, when added with an underlying value, will produce the underlying /// value. This is used for SMIL animation's "by-animation" where SMIL first interpolates from /// the zero value to the 'by' value, and then adds the result to the underlying value. /// /// This is not the necessarily the same as the initial value of a property. For example, the /// initial value of'stroke-width' is 1, but the zero value is 0, since adding 1 to the /// underlying value will not produce the underlying value. fn to_animated_zero(&self) -> Result<Self, ()>; } impl Procedure { /// Returns this procedure as a pair of weights. /// /// This is useful for animations that don't animate differently /// depending on the used procedure. #[inline] pub fn weights(self) -> (f64, f64) { match self { Procedure::Interpolate { progress } => (1. - progress, progress), Procedure::Add => (1., 1.), Procedure::Accumulate { count } => (count as f64, 1.), } } } /// <https://drafts.csswg.org/css-transitions/#animtype-number> impl Animate for i32 { #[inline] fn animate(&self, other: &Self, procedure: Procedure) -> Result<Self, ()> { Ok(((*self as f64).animate(&(*other as f64), procedure)? + 0.5).floor() as i32) } } /// <https://drafts.csswg.org/css-transitions/#animtype-number> impl Animate for f32 { #[inline] fn animate(&self, other: &Self, procedure: Procedure) -> Result<Self, ()> { use std::f32; let ret = (*self as f64).animate(&(*other as f64), procedure)?; Ok(ret.min(f32::MAX as f64).max(f32::MIN as f64) as f32) } } /// <https://drafts.csswg.org/css-transitions/#animtype-number> impl Animate for f64 { #[inline] fn animate(&self, other: &Self, procedure: Procedure) -> Result<Self, ()> { use std::f64; let (self_weight, other_weight) = procedure.weights(); let ret = *self * self_weight + *other * other_weight; Ok(ret.min(f64::MAX).max(f64::MIN)) } } impl<T> Animate for Option<T> where T: Animate, { #[inline] fn animate(&self, other: &Self, procedure: Procedure) -> Result<Self, ()> { match (self.as_ref(), other.as_ref()) { (Some(ref this), Some(ref other)) => Ok(Some(this.animate(other, procedure)?)), (None, None) => Ok(None), _ => Err(()), } } } impl Animate for Au { #[inline] fn animate(&self, other: &Self, procedure: Procedure) -> Result<Self, ()> { Ok(Au::new(self.0.animate(&other.0, procedure)?)) } } impl<T> Animate for Size2D<T> where T: Animate, { #[inline] fn animate(&self, other: &Self, procedure: Procedure) -> Result<Self, ()> { Ok(Size2D::new( self.width.animate(&other.width, procedure)?, self.height.animate(&other.height, procedure)?, )) } } impl<T> Animate for Point2D<T> where T: Animate, { #[inline] fn animate(&self, other: &Self, procedure: Procedure) -> Result<Self, ()> { Ok(Point2D::new( self.x.animate(&other.x, procedure)?, self.y.animate(&other.y, procedure)?, )) } } impl<T> ToAnimatedValue for Option<T> where T: ToAnimatedValue, { type AnimatedValue = Option<<T as ToAnimatedValue>::AnimatedValue>; #[inline] fn to_animated_value(self) -> Self::AnimatedValue { self.map(T::to_animated_value) } #[inline] fn from_animated_value(animated: Self::AnimatedValue) -> Self { animated.map(T::from_animated_value) } } impl<T> ToAnimatedValue for Vec<T> where T: ToAnimatedValue, { type AnimatedValue = Vec<<T as ToAnimatedValue>::AnimatedValue>; #[inline] fn to_animated_value(self) -> Self::AnimatedValue { self.into_iter().map(T::to_animated_value).collect() } #[inline] fn from_animated_value(animated: Self::AnimatedValue) -> Self { animated.into_iter().map(T::from_animated_value).collect() } } impl<T> ToAnimatedValue for SmallVec<[T; 1]> where T: ToAnimatedValue, { type AnimatedValue = SmallVec<[T::AnimatedValue; 1]>; #[inline] fn to_animated_value(self) -> Self::AnimatedValue { self.into_iter().map(T::to_animated_value).collect() } #[inline] fn from_animated_value(animated: Self::AnimatedValue) -> Self { animated.into_iter().map(T::from_animated_value).collect() } } macro_rules! trivial_to_animated_value { ($ty:ty) => { impl $crate::values::animated::ToAnimatedValue for $ty { type AnimatedValue = Self; #[inline] fn to_animated_value(self) -> Self { self } #[inline] fn from_animated_value(animated: Self::AnimatedValue) -> Self { animated } } }; } trivial_to_animated_value!(Au); trivial_to_animated_value!(CalcLengthOrPercentage); trivial_to_animated_value!(ComputedAngle); trivial_to_animated_value!(ComputedUrl); trivial_to_animated_value!(bool); trivial_to_animated_value!(f32); impl ToAnimatedValue for ComputedBorderCornerRadius { type AnimatedValue = Self; #[inline] fn to_animated_value(self) -> Self {
#[inline] fn from_animated_value(animated: Self::AnimatedValue) -> Self { ComputedBorderCornerRadius::new( (animated.0).0.width.clamp_to_non_negative(), (animated.0).0.height.clamp_to_non_negative(), ) } } impl ToAnimatedZero for Au { #[inline] fn to_animated_zero(&self) -> Result<Self, ()> { Ok(Au(0)) } } impl ToAnimatedZero for f32 { #[inline] fn to_animated_zero(&self) -> Result<Self, ()> { Ok(0.) } } impl ToAnimatedZero for f64 { #[inline] fn to_animated_zero(&self) -> Result<Self, ()> { Ok(0.) } } impl ToAnimatedZero for i32 { #[inline] fn to_animated_zero(&self) -> Result<Self, ()> { Ok(0) } } impl<T> ToAnimatedZero for Option<T> where T: ToAnimatedZero, { #[inline] fn to_animated_zero(&self) -> Result<Self, ()> { match *self { Some(ref value) => Ok(Some(value.to_animated_zero()?)), None => Ok(None), } } } impl<T> ToAnimatedZero for Size2D<T> where T: ToAnimatedZero, { #[inline] fn to_animated_zero(&self) -> Result<Self, ()> { Ok(Size2D::new( self.width.to_animated_zero()?, self.height.to_animated_zero()?, )) } } impl<T> ToAnimatedZero for Box<[T]> where T: ToAnimatedZero, { #[inline] fn to_animated_zero(&self) -> Result<Self, ()> { let v = self .iter() .map(|v| v.to_animated_zero()) .collect::<Result<Vec<_>, _>>()?; Ok(v.into_boxed_slice()) } }
self }
identifier_body
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/. */ //! Animated values. //! //! Some values, notably colors, cannot be interpolated directly with their //! computed values and need yet another intermediate representation. This //! module's raison d'être is to ultimately contain all these types. use app_units::Au; use euclid::{Point2D, Size2D}; use properties::PropertyId; use smallvec::SmallVec; use std::cmp; use values::computed::length::CalcLengthOrPercentage; use values::computed::url::ComputedUrl; use values::computed::Angle as ComputedAngle; use values::computed::BorderCornerRadius as ComputedBorderCornerRadius; pub mod color; pub mod effects; mod font; mod length; mod svg; /// The category a property falls into for ordering purposes. /// /// https://drafts.csswg.org/web-animations/#calculating-computed-keyframes #[derive(Clone, Copy, Eq, Ord, PartialEq, PartialOrd)] enum PropertyCategory { Custom, PhysicalLonghand, LogicalLonghand, Shorthand, } impl PropertyCategory { fn of(id: &PropertyId) -> Self { match *id { PropertyId::Shorthand(..) | PropertyId::ShorthandAlias(..) => { PropertyCategory::Shorthand }, PropertyId::Longhand(id) | PropertyId::LonghandAlias(id,..) => { if id.is_logical() { PropertyCategory::LogicalLonghand } else { PropertyCategory::PhysicalLonghand } }, PropertyId::Custom(..) => PropertyCategory::Custom, } } } /// A comparator to sort PropertyIds such that physical longhands are sorted /// before logical longhands and shorthands, shorthands with fewer components /// are sorted before shorthands with more components, and otherwise shorthands /// are sorted by IDL name as defined by [Web Animations][property-order]. /// /// Using this allows us to prioritize values specified by longhands (or smaller /// shorthand subsets) when longhands and shorthands are both specified on the /// one keyframe. /// /// [property-order] https://drafts.csswg.org/web-animations/#calculating-computed-keyframes pub fn compare_property_priority(a: &PropertyId, b: &PropertyId) -> cmp::Ordering { let a_category = PropertyCategory::of(a); let b_category = PropertyCategory::of(b); if a_category!= b_category { return a_category.cmp(&b_category); } if a_category!= PropertyCategory::Shorthand { return cmp::Ordering::Equal; } let a = a.as_shorthand().unwrap(); let b = b.as_shorthand().unwrap(); // Within shorthands, sort by the number of subproperties, then by IDL // name. let subprop_count_a = a.longhands().count(); let subprop_count_b = b.longhands().count(); subprop_count_a .cmp(&subprop_count_b) .then_with(|| a.idl_name_sort_order().cmp(&b.idl_name_sort_order())) } /// Animate from one value to another. /// /// This trait is derivable with `#[derive(Animate)]`. The derived /// implementation uses a `match` expression with identical patterns for both /// `self` and `other`, calling `Animate::animate` on each fields of the values. /// If a field is annotated with `#[animation(constant)]`, the two values should /// be equal or an error is returned. /// /// If a variant is annotated with `#[animation(error)]`, the corresponding /// `match` arm is not generated. /// /// If the two values are not similar, an error is returned unless a fallback /// function has been specified through `#[animate(fallback)]`. /// /// Trait bounds for type parameter `Foo` can be opted out of with /// `#[animation(no_bound(Foo))]` on the type definition. pub trait Animate: Sized { /// Animate a value towards another one, given an animation procedure. fn animate(&self, other: &Self, procedure: Procedure) -> Result<Self, ()>; } /// An animation procedure. /// /// <https://drafts.csswg.org/web-animations/#procedures-for-animating-properties> #[allow(missing_docs)] #[derive(Clone, Copy, Debug, PartialEq)] pub enum Procedure { /// <https://drafts.csswg.org/web-animations/#animation-interpolation> Interpolate { progress: f64 }, /// <https://drafts.csswg.org/web-animations/#animation-addition> Add, /// <https://drafts.csswg.org/web-animations/#animation-accumulation> Accumulate { count: u64 }, } /// Conversion between computed values and intermediate values for animations. /// /// Notably, colors are represented as four floats during animations. /// /// This trait is derivable with `#[derive(ToAnimatedValue)]`. pub trait ToAnimatedValue { /// The type of the animated value. type AnimatedValue; /// Converts this value to an animated value. fn to_animated_value(self) -> Self::AnimatedValue; /// Converts back an animated value into a computed value. fn from_animated_value(animated: Self::AnimatedValue) -> Self; } /// Returns a value similar to `self` that represents zero. /// /// This trait is derivable with `#[derive(ToAnimatedValue)]`. If a field is /// annotated with `#[animation(constant)]`, a clone of its value will be used /// instead of calling `ToAnimatedZero::to_animated_zero` on it. /// /// If a variant is annotated with `#[animation(error)]`, the corresponding /// `match` arm is not generated. /// /// Trait bounds for type parameter `Foo` can be opted out of with /// `#[animation(no_bound(Foo))]` on the type definition. pub trait ToAnimatedZero: Sized { /// Returns a value that, when added with an underlying value, will produce the underlying /// value. This is used for SMIL animation's "by-animation" where SMIL first interpolates from /// the zero value to the 'by' value, and then adds the result to the underlying value. /// /// This is not the necessarily the same as the initial value of a property. For example, the /// initial value of'stroke-width' is 1, but the zero value is 0, since adding 1 to the /// underlying value will not produce the underlying value. fn to_animated_zero(&self) -> Result<Self, ()>; } impl Procedure { /// Returns this procedure as a pair of weights. /// /// This is useful for animations that don't animate differently /// depending on the used procedure. #[inline] pub fn weights(self) -> (f64, f64) { match self { Procedure::Interpolate { progress } => (1. - progress, progress), Procedure::Add => (1., 1.), Procedure::Accumulate { count } => (count as f64, 1.), } } } /// <https://drafts.csswg.org/css-transitions/#animtype-number> impl Animate for i32 { #[inline] fn animate(&self, other: &Self, procedure: Procedure) -> Result<Self, ()> { Ok(((*self as f64).animate(&(*other as f64), procedure)? + 0.5).floor() as i32) } } /// <https://drafts.csswg.org/css-transitions/#animtype-number> impl Animate for f32 { #[inline] fn animate(&self, other: &Self, procedure: Procedure) -> Result<Self, ()> { use std::f32; let ret = (*self as f64).animate(&(*other as f64), procedure)?; Ok(ret.min(f32::MAX as f64).max(f32::MIN as f64) as f32) } } /// <https://drafts.csswg.org/css-transitions/#animtype-number> impl Animate for f64 { #[inline] fn animate(&self, other: &Self, procedure: Procedure) -> Result<Self, ()> { use std::f64; let (self_weight, other_weight) = procedure.weights(); let ret = *self * self_weight + *other * other_weight; Ok(ret.min(f64::MAX).max(f64::MIN)) } } impl<T> Animate for Option<T> where T: Animate, { #[inline] fn animate(&self, other: &Self, procedure: Procedure) -> Result<Self, ()> { match (self.as_ref(), other.as_ref()) { (Some(ref this), Some(ref other)) => Ok(Some(this.animate(other, procedure)?)), (None, None) => Ok(None), _ => Err(()), } } } impl Animate for Au { #[inline] fn animate(&self, other: &Self, procedure: Procedure) -> Result<Self, ()> { Ok(Au::new(self.0.animate(&other.0, procedure)?)) } } impl<T> Animate for Size2D<T> where T: Animate, { #[inline] fn animate(&self, other: &Self, procedure: Procedure) -> Result<Self, ()> { Ok(Size2D::new( self.width.animate(&other.width, procedure)?, self.height.animate(&other.height, procedure)?, )) } } impl<T> Animate for Point2D<T> where T: Animate, { #[inline] fn animate(&self, other: &Self, procedure: Procedure) -> Result<Self, ()> { Ok(Point2D::new( self.x.animate(&other.x, procedure)?, self.y.animate(&other.y, procedure)?, )) } } impl<T> ToAnimatedValue for Option<T> where T: ToAnimatedValue, { type AnimatedValue = Option<<T as ToAnimatedValue>::AnimatedValue>; #[inline] fn to_animated_value(self) -> Self::AnimatedValue { self.map(T::to_animated_value) } #[inline] fn from_animated_value(animated: Self::AnimatedValue) -> Self { animated.map(T::from_animated_value) } } impl<T> ToAnimatedValue for Vec<T> where T: ToAnimatedValue, { type AnimatedValue = Vec<<T as ToAnimatedValue>::AnimatedValue>; #[inline] fn to_animated_value(self) -> Self::AnimatedValue { self.into_iter().map(T::to_animated_value).collect() } #[inline] fn from_animated_value(animated: Self::AnimatedValue) -> Self { animated.into_iter().map(T::from_animated_value).collect() } } impl<T> ToAnimatedValue for SmallVec<[T; 1]> where T: ToAnimatedValue, { type AnimatedValue = SmallVec<[T::AnimatedValue; 1]>; #[inline] fn to_animated_value(self) -> Self::AnimatedValue { self.into_iter().map(T::to_animated_value).collect() } #[inline] fn from_animated_value(animated: Self::AnimatedValue) -> Self { animated.into_iter().map(T::from_animated_value).collect() } } macro_rules! trivial_to_animated_value { ($ty:ty) => { impl $crate::values::animated::ToAnimatedValue for $ty { type AnimatedValue = Self; #[inline] fn to_animated_value(self) -> Self { self } #[inline] fn from_animated_value(animated: Self::AnimatedValue) -> Self { animated } } }; } trivial_to_animated_value!(Au); trivial_to_animated_value!(CalcLengthOrPercentage); trivial_to_animated_value!(ComputedAngle); trivial_to_animated_value!(ComputedUrl); trivial_to_animated_value!(bool); trivial_to_animated_value!(f32); impl ToAnimatedValue for ComputedBorderCornerRadius { type AnimatedValue = Self; #[inline] fn to_animated_value(self) -> Self { self } #[inline] fn from_animated_value(animated: Self::AnimatedValue) -> Self { ComputedBorderCornerRadius::new( (animated.0).0.width.clamp_to_non_negative(), (animated.0).0.height.clamp_to_non_negative(), ) } } impl ToAnimatedZero for Au { #[inline] fn to_animated_zero(&self) -> Result<Self, ()> { Ok(Au(0)) } } impl ToAnimatedZero for f32 { #[inline] fn to_animated_zero(&self) -> Result<Self, ()> { Ok(0.) } } impl ToAnimatedZero for f64 { #[inline] fn to_animated_zero(&self) -> Result<Self, ()> { Ok(0.) } } impl ToAnimatedZero for i32 { #[inline] fn t
&self) -> Result<Self, ()> { Ok(0) } } impl<T> ToAnimatedZero for Option<T> where T: ToAnimatedZero, { #[inline] fn to_animated_zero(&self) -> Result<Self, ()> { match *self { Some(ref value) => Ok(Some(value.to_animated_zero()?)), None => Ok(None), } } } impl<T> ToAnimatedZero for Size2D<T> where T: ToAnimatedZero, { #[inline] fn to_animated_zero(&self) -> Result<Self, ()> { Ok(Size2D::new( self.width.to_animated_zero()?, self.height.to_animated_zero()?, )) } } impl<T> ToAnimatedZero for Box<[T]> where T: ToAnimatedZero, { #[inline] fn to_animated_zero(&self) -> Result<Self, ()> { let v = self .iter() .map(|v| v.to_animated_zero()) .collect::<Result<Vec<_>, _>>()?; Ok(v.into_boxed_slice()) } }
o_animated_zero(
identifier_name
main.rs
#![deny( missing_debug_implementations, missing_copy_implementations, warnings, trivial_numeric_casts, unstable_features, unused, future_incompatible )] use actix_web::server; use anyhow::Result; use log::info; use potboiler_common::pg; use std::env; fn main() -> Result<()>
{ log4rs::init_file("log.yaml", Default::default()).expect("log config ok"); let db_url: &str = &env::var("DATABASE_URL").expect("Needed DATABASE_URL"); let pool = pg::get_pool(db_url).unwrap(); let app_state = pigtail::AppState::new(pool)?; let port: u16 = env::var("PORT") .unwrap_or_else(|_| "8000".to_string()) .parse::<u16>() .unwrap(); server::new(move || pigtail::app_router(app_state.clone()).unwrap().finish()) .bind(("0.0.0.0", port)) .unwrap() .run(); pigtail::register(); info!("Pigtail booted"); Ok(()) }
identifier_body
main.rs
#![deny( missing_debug_implementations, missing_copy_implementations, warnings, trivial_numeric_casts, unstable_features, unused, future_incompatible )] use actix_web::server; use anyhow::Result; use log::info; use potboiler_common::pg; use std::env; fn
() -> Result<()> { log4rs::init_file("log.yaml", Default::default()).expect("log config ok"); let db_url: &str = &env::var("DATABASE_URL").expect("Needed DATABASE_URL"); let pool = pg::get_pool(db_url).unwrap(); let app_state = pigtail::AppState::new(pool)?; let port: u16 = env::var("PORT") .unwrap_or_else(|_| "8000".to_string()) .parse::<u16>() .unwrap(); server::new(move || pigtail::app_router(app_state.clone()).unwrap().finish()) .bind(("0.0.0.0", port)) .unwrap() .run(); pigtail::register(); info!("Pigtail booted"); Ok(()) }
main
identifier_name
main.rs
#![deny( missing_debug_implementations, missing_copy_implementations, warnings, trivial_numeric_casts, unstable_features, unused, future_incompatible )] use actix_web::server; use anyhow::Result; use log::info; use potboiler_common::pg; use std::env; fn main() -> Result<()> { log4rs::init_file("log.yaml", Default::default()).expect("log config ok"); let db_url: &str = &env::var("DATABASE_URL").expect("Needed DATABASE_URL"); let pool = pg::get_pool(db_url).unwrap(); let app_state = pigtail::AppState::new(pool)?; let port: u16 = env::var("PORT") .unwrap_or_else(|_| "8000".to_string()) .parse::<u16>() .unwrap(); server::new(move || pigtail::app_router(app_state.clone()).unwrap().finish())
.unwrap() .run(); pigtail::register(); info!("Pigtail booted"); Ok(()) }
.bind(("0.0.0.0", port))
random_line_split
aggregate_kernels.rs
// Licensed to the Apache Software Foundation (ASF) under one // or more contributor license agreements. See the NOTICE file // distributed with this work for additional information // regarding copyright ownership. The ASF licenses this file // to you 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. #[macro_use] extern crate criterion; use criterion::Criterion; use rand::{distributions::Alphanumeric, Rng}; extern crate arrow; use arrow::array::*; use arrow::compute::kernels::aggregate::*; use arrow::util::test_util::seedable_rng; fn create_array(size: usize, with_nulls: bool) -> Float32Array { // use random numbers to avoid spurious compiler optimizations wrt to branching let mut rng = seedable_rng(); let mut builder = Float32Builder::new(size); for _ in 0..size { if with_nulls && rng.gen::<f32>() > 0.5 { builder.append_null().unwrap(); } else
} builder.finish() } fn create_string_array(size: usize, with_nulls: bool) -> StringArray { // use random numbers to avoid spurious compiler optimizations wrt to branching let mut rng = seedable_rng(); let mut builder = StringBuilder::new(size); for _ in 0..size { if with_nulls && rng.gen::<f32>() > 0.5 { builder.append_null().unwrap(); } else { let string = seedable_rng() .sample_iter(&Alphanumeric) .take(10) .collect::<String>(); builder.append_value(&string).unwrap(); } } builder.finish() } fn bench_sum(arr_a: &Float32Array) { criterion::black_box(sum(&arr_a).unwrap()); } fn bench_min(arr_a: &Float32Array) { criterion::black_box(min(&arr_a).unwrap()); } fn bench_min_string(arr_a: &StringArray) { criterion::black_box(min_string(&arr_a).unwrap()); } fn add_benchmark(c: &mut Criterion) { let arr_a = create_array(512, false); c.bench_function("sum 512", |b| b.iter(|| bench_sum(&arr_a))); c.bench_function("min 512", |b| b.iter(|| bench_min(&arr_a))); let arr_a = create_array(512, true); c.bench_function("sum nulls 512", |b| b.iter(|| bench_sum(&arr_a))); c.bench_function("min nulls 512", |b| b.iter(|| bench_min(&arr_a))); let arr_b = create_string_array(512, false); c.bench_function("min string 512", |b| b.iter(|| bench_min_string(&arr_b))); let arr_b = create_string_array(512, true); c.bench_function("min nulls string 512", |b| { b.iter(|| bench_min_string(&arr_b)) }); } criterion_group!(benches, add_benchmark); criterion_main!(benches);
{ builder.append_value(rng.gen()).unwrap(); }
conditional_block
aggregate_kernels.rs
// Licensed to the Apache Software Foundation (ASF) under one // or more contributor license agreements. See the NOTICE file // distributed with this work for additional information // regarding copyright ownership. The ASF licenses this file // to you 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. #[macro_use] extern crate criterion; use criterion::Criterion; use rand::{distributions::Alphanumeric, Rng}; extern crate arrow; use arrow::array::*; use arrow::compute::kernels::aggregate::*; use arrow::util::test_util::seedable_rng; fn create_array(size: usize, with_nulls: bool) -> Float32Array { // use random numbers to avoid spurious compiler optimizations wrt to branching let mut rng = seedable_rng(); let mut builder = Float32Builder::new(size); for _ in 0..size { if with_nulls && rng.gen::<f32>() > 0.5 { builder.append_null().unwrap(); } else { builder.append_value(rng.gen()).unwrap(); } } builder.finish() } fn create_string_array(size: usize, with_nulls: bool) -> StringArray { // use random numbers to avoid spurious compiler optimizations wrt to branching let mut rng = seedable_rng(); let mut builder = StringBuilder::new(size); for _ in 0..size { if with_nulls && rng.gen::<f32>() > 0.5 { builder.append_null().unwrap(); } else { let string = seedable_rng() .sample_iter(&Alphanumeric) .take(10) .collect::<String>(); builder.append_value(&string).unwrap(); } } builder.finish() } fn
(arr_a: &Float32Array) { criterion::black_box(sum(&arr_a).unwrap()); } fn bench_min(arr_a: &Float32Array) { criterion::black_box(min(&arr_a).unwrap()); } fn bench_min_string(arr_a: &StringArray) { criterion::black_box(min_string(&arr_a).unwrap()); } fn add_benchmark(c: &mut Criterion) { let arr_a = create_array(512, false); c.bench_function("sum 512", |b| b.iter(|| bench_sum(&arr_a))); c.bench_function("min 512", |b| b.iter(|| bench_min(&arr_a))); let arr_a = create_array(512, true); c.bench_function("sum nulls 512", |b| b.iter(|| bench_sum(&arr_a))); c.bench_function("min nulls 512", |b| b.iter(|| bench_min(&arr_a))); let arr_b = create_string_array(512, false); c.bench_function("min string 512", |b| b.iter(|| bench_min_string(&arr_b))); let arr_b = create_string_array(512, true); c.bench_function("min nulls string 512", |b| { b.iter(|| bench_min_string(&arr_b)) }); } criterion_group!(benches, add_benchmark); criterion_main!(benches);
bench_sum
identifier_name
aggregate_kernels.rs
// Licensed to the Apache Software Foundation (ASF) under one // or more contributor license agreements. See the NOTICE file // distributed with this work for additional information // regarding copyright ownership. The ASF licenses this file // to you 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. #[macro_use] extern crate criterion; use criterion::Criterion; use rand::{distributions::Alphanumeric, Rng}; extern crate arrow; use arrow::array::*; use arrow::compute::kernels::aggregate::*; use arrow::util::test_util::seedable_rng; fn create_array(size: usize, with_nulls: bool) -> Float32Array { // use random numbers to avoid spurious compiler optimizations wrt to branching let mut rng = seedable_rng(); let mut builder = Float32Builder::new(size); for _ in 0..size { if with_nulls && rng.gen::<f32>() > 0.5 { builder.append_null().unwrap(); } else { builder.append_value(rng.gen()).unwrap(); } } builder.finish() } fn create_string_array(size: usize, with_nulls: bool) -> StringArray { // use random numbers to avoid spurious compiler optimizations wrt to branching let mut rng = seedable_rng(); let mut builder = StringBuilder::new(size); for _ in 0..size { if with_nulls && rng.gen::<f32>() > 0.5 { builder.append_null().unwrap(); } else { let string = seedable_rng() .sample_iter(&Alphanumeric) .take(10) .collect::<String>(); builder.append_value(&string).unwrap(); } } builder.finish() } fn bench_sum(arr_a: &Float32Array) { criterion::black_box(sum(&arr_a).unwrap()); } fn bench_min(arr_a: &Float32Array) { criterion::black_box(min(&arr_a).unwrap()); } fn bench_min_string(arr_a: &StringArray) { criterion::black_box(min_string(&arr_a).unwrap()); } fn add_benchmark(c: &mut Criterion) { let arr_a = create_array(512, false); c.bench_function("sum 512", |b| b.iter(|| bench_sum(&arr_a))); c.bench_function("min 512", |b| b.iter(|| bench_min(&arr_a))); let arr_a = create_array(512, true); c.bench_function("sum nulls 512", |b| b.iter(|| bench_sum(&arr_a))); c.bench_function("min nulls 512", |b| b.iter(|| bench_min(&arr_a)));
let arr_b = create_string_array(512, false); c.bench_function("min string 512", |b| b.iter(|| bench_min_string(&arr_b))); let arr_b = create_string_array(512, true); c.bench_function("min nulls string 512", |b| { b.iter(|| bench_min_string(&arr_b)) }); } criterion_group!(benches, add_benchmark); criterion_main!(benches);
random_line_split
aggregate_kernels.rs
// Licensed to the Apache Software Foundation (ASF) under one // or more contributor license agreements. See the NOTICE file // distributed with this work for additional information // regarding copyright ownership. The ASF licenses this file // to you 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. #[macro_use] extern crate criterion; use criterion::Criterion; use rand::{distributions::Alphanumeric, Rng}; extern crate arrow; use arrow::array::*; use arrow::compute::kernels::aggregate::*; use arrow::util::test_util::seedable_rng; fn create_array(size: usize, with_nulls: bool) -> Float32Array { // use random numbers to avoid spurious compiler optimizations wrt to branching let mut rng = seedable_rng(); let mut builder = Float32Builder::new(size); for _ in 0..size { if with_nulls && rng.gen::<f32>() > 0.5 { builder.append_null().unwrap(); } else { builder.append_value(rng.gen()).unwrap(); } } builder.finish() } fn create_string_array(size: usize, with_nulls: bool) -> StringArray { // use random numbers to avoid spurious compiler optimizations wrt to branching let mut rng = seedable_rng(); let mut builder = StringBuilder::new(size); for _ in 0..size { if with_nulls && rng.gen::<f32>() > 0.5 { builder.append_null().unwrap(); } else { let string = seedable_rng() .sample_iter(&Alphanumeric) .take(10) .collect::<String>(); builder.append_value(&string).unwrap(); } } builder.finish() } fn bench_sum(arr_a: &Float32Array) { criterion::black_box(sum(&arr_a).unwrap()); } fn bench_min(arr_a: &Float32Array) { criterion::black_box(min(&arr_a).unwrap()); } fn bench_min_string(arr_a: &StringArray)
fn add_benchmark(c: &mut Criterion) { let arr_a = create_array(512, false); c.bench_function("sum 512", |b| b.iter(|| bench_sum(&arr_a))); c.bench_function("min 512", |b| b.iter(|| bench_min(&arr_a))); let arr_a = create_array(512, true); c.bench_function("sum nulls 512", |b| b.iter(|| bench_sum(&arr_a))); c.bench_function("min nulls 512", |b| b.iter(|| bench_min(&arr_a))); let arr_b = create_string_array(512, false); c.bench_function("min string 512", |b| b.iter(|| bench_min_string(&arr_b))); let arr_b = create_string_array(512, true); c.bench_function("min nulls string 512", |b| { b.iter(|| bench_min_string(&arr_b)) }); } criterion_group!(benches, add_benchmark); criterion_main!(benches);
{ criterion::black_box(min_string(&arr_a).unwrap()); }
identifier_body
map.rs
//! Extension methods for `Stream` based on record-by-record transformation. use Data; use dataflow::{Stream, Scope}; use dataflow::channels::pact::Pipeline; use dataflow::operators::unary::Unary; /// Extension trait for `Stream`. pub trait Map<S: Scope, D: Data> { /// Consumes each element of the stream and yields a new element. /// /// #Examples /// ``` /// use timely::dataflow::operators::{ToStream, Map, Inspect}; /// /// timely::example(|scope| { /// (0..10).to_stream(scope) /// .map(|x| x + 1) /// .inspect(|x| println!("seen: {:?}", x)); /// }); /// ``` fn map<D2: Data, L: Fn(D)->D2+'static>(&self, logic: L) -> Stream<S, D2>; /// Updates each element of the stream and yields the element, re-using memory where possible. /// /// #Examples /// ``` /// use timely::dataflow::operators::{ToStream, Map, Inspect}; /// /// timely::example(|scope| { /// (0..10).to_stream(scope) /// .map_in_place(|x| *x += 1) /// .inspect(|x| println!("seen: {:?}", x)); /// });
/// ``` fn map_in_place<L: Fn(&mut D)+'static>(&self, logic: L) -> Stream<S, D>; /// Consumes each element of the stream and yields some number of new elements. /// /// #Examples /// ``` /// use timely::dataflow::operators::{ToStream, Map, Inspect}; /// /// timely::example(|scope| { /// (0..10).to_stream(scope) /// .flat_map(|x| (0..x)) /// .inspect(|x| println!("seen: {:?}", x)); /// }); /// ``` fn flat_map<I: Iterator, L: Fn(D)->I+'static>(&self, logic: L) -> Stream<S, I::Item> where I::Item: Data; } impl<S: Scope, D: Data> Map<S, D> for Stream<S, D> { fn map<D2: Data, L: Fn(D)->D2+'static>(&self, logic: L) -> Stream<S, D2> { self.unary_stream(Pipeline, "Map", move |input, output| { input.for_each(|time, data| { output.session(&time).give_iterator(data.drain(..).map(|x| logic(x))); }); }) } fn map_in_place<L: Fn(&mut D)+'static>(&self, logic: L) -> Stream<S, D> { self.unary_stream(Pipeline, "MapInPlace", move |input, output| { input.for_each(|time, data| { for datum in data.iter_mut() { logic(datum); } output.session(&time).give_content(data); }) }) } // TODO : This would be more robust if it captured an iterator and then pulled an appropriate // TODO : number of elements from the iterator. This would allow iterators that produce many // TODO : records without taking arbitrarily long and arbitrarily much memory. fn flat_map<I: Iterator, L: Fn(D)->I+'static>(&self, logic: L) -> Stream<S, I::Item> where I::Item: Data { self.unary_stream(Pipeline, "FlatMap", move |input, output| { input.for_each(|time, data| { output.session(&time).give_iterator(data.drain(..).flat_map(|x| logic(x))); }); }) } // fn filter_map<D2: Data, L: Fn(D)->Option<D2>+'static>(&self, logic: L) -> Stream<S, D2> { // self.unary_stream(Pipeline, "FilterMap", move |input, output| { // while let Some((time, data)) = input.next() { // output.session(time).give_iterator(data.drain(..).filter_map(|x| logic(x))); // } // }) // } }
random_line_split
map.rs
//! Extension methods for `Stream` based on record-by-record transformation. use Data; use dataflow::{Stream, Scope}; use dataflow::channels::pact::Pipeline; use dataflow::operators::unary::Unary; /// Extension trait for `Stream`. pub trait Map<S: Scope, D: Data> { /// Consumes each element of the stream and yields a new element. /// /// #Examples /// ``` /// use timely::dataflow::operators::{ToStream, Map, Inspect}; /// /// timely::example(|scope| { /// (0..10).to_stream(scope) /// .map(|x| x + 1) /// .inspect(|x| println!("seen: {:?}", x)); /// }); /// ``` fn map<D2: Data, L: Fn(D)->D2+'static>(&self, logic: L) -> Stream<S, D2>; /// Updates each element of the stream and yields the element, re-using memory where possible. /// /// #Examples /// ``` /// use timely::dataflow::operators::{ToStream, Map, Inspect}; /// /// timely::example(|scope| { /// (0..10).to_stream(scope) /// .map_in_place(|x| *x += 1) /// .inspect(|x| println!("seen: {:?}", x)); /// }); /// ``` fn map_in_place<L: Fn(&mut D)+'static>(&self, logic: L) -> Stream<S, D>; /// Consumes each element of the stream and yields some number of new elements. /// /// #Examples /// ``` /// use timely::dataflow::operators::{ToStream, Map, Inspect}; /// /// timely::example(|scope| { /// (0..10).to_stream(scope) /// .flat_map(|x| (0..x)) /// .inspect(|x| println!("seen: {:?}", x)); /// }); /// ``` fn flat_map<I: Iterator, L: Fn(D)->I+'static>(&self, logic: L) -> Stream<S, I::Item> where I::Item: Data; } impl<S: Scope, D: Data> Map<S, D> for Stream<S, D> { fn map<D2: Data, L: Fn(D)->D2+'static>(&self, logic: L) -> Stream<S, D2> { self.unary_stream(Pipeline, "Map", move |input, output| { input.for_each(|time, data| { output.session(&time).give_iterator(data.drain(..).map(|x| logic(x))); }); }) } fn map_in_place<L: Fn(&mut D)+'static>(&self, logic: L) -> Stream<S, D> { self.unary_stream(Pipeline, "MapInPlace", move |input, output| { input.for_each(|time, data| { for datum in data.iter_mut() { logic(datum); } output.session(&time).give_content(data); }) }) } // TODO : This would be more robust if it captured an iterator and then pulled an appropriate // TODO : number of elements from the iterator. This would allow iterators that produce many // TODO : records without taking arbitrarily long and arbitrarily much memory. fn
<I: Iterator, L: Fn(D)->I+'static>(&self, logic: L) -> Stream<S, I::Item> where I::Item: Data { self.unary_stream(Pipeline, "FlatMap", move |input, output| { input.for_each(|time, data| { output.session(&time).give_iterator(data.drain(..).flat_map(|x| logic(x))); }); }) } // fn filter_map<D2: Data, L: Fn(D)->Option<D2>+'static>(&self, logic: L) -> Stream<S, D2> { // self.unary_stream(Pipeline, "FilterMap", move |input, output| { // while let Some((time, data)) = input.next() { // output.session(time).give_iterator(data.drain(..).filter_map(|x| logic(x))); // } // }) // } }
flat_map
identifier_name
map.rs
//! Extension methods for `Stream` based on record-by-record transformation. use Data; use dataflow::{Stream, Scope}; use dataflow::channels::pact::Pipeline; use dataflow::operators::unary::Unary; /// Extension trait for `Stream`. pub trait Map<S: Scope, D: Data> { /// Consumes each element of the stream and yields a new element. /// /// #Examples /// ``` /// use timely::dataflow::operators::{ToStream, Map, Inspect}; /// /// timely::example(|scope| { /// (0..10).to_stream(scope) /// .map(|x| x + 1) /// .inspect(|x| println!("seen: {:?}", x)); /// }); /// ``` fn map<D2: Data, L: Fn(D)->D2+'static>(&self, logic: L) -> Stream<S, D2>; /// Updates each element of the stream and yields the element, re-using memory where possible. /// /// #Examples /// ``` /// use timely::dataflow::operators::{ToStream, Map, Inspect}; /// /// timely::example(|scope| { /// (0..10).to_stream(scope) /// .map_in_place(|x| *x += 1) /// .inspect(|x| println!("seen: {:?}", x)); /// }); /// ``` fn map_in_place<L: Fn(&mut D)+'static>(&self, logic: L) -> Stream<S, D>; /// Consumes each element of the stream and yields some number of new elements. /// /// #Examples /// ``` /// use timely::dataflow::operators::{ToStream, Map, Inspect}; /// /// timely::example(|scope| { /// (0..10).to_stream(scope) /// .flat_map(|x| (0..x)) /// .inspect(|x| println!("seen: {:?}", x)); /// }); /// ``` fn flat_map<I: Iterator, L: Fn(D)->I+'static>(&self, logic: L) -> Stream<S, I::Item> where I::Item: Data; } impl<S: Scope, D: Data> Map<S, D> for Stream<S, D> { fn map<D2: Data, L: Fn(D)->D2+'static>(&self, logic: L) -> Stream<S, D2> { self.unary_stream(Pipeline, "Map", move |input, output| { input.for_each(|time, data| { output.session(&time).give_iterator(data.drain(..).map(|x| logic(x))); }); }) } fn map_in_place<L: Fn(&mut D)+'static>(&self, logic: L) -> Stream<S, D> { self.unary_stream(Pipeline, "MapInPlace", move |input, output| { input.for_each(|time, data| { for datum in data.iter_mut() { logic(datum); } output.session(&time).give_content(data); }) }) } // TODO : This would be more robust if it captured an iterator and then pulled an appropriate // TODO : number of elements from the iterator. This would allow iterators that produce many // TODO : records without taking arbitrarily long and arbitrarily much memory. fn flat_map<I: Iterator, L: Fn(D)->I+'static>(&self, logic: L) -> Stream<S, I::Item> where I::Item: Data
// fn filter_map<D2: Data, L: Fn(D)->Option<D2>+'static>(&self, logic: L) -> Stream<S, D2> { // self.unary_stream(Pipeline, "FilterMap", move |input, output| { // while let Some((time, data)) = input.next() { // output.session(time).give_iterator(data.drain(..).filter_map(|x| logic(x))); // } // }) // } }
{ self.unary_stream(Pipeline, "FlatMap", move |input, output| { input.for_each(|time, data| { output.session(&time).give_iterator(data.drain(..).flat_map(|x| logic(x))); }); }) }
identifier_body
sync.rs
/* (C) Joshua Yanovski (@pythonesque) https://gist.github.com/pythonesque/5bdf071d3617b61b3fed */ #![allow(dead_code)] use std::cell::UnsafeCell; use std::mem; use std::sync::{self, MutexGuard, Mutex}; use std::sync::atomic::{AtomicUsize, Ordering}; use std::marker::PhantomData; // This may seem useless but provided that each thread has a unique // thread local address, and this is created once per thread, it will // always be unique. thread_local!(static THREAD_ID: () = ()); #[derive(Debug)] enum LockError { /// Mutex was poisoned, Poisoned, /// Mutex would block due to exceeded recursion limits. WouldBlockRecursive, } #[derive(Debug)] enum TryLockError { /// Mutex was poisoned Poisoned, /// Mutex would block because it is taken by another thread. WouldBlockExclusive, /// Mutex would block due to exceeded recursion limits. WouldBlockRecursive, } struct RecursiveMutex { owner: AtomicUsize, recursion: UnsafeCell<u64>, mutex: Mutex<()>, guard: UnsafeCell<*mut MutexGuard<'static, ()>>, } unsafe impl Sync for RecursiveMutex {} unsafe impl Send for RecursiveMutex {} #[must_use] struct RecursiveMutexGuard<'a> { mutex: &'a RecursiveMutex, marker: PhantomData<*mut ()>, //!Send } // Cannot implement Send because we rely on the guard being dropped in the // same thread (otherwise we can't use Relaxed). We might be able to allow // it with Acquire / Release? impl RecursiveMutex { fn new() -> RecursiveMutex { RecursiveMutex { owner: AtomicUsize::new(0), recursion: UnsafeCell::new(0), mutex: Mutex::new(()), guard: UnsafeCell::new(0 as *mut _), } } fn get_thread_id(&self) -> usize { THREAD_ID.with(|x| x as *const _ as usize) } fn is_same_thread(&self) -> bool { self.get_thread_id() == self.owner.load(Ordering::Relaxed) } fn store_thread_id(&self, guard: MutexGuard<()>) { unsafe { let tid = self.get_thread_id(); self.owner.store(tid, Ordering::Relaxed); *self.guard.get() = mem::transmute(Box::new(guard)); } } fn check_recursion(&self) -> Option<RecursiveMutexGuard> { unsafe { let recursion = self.recursion.get(); if let Some(n) = (*recursion).checked_add(1) { *recursion = n; Some(RecursiveMutexGuard { mutex: self, marker: PhantomData }) } else { None } } } pub fn lock(&'static self) -> Result<RecursiveMutexGuard, LockError> { // Relaxed is sufficient. If tid == self.owner, it must have been set in the // same thread, and nothing else could have taken the lock in another thread; // hence, it is synchronized. Similarly, if tid!= self.owner, either the // lock was never taken by this thread, or the lock was taken by this thread // and then dropped in the same thread (known because the guard is not Send), // so that is synchronized as well. The only reason it needs to be atomic at // all is to ensure it doesn't see partial data, and to make sure the load and // store aren't reordered around the acquire incorrectly (I believe this is why // Unordered is not suitable here, but I may be wrong since acquire() provides // a memory fence). if!self.is_same_thread() { match self.mutex.lock() { Ok(guard) => self.store_thread_id(guard), Err(_) => return Err(LockError::Poisoned), } } match self.check_recursion() { Some(guard) => Ok(guard), None => Err(LockError::WouldBlockRecursive), } } #[allow(dead_code)] fn try_lock(&'static self) -> Result<RecursiveMutexGuard, TryLockError> { // Same reasoning as in lock(). if!self.is_same_thread() { match self.mutex.try_lock() { Ok(guard) => self.store_thread_id(guard), Err(sync::TryLockError::Poisoned(_)) => return Err(TryLockError::Poisoned), Err(sync::TryLockError::WouldBlock) => return Err(TryLockError::WouldBlockExclusive), } } match self.check_recursion() { Some(guard) => Ok(guard), None => Err(TryLockError::WouldBlockRecursive), } } } impl<'a> Drop for RecursiveMutexGuard<'a> { fn drop(&mut self) { // We can avoid the assertion here because Rust can statically guarantee // we are not running the destructor in the wrong thread. unsafe { let recursion = self.mutex.recursion.get(); *recursion -= 1; if *recursion == 0 { self.mutex.owner.store(0, Ordering::Relaxed); mem::transmute::<_,Box<MutexGuard<()>>>(*self.mutex.guard.get()); } } } } /// Guards the execution of the provided closure with a recursive static mutex. pub fn sync<T, F>(func: F) -> T where F: FnOnce() -> T, { use remutex::ReentrantMutex; lazy_static! { // static ref LOCK: RecursiveMutex = RecursiveMutex::new(); // use temporary implementation of ReentrantMutex from nightly libstd static ref LOCK: ReentrantMutex<()> = ReentrantMutex::new(()); } let _guard = LOCK.lock(); func() } #[cfg(test)] mod tests { use super::RecursiveMutex; #[test] pub fn test_recursive_mutex() { lazy_static! { static ref LOCK: RecursiveMutex = RecursiveMutex::new(); } let _g1 = LOCK.try_lock(); let _g2 = LOCK.lock();
let _g3 = LOCK.try_lock(); let _g4 = LOCK.lock(); } }
random_line_split
sync.rs
/* (C) Joshua Yanovski (@pythonesque) https://gist.github.com/pythonesque/5bdf071d3617b61b3fed */ #![allow(dead_code)] use std::cell::UnsafeCell; use std::mem; use std::sync::{self, MutexGuard, Mutex}; use std::sync::atomic::{AtomicUsize, Ordering}; use std::marker::PhantomData; // This may seem useless but provided that each thread has a unique // thread local address, and this is created once per thread, it will // always be unique. thread_local!(static THREAD_ID: () = ()); #[derive(Debug)] enum LockError { /// Mutex was poisoned, Poisoned, /// Mutex would block due to exceeded recursion limits. WouldBlockRecursive, } #[derive(Debug)] enum TryLockError { /// Mutex was poisoned Poisoned, /// Mutex would block because it is taken by another thread. WouldBlockExclusive, /// Mutex would block due to exceeded recursion limits. WouldBlockRecursive, } struct RecursiveMutex { owner: AtomicUsize, recursion: UnsafeCell<u64>, mutex: Mutex<()>, guard: UnsafeCell<*mut MutexGuard<'static, ()>>, } unsafe impl Sync for RecursiveMutex {} unsafe impl Send for RecursiveMutex {} #[must_use] struct RecursiveMutexGuard<'a> { mutex: &'a RecursiveMutex, marker: PhantomData<*mut ()>, //!Send } // Cannot implement Send because we rely on the guard being dropped in the // same thread (otherwise we can't use Relaxed). We might be able to allow // it with Acquire / Release? impl RecursiveMutex { fn new() -> RecursiveMutex { RecursiveMutex { owner: AtomicUsize::new(0), recursion: UnsafeCell::new(0), mutex: Mutex::new(()), guard: UnsafeCell::new(0 as *mut _), } } fn get_thread_id(&self) -> usize { THREAD_ID.with(|x| x as *const _ as usize) } fn
(&self) -> bool { self.get_thread_id() == self.owner.load(Ordering::Relaxed) } fn store_thread_id(&self, guard: MutexGuard<()>) { unsafe { let tid = self.get_thread_id(); self.owner.store(tid, Ordering::Relaxed); *self.guard.get() = mem::transmute(Box::new(guard)); } } fn check_recursion(&self) -> Option<RecursiveMutexGuard> { unsafe { let recursion = self.recursion.get(); if let Some(n) = (*recursion).checked_add(1) { *recursion = n; Some(RecursiveMutexGuard { mutex: self, marker: PhantomData }) } else { None } } } pub fn lock(&'static self) -> Result<RecursiveMutexGuard, LockError> { // Relaxed is sufficient. If tid == self.owner, it must have been set in the // same thread, and nothing else could have taken the lock in another thread; // hence, it is synchronized. Similarly, if tid!= self.owner, either the // lock was never taken by this thread, or the lock was taken by this thread // and then dropped in the same thread (known because the guard is not Send), // so that is synchronized as well. The only reason it needs to be atomic at // all is to ensure it doesn't see partial data, and to make sure the load and // store aren't reordered around the acquire incorrectly (I believe this is why // Unordered is not suitable here, but I may be wrong since acquire() provides // a memory fence). if!self.is_same_thread() { match self.mutex.lock() { Ok(guard) => self.store_thread_id(guard), Err(_) => return Err(LockError::Poisoned), } } match self.check_recursion() { Some(guard) => Ok(guard), None => Err(LockError::WouldBlockRecursive), } } #[allow(dead_code)] fn try_lock(&'static self) -> Result<RecursiveMutexGuard, TryLockError> { // Same reasoning as in lock(). if!self.is_same_thread() { match self.mutex.try_lock() { Ok(guard) => self.store_thread_id(guard), Err(sync::TryLockError::Poisoned(_)) => return Err(TryLockError::Poisoned), Err(sync::TryLockError::WouldBlock) => return Err(TryLockError::WouldBlockExclusive), } } match self.check_recursion() { Some(guard) => Ok(guard), None => Err(TryLockError::WouldBlockRecursive), } } } impl<'a> Drop for RecursiveMutexGuard<'a> { fn drop(&mut self) { // We can avoid the assertion here because Rust can statically guarantee // we are not running the destructor in the wrong thread. unsafe { let recursion = self.mutex.recursion.get(); *recursion -= 1; if *recursion == 0 { self.mutex.owner.store(0, Ordering::Relaxed); mem::transmute::<_,Box<MutexGuard<()>>>(*self.mutex.guard.get()); } } } } /// Guards the execution of the provided closure with a recursive static mutex. pub fn sync<T, F>(func: F) -> T where F: FnOnce() -> T, { use remutex::ReentrantMutex; lazy_static! { // static ref LOCK: RecursiveMutex = RecursiveMutex::new(); // use temporary implementation of ReentrantMutex from nightly libstd static ref LOCK: ReentrantMutex<()> = ReentrantMutex::new(()); } let _guard = LOCK.lock(); func() } #[cfg(test)] mod tests { use super::RecursiveMutex; #[test] pub fn test_recursive_mutex() { lazy_static! { static ref LOCK: RecursiveMutex = RecursiveMutex::new(); } let _g1 = LOCK.try_lock(); let _g2 = LOCK.lock(); let _g3 = LOCK.try_lock(); let _g4 = LOCK.lock(); } }
is_same_thread
identifier_name
sync.rs
/* (C) Joshua Yanovski (@pythonesque) https://gist.github.com/pythonesque/5bdf071d3617b61b3fed */ #![allow(dead_code)] use std::cell::UnsafeCell; use std::mem; use std::sync::{self, MutexGuard, Mutex}; use std::sync::atomic::{AtomicUsize, Ordering}; use std::marker::PhantomData; // This may seem useless but provided that each thread has a unique // thread local address, and this is created once per thread, it will // always be unique. thread_local!(static THREAD_ID: () = ()); #[derive(Debug)] enum LockError { /// Mutex was poisoned, Poisoned, /// Mutex would block due to exceeded recursion limits. WouldBlockRecursive, } #[derive(Debug)] enum TryLockError { /// Mutex was poisoned Poisoned, /// Mutex would block because it is taken by another thread. WouldBlockExclusive, /// Mutex would block due to exceeded recursion limits. WouldBlockRecursive, } struct RecursiveMutex { owner: AtomicUsize, recursion: UnsafeCell<u64>, mutex: Mutex<()>, guard: UnsafeCell<*mut MutexGuard<'static, ()>>, } unsafe impl Sync for RecursiveMutex {} unsafe impl Send for RecursiveMutex {} #[must_use] struct RecursiveMutexGuard<'a> { mutex: &'a RecursiveMutex, marker: PhantomData<*mut ()>, //!Send } // Cannot implement Send because we rely on the guard being dropped in the // same thread (otherwise we can't use Relaxed). We might be able to allow // it with Acquire / Release? impl RecursiveMutex { fn new() -> RecursiveMutex { RecursiveMutex { owner: AtomicUsize::new(0), recursion: UnsafeCell::new(0), mutex: Mutex::new(()), guard: UnsafeCell::new(0 as *mut _), } } fn get_thread_id(&self) -> usize
fn is_same_thread(&self) -> bool { self.get_thread_id() == self.owner.load(Ordering::Relaxed) } fn store_thread_id(&self, guard: MutexGuard<()>) { unsafe { let tid = self.get_thread_id(); self.owner.store(tid, Ordering::Relaxed); *self.guard.get() = mem::transmute(Box::new(guard)); } } fn check_recursion(&self) -> Option<RecursiveMutexGuard> { unsafe { let recursion = self.recursion.get(); if let Some(n) = (*recursion).checked_add(1) { *recursion = n; Some(RecursiveMutexGuard { mutex: self, marker: PhantomData }) } else { None } } } pub fn lock(&'static self) -> Result<RecursiveMutexGuard, LockError> { // Relaxed is sufficient. If tid == self.owner, it must have been set in the // same thread, and nothing else could have taken the lock in another thread; // hence, it is synchronized. Similarly, if tid!= self.owner, either the // lock was never taken by this thread, or the lock was taken by this thread // and then dropped in the same thread (known because the guard is not Send), // so that is synchronized as well. The only reason it needs to be atomic at // all is to ensure it doesn't see partial data, and to make sure the load and // store aren't reordered around the acquire incorrectly (I believe this is why // Unordered is not suitable here, but I may be wrong since acquire() provides // a memory fence). if!self.is_same_thread() { match self.mutex.lock() { Ok(guard) => self.store_thread_id(guard), Err(_) => return Err(LockError::Poisoned), } } match self.check_recursion() { Some(guard) => Ok(guard), None => Err(LockError::WouldBlockRecursive), } } #[allow(dead_code)] fn try_lock(&'static self) -> Result<RecursiveMutexGuard, TryLockError> { // Same reasoning as in lock(). if!self.is_same_thread() { match self.mutex.try_lock() { Ok(guard) => self.store_thread_id(guard), Err(sync::TryLockError::Poisoned(_)) => return Err(TryLockError::Poisoned), Err(sync::TryLockError::WouldBlock) => return Err(TryLockError::WouldBlockExclusive), } } match self.check_recursion() { Some(guard) => Ok(guard), None => Err(TryLockError::WouldBlockRecursive), } } } impl<'a> Drop for RecursiveMutexGuard<'a> { fn drop(&mut self) { // We can avoid the assertion here because Rust can statically guarantee // we are not running the destructor in the wrong thread. unsafe { let recursion = self.mutex.recursion.get(); *recursion -= 1; if *recursion == 0 { self.mutex.owner.store(0, Ordering::Relaxed); mem::transmute::<_,Box<MutexGuard<()>>>(*self.mutex.guard.get()); } } } } /// Guards the execution of the provided closure with a recursive static mutex. pub fn sync<T, F>(func: F) -> T where F: FnOnce() -> T, { use remutex::ReentrantMutex; lazy_static! { // static ref LOCK: RecursiveMutex = RecursiveMutex::new(); // use temporary implementation of ReentrantMutex from nightly libstd static ref LOCK: ReentrantMutex<()> = ReentrantMutex::new(()); } let _guard = LOCK.lock(); func() } #[cfg(test)] mod tests { use super::RecursiveMutex; #[test] pub fn test_recursive_mutex() { lazy_static! { static ref LOCK: RecursiveMutex = RecursiveMutex::new(); } let _g1 = LOCK.try_lock(); let _g2 = LOCK.lock(); let _g3 = LOCK.try_lock(); let _g4 = LOCK.lock(); } }
{ THREAD_ID.with(|x| x as *const _ as usize) }
identifier_body
pde.rs
use ndarray::*; use ndarray_linalg::*; use std::f64::consts::PI; use std::iter::FromIterator; use eom::pde::*; #[test] fn pair_r2c2r() { let n = 128; let a: Array1<f64> = random(n); let mut p = Pair::new(n); p.r.copy_from_slice(&a.as_slice().unwrap()); p.r2c(); p.c2r(); let b: Array1<f64> = Array::from_iter(p.r.iter().cloned()); assert_close_l2!(&a, &b, 1e-7); } #[test]
let n = 128; let k0 = 2.0 * PI / n as f64; let a = Array::from_shape_fn(n, |i| 2.0 * (i as f64 * k0).cos()); let mut p = Pair::new(n); p.c[1] = c64::new(1.0, 0.0); p.c2r(); let b = Array::from_iter(p.r.iter().cloned()); assert_close_l2!(&a, &b, 1e-7); }
fn pair_c2r() {
random_line_split
pde.rs
use ndarray::*; use ndarray_linalg::*; use std::f64::consts::PI; use std::iter::FromIterator; use eom::pde::*; #[test] fn
() { let n = 128; let a: Array1<f64> = random(n); let mut p = Pair::new(n); p.r.copy_from_slice(&a.as_slice().unwrap()); p.r2c(); p.c2r(); let b: Array1<f64> = Array::from_iter(p.r.iter().cloned()); assert_close_l2!(&a, &b, 1e-7); } #[test] fn pair_c2r() { let n = 128; let k0 = 2.0 * PI / n as f64; let a = Array::from_shape_fn(n, |i| 2.0 * (i as f64 * k0).cos()); let mut p = Pair::new(n); p.c[1] = c64::new(1.0, 0.0); p.c2r(); let b = Array::from_iter(p.r.iter().cloned()); assert_close_l2!(&a, &b, 1e-7); }
pair_r2c2r
identifier_name
pde.rs
use ndarray::*; use ndarray_linalg::*; use std::f64::consts::PI; use std::iter::FromIterator; use eom::pde::*; #[test] fn pair_r2c2r() { let n = 128; let a: Array1<f64> = random(n); let mut p = Pair::new(n); p.r.copy_from_slice(&a.as_slice().unwrap()); p.r2c(); p.c2r(); let b: Array1<f64> = Array::from_iter(p.r.iter().cloned()); assert_close_l2!(&a, &b, 1e-7); } #[test] fn pair_c2r()
{ let n = 128; let k0 = 2.0 * PI / n as f64; let a = Array::from_shape_fn(n, |i| 2.0 * (i as f64 * k0).cos()); let mut p = Pair::new(n); p.c[1] = c64::new(1.0, 0.0); p.c2r(); let b = Array::from_iter(p.r.iter().cloned()); assert_close_l2!(&a, &b, 1e-7); }
identifier_body
convert_string_literal.rs
use rstest::*; use std::net::SocketAddr;
#[case(true, r#"4.3.2.1:24"#)] #[case(false, "[2001:db8:85a3:8d3:1319:8a2e:370:7348]:443")] #[case(false, r#"[2aa1:db8:85a3:8af:1319:8a2e:375:4873]:344"#)] #[case(false, "this.is.not.a.socket.address")] #[case(false, r#"this.is.not.a.socket.address"#)] fn cases(#[case] expected: bool, #[case] addr: SocketAddr) { assert_eq!(expected, addr.is_ipv4()); } #[rstest] fn values( #[values( "1.2.3.4:42", r#"4.3.2.1:24"#, "this.is.not.a.socket.address", r#"this.is.not.a.socket.address"# )] addr: SocketAddr, ) { assert!(addr.is_ipv4()) } #[rstest] #[case(b"12345")] fn not_convert_byte_array(#[case] cases: &[u8], #[values(b"abc")] values: &[u8]) { assert_eq!(5, cases.len()); assert_eq!(3, values.len()); } trait MyTrait { fn my_trait(&self) -> u32 { 42 } } impl MyTrait for &str {} #[rstest] #[case("impl", "nothing")] fn not_convert_impl(#[case] that_impl: impl MyTrait, #[case] s: &str) { assert_eq!(42, that_impl.my_trait()); assert_eq!(42, s.my_trait()); } #[rstest] #[case("1.2.3.4", "1.2.3.4:42")] #[case("1.2.3.4".to_owned(), "1.2.3.4:42")] fn not_convert_generics<S: AsRef<str>>(#[case] ip: S, #[case] addr: SocketAddr) { assert_eq!(addr.ip().to_string(), ip.as_ref()); } struct MyType(String); struct E; impl core::str::FromStr for MyType { type Err = E; fn from_str(s: &str) -> Result<Self, Self::Err> { match s { "error" => Err(E), inner => Ok(MyType(inner.to_owned())), } } } #[rstest] #[case("hello", "hello")] #[case("doesn't mater", "error")] fn convert_without_debug(#[case] expected: &str, #[case] converted: MyType) { assert_eq!(expected, converted.0); }
#[rstest] #[case(true, "1.2.3.4:42")]
random_line_split
convert_string_literal.rs
use rstest::*; use std::net::SocketAddr; #[rstest] #[case(true, "1.2.3.4:42")] #[case(true, r#"4.3.2.1:24"#)] #[case(false, "[2001:db8:85a3:8d3:1319:8a2e:370:7348]:443")] #[case(false, r#"[2aa1:db8:85a3:8af:1319:8a2e:375:4873]:344"#)] #[case(false, "this.is.not.a.socket.address")] #[case(false, r#"this.is.not.a.socket.address"#)] fn cases(#[case] expected: bool, #[case] addr: SocketAddr) { assert_eq!(expected, addr.is_ipv4()); } #[rstest] fn values( #[values( "1.2.3.4:42", r#"4.3.2.1:24"#, "this.is.not.a.socket.address", r#"this.is.not.a.socket.address"# )] addr: SocketAddr, ) { assert!(addr.is_ipv4()) } #[rstest] #[case(b"12345")] fn
(#[case] cases: &[u8], #[values(b"abc")] values: &[u8]) { assert_eq!(5, cases.len()); assert_eq!(3, values.len()); } trait MyTrait { fn my_trait(&self) -> u32 { 42 } } impl MyTrait for &str {} #[rstest] #[case("impl", "nothing")] fn not_convert_impl(#[case] that_impl: impl MyTrait, #[case] s: &str) { assert_eq!(42, that_impl.my_trait()); assert_eq!(42, s.my_trait()); } #[rstest] #[case("1.2.3.4", "1.2.3.4:42")] #[case("1.2.3.4".to_owned(), "1.2.3.4:42")] fn not_convert_generics<S: AsRef<str>>(#[case] ip: S, #[case] addr: SocketAddr) { assert_eq!(addr.ip().to_string(), ip.as_ref()); } struct MyType(String); struct E; impl core::str::FromStr for MyType { type Err = E; fn from_str(s: &str) -> Result<Self, Self::Err> { match s { "error" => Err(E), inner => Ok(MyType(inner.to_owned())), } } } #[rstest] #[case("hello", "hello")] #[case("doesn't mater", "error")] fn convert_without_debug(#[case] expected: &str, #[case] converted: MyType) { assert_eq!(expected, converted.0); }
not_convert_byte_array
identifier_name
color.rs
use std::ops::{Add, Mul}; use std::iter::Sum; #[derive(Copy, Clone, Serialize, Deserialize)] pub struct Color(pub f64, pub f64, pub f64); pub const RED: Color = Color(1.0, 0.0, 0.0); pub const GREEN: Color = Color(0.0, 1.0, 0.0); pub const BLUE: Color = Color(0.0, 0.0, 1.0); pub const WHITE: Color = Color(1.0, 1.0, 1.0); pub const BLACK: Color = Color(0.0, 0.0, 0.0); impl Add for Color { type Output = Color; fn add(self, other: Color) -> Color { Color(self.0 + other.0, self.1 + other.1, self.2 + other.2) } } impl Mul for Color { type Output = Color; fn mul(self, other: Color) -> Color { Color(self.0 * other.0, self.1 * other.1, self.2 * other.2) } } impl Mul<f64> for Color { type Output = Color; fn mul(self, other: f64) -> Color { Color(self.0 * other, self.1 * other, self.2 * other) } } impl Into<(u8, u8, u8)> for Color { fn into(mut self) -> (u8, u8, u8) {
if self.1 > 1.0 { self.1 = 1.0; } if self.2 > 1.0 { self.2 = 1.0; } ( (255.0 * self.0) as u8, (255.0 * self.1) as u8, (255.0 * self.2) as u8, ) } } impl Sum for Color { fn sum<I>(iter: I) -> Self where I: Iterator<Item = Self>, { iter.fold(Color(0.0, 0.0, 0.0), |s, c| s + c) } }
if self.0 > 1.0 { self.0 = 1.0; }
random_line_split
color.rs
use std::ops::{Add, Mul}; use std::iter::Sum; #[derive(Copy, Clone, Serialize, Deserialize)] pub struct Color(pub f64, pub f64, pub f64); pub const RED: Color = Color(1.0, 0.0, 0.0); pub const GREEN: Color = Color(0.0, 1.0, 0.0); pub const BLUE: Color = Color(0.0, 0.0, 1.0); pub const WHITE: Color = Color(1.0, 1.0, 1.0); pub const BLACK: Color = Color(0.0, 0.0, 0.0); impl Add for Color { type Output = Color; fn add(self, other: Color) -> Color { Color(self.0 + other.0, self.1 + other.1, self.2 + other.2) } } impl Mul for Color { type Output = Color; fn mul(self, other: Color) -> Color { Color(self.0 * other.0, self.1 * other.1, self.2 * other.2) } } impl Mul<f64> for Color { type Output = Color; fn mul(self, other: f64) -> Color { Color(self.0 * other, self.1 * other, self.2 * other) } } impl Into<(u8, u8, u8)> for Color { fn into(mut self) -> (u8, u8, u8) { if self.0 > 1.0 { self.0 = 1.0; } if self.1 > 1.0 { self.1 = 1.0; } if self.2 > 1.0 { self.2 = 1.0; } ( (255.0 * self.0) as u8, (255.0 * self.1) as u8, (255.0 * self.2) as u8, ) } } impl Sum for Color { fn
<I>(iter: I) -> Self where I: Iterator<Item = Self>, { iter.fold(Color(0.0, 0.0, 0.0), |s, c| s + c) } }
sum
identifier_name
color.rs
use std::ops::{Add, Mul}; use std::iter::Sum; #[derive(Copy, Clone, Serialize, Deserialize)] pub struct Color(pub f64, pub f64, pub f64); pub const RED: Color = Color(1.0, 0.0, 0.0); pub const GREEN: Color = Color(0.0, 1.0, 0.0); pub const BLUE: Color = Color(0.0, 0.0, 1.0); pub const WHITE: Color = Color(1.0, 1.0, 1.0); pub const BLACK: Color = Color(0.0, 0.0, 0.0); impl Add for Color { type Output = Color; fn add(self, other: Color) -> Color { Color(self.0 + other.0, self.1 + other.1, self.2 + other.2) } } impl Mul for Color { type Output = Color; fn mul(self, other: Color) -> Color { Color(self.0 * other.0, self.1 * other.1, self.2 * other.2) } } impl Mul<f64> for Color { type Output = Color; fn mul(self, other: f64) -> Color
} impl Into<(u8, u8, u8)> for Color { fn into(mut self) -> (u8, u8, u8) { if self.0 > 1.0 { self.0 = 1.0; } if self.1 > 1.0 { self.1 = 1.0; } if self.2 > 1.0 { self.2 = 1.0; } ( (255.0 * self.0) as u8, (255.0 * self.1) as u8, (255.0 * self.2) as u8, ) } } impl Sum for Color { fn sum<I>(iter: I) -> Self where I: Iterator<Item = Self>, { iter.fold(Color(0.0, 0.0, 0.0), |s, c| s + c) } }
{ Color(self.0 * other, self.1 * other, self.2 * other) }
identifier_body
color.rs
use std::ops::{Add, Mul}; use std::iter::Sum; #[derive(Copy, Clone, Serialize, Deserialize)] pub struct Color(pub f64, pub f64, pub f64); pub const RED: Color = Color(1.0, 0.0, 0.0); pub const GREEN: Color = Color(0.0, 1.0, 0.0); pub const BLUE: Color = Color(0.0, 0.0, 1.0); pub const WHITE: Color = Color(1.0, 1.0, 1.0); pub const BLACK: Color = Color(0.0, 0.0, 0.0); impl Add for Color { type Output = Color; fn add(self, other: Color) -> Color { Color(self.0 + other.0, self.1 + other.1, self.2 + other.2) } } impl Mul for Color { type Output = Color; fn mul(self, other: Color) -> Color { Color(self.0 * other.0, self.1 * other.1, self.2 * other.2) } } impl Mul<f64> for Color { type Output = Color; fn mul(self, other: f64) -> Color { Color(self.0 * other, self.1 * other, self.2 * other) } } impl Into<(u8, u8, u8)> for Color { fn into(mut self) -> (u8, u8, u8) { if self.0 > 1.0
if self.1 > 1.0 { self.1 = 1.0; } if self.2 > 1.0 { self.2 = 1.0; } ( (255.0 * self.0) as u8, (255.0 * self.1) as u8, (255.0 * self.2) as u8, ) } } impl Sum for Color { fn sum<I>(iter: I) -> Self where I: Iterator<Item = Self>, { iter.fold(Color(0.0, 0.0, 0.0), |s, c| s + c) } }
{ self.0 = 1.0; }
conditional_block
config.rs
// Copyright 2015, 2016 Ethcore (UK) Ltd. // This file is part of Parity. // Parity is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // Parity is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // You should have received a copy of the GNU General Public License // along with Parity. If not, see <http://www.gnu.org/licenses/>. //! Traces config. use bloomchain::Config as BloomConfig; /// Traces config. #[derive(Debug, PartialEq, Clone)] pub struct
{ /// Indicates if tracing should be enabled or not. /// If it's None, it will be automatically configured. pub enabled: bool, /// Traces blooms configuration. pub blooms: BloomConfig, /// Preferef cache-size. pub pref_cache_size: usize, /// Max cache-size. pub max_cache_size: usize, } impl Default for Config { fn default() -> Self { Config { enabled: false, blooms: BloomConfig { levels: 3, elements_per_index: 16, }, pref_cache_size: 15 * 1024 * 1024, max_cache_size: 20 * 1024 * 1024, } } }
Config
identifier_name
config.rs
// Copyright 2015, 2016 Ethcore (UK) Ltd. // This file is part of Parity. // Parity is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // Parity is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // You should have received a copy of the GNU General Public License
use bloomchain::Config as BloomConfig; /// Traces config. #[derive(Debug, PartialEq, Clone)] pub struct Config { /// Indicates if tracing should be enabled or not. /// If it's None, it will be automatically configured. pub enabled: bool, /// Traces blooms configuration. pub blooms: BloomConfig, /// Preferef cache-size. pub pref_cache_size: usize, /// Max cache-size. pub max_cache_size: usize, } impl Default for Config { fn default() -> Self { Config { enabled: false, blooms: BloomConfig { levels: 3, elements_per_index: 16, }, pref_cache_size: 15 * 1024 * 1024, max_cache_size: 20 * 1024 * 1024, } } }
// along with Parity. If not, see <http://www.gnu.org/licenses/>. //! Traces config.
random_line_split
hook_macro.rs
//! A macro that handles hooking an exported function that may have already //! been hooked in a way that GetProcAddress doesn't return the expected dll. use std::io; use libc::c_void; use crate::windows; // It would be preferrable to refactor this macro away to some sort of an api like // ``` // let mut hook = WinapiDllHook::new(&mut patcher, "user32"); // hook.hook(ShowWindow, "ShowWindow", show_window_hook); // Does normal hook here, or buffers // // an unusal hook for later. // ... // hook.commit(); // Does unusual_hooks here, if any // ``` // instead, but this was copy-pasted from older code that did it this way so this'll do for now. macro_rules! hook_winapi_exports { ($active:expr, $expected_name:expr, $($name:expr, $hook:ident, $func:ident;)*) => {{ let lib = crate::windows::load_library($expected_name).unwrap(); let mut default_patcher = $active.patch_library($expected_name, 0); const fn zero(_name: &'static str) -> usize { 0 } let mut unusual_hooks = [$(zero($name)),*]; let mut i = 0; $( let proc_address = crate::hook_macro::hook_proc_address(&lib, $name); if let Ok(proc_address) = proc_address { let actual_module = crate::windows::module_from_address(proc_address as *mut c_void); let normal = actual_module.as_ref() .map(|x| x.1 == lib.handle()) .unwrap_or(false); if normal { let addr = proc_address - lib.handle() as usize; default_patcher.hook_closure_address($hook, $func, addr); } else { unusual_hooks[i] = proc_address; } } else { error!("Didn't find {}", $name); } #[allow(unused_assignments)] { i += 1; } )* i = 0; $( if unusual_hooks[i]!= 0 { let proc_address = unusual_hooks[i]; let (mut patcher, offset, _guard) = crate::hook_macro::unprotect_memory_for_hook($active, proc_address); patcher.hook_closure_address($hook, $func, offset); } #[allow(unused_assignments)] { i += 1; } )* }} } /// Helper for hook_winapi_exports! macro. pub unsafe fn unprotect_memory_for_hook<'a>( active_patcher: &'a mut whack::Patcher, proc_address: usize, ) -> (whack::ModulePatcher<'a>, usize, Option<windows::MemoryProtectionGuard>) { // Windows has always 4k pages let start = proc_address &!0xfff; let end = ((proc_address + 0x10) | 0xfff) + 1; let len = end - start; // If the unprotection for some reason fails, just keep going and hope the memory // can be written. let start = start as *mut c_void; debug!("Unprotecting memory for hook {:x} @ {:x}~{:x}", proc_address, start as usize, len); let guard = windows::unprotect_memory(start, len).ok(); let patcher = active_patcher.patch_memory(start, start,!0); (patcher, proc_address - start as usize, guard) } /// Determines address for hooking the function. /// /// In addition to just GetProcAddress this follows any unconditional jumps at the /// address returned by GetProcAddress, in order to avoid placing a second hook /// at a address which was already hooked by some system DLL (Nvidia driver). /// This should end up being more stable than otherwise. pub unsafe fn hook_proc_address(lib: &windows::Library, proc: &str) -> Result<usize, io::Error> { let mut address = lib.proc_address(proc)? as *const u8; loop { match *address { // Long jump 0xe9 =>
// Short jump 0xeb => { let offset = *address.add(1) as i8 as isize as usize; address = address.wrapping_add(2).wrapping_add(offset); } _ => return Ok(address as usize), } } }
{ let offset = (address.add(1) as *const i32).read_unaligned() as isize as usize; address = address.wrapping_add(5).wrapping_add(offset); }
conditional_block
hook_macro.rs
//! A macro that handles hooking an exported function that may have already //! been hooked in a way that GetProcAddress doesn't return the expected dll. use std::io; use libc::c_void; use crate::windows; // It would be preferrable to refactor this macro away to some sort of an api like // ``` // let mut hook = WinapiDllHook::new(&mut patcher, "user32"); // hook.hook(ShowWindow, "ShowWindow", show_window_hook); // Does normal hook here, or buffers // // an unusal hook for later. // ... // hook.commit(); // Does unusual_hooks here, if any // ``` // instead, but this was copy-pasted from older code that did it this way so this'll do for now. macro_rules! hook_winapi_exports { ($active:expr, $expected_name:expr, $($name:expr, $hook:ident, $func:ident;)*) => {{ let lib = crate::windows::load_library($expected_name).unwrap(); let mut default_patcher = $active.patch_library($expected_name, 0); const fn zero(_name: &'static str) -> usize { 0 } let mut unusual_hooks = [$(zero($name)),*]; let mut i = 0; $( let proc_address = crate::hook_macro::hook_proc_address(&lib, $name); if let Ok(proc_address) = proc_address { let actual_module = crate::windows::module_from_address(proc_address as *mut c_void); let normal = actual_module.as_ref() .map(|x| x.1 == lib.handle()) .unwrap_or(false); if normal { let addr = proc_address - lib.handle() as usize; default_patcher.hook_closure_address($hook, $func, addr); } else { unusual_hooks[i] = proc_address; } } else { error!("Didn't find {}", $name); } #[allow(unused_assignments)] { i += 1; } )* i = 0; $( if unusual_hooks[i]!= 0 { let proc_address = unusual_hooks[i]; let (mut patcher, offset, _guard) = crate::hook_macro::unprotect_memory_for_hook($active, proc_address); patcher.hook_closure_address($hook, $func, offset); } #[allow(unused_assignments)] { i += 1; } )* }} } /// Helper for hook_winapi_exports! macro. pub unsafe fn unprotect_memory_for_hook<'a>( active_patcher: &'a mut whack::Patcher, proc_address: usize, ) -> (whack::ModulePatcher<'a>, usize, Option<windows::MemoryProtectionGuard>) { // Windows has always 4k pages let start = proc_address &!0xfff; let end = ((proc_address + 0x10) | 0xfff) + 1; let len = end - start; // If the unprotection for some reason fails, just keep going and hope the memory // can be written. let start = start as *mut c_void; debug!("Unprotecting memory for hook {:x} @ {:x}~{:x}", proc_address, start as usize, len); let guard = windows::unprotect_memory(start, len).ok(); let patcher = active_patcher.patch_memory(start, start,!0); (patcher, proc_address - start as usize, guard) } /// Determines address for hooking the function. /// /// In addition to just GetProcAddress this follows any unconditional jumps at the /// address returned by GetProcAddress, in order to avoid placing a second hook /// at a address which was already hooked by some system DLL (Nvidia driver). /// This should end up being more stable than otherwise. pub unsafe fn
(lib: &windows::Library, proc: &str) -> Result<usize, io::Error> { let mut address = lib.proc_address(proc)? as *const u8; loop { match *address { // Long jump 0xe9 => { let offset = (address.add(1) as *const i32).read_unaligned() as isize as usize; address = address.wrapping_add(5).wrapping_add(offset); } // Short jump 0xeb => { let offset = *address.add(1) as i8 as isize as usize; address = address.wrapping_add(2).wrapping_add(offset); } _ => return Ok(address as usize), } } }
hook_proc_address
identifier_name
hook_macro.rs
//! A macro that handles hooking an exported function that may have already //! been hooked in a way that GetProcAddress doesn't return the expected dll. use std::io; use libc::c_void; use crate::windows; // It would be preferrable to refactor this macro away to some sort of an api like // ``` // let mut hook = WinapiDllHook::new(&mut patcher, "user32"); // hook.hook(ShowWindow, "ShowWindow", show_window_hook); // Does normal hook here, or buffers // // an unusal hook for later. // ... // hook.commit(); // Does unusual_hooks here, if any // ``` // instead, but this was copy-pasted from older code that did it this way so this'll do for now. macro_rules! hook_winapi_exports { ($active:expr, $expected_name:expr, $($name:expr, $hook:ident, $func:ident;)*) => {{ let lib = crate::windows::load_library($expected_name).unwrap(); let mut default_patcher = $active.patch_library($expected_name, 0); const fn zero(_name: &'static str) -> usize { 0 } let mut unusual_hooks = [$(zero($name)),*]; let mut i = 0; $( let proc_address = crate::hook_macro::hook_proc_address(&lib, $name); if let Ok(proc_address) = proc_address { let actual_module = crate::windows::module_from_address(proc_address as *mut c_void); let normal = actual_module.as_ref() .map(|x| x.1 == lib.handle()) .unwrap_or(false); if normal { let addr = proc_address - lib.handle() as usize; default_patcher.hook_closure_address($hook, $func, addr); } else { unusual_hooks[i] = proc_address; } } else { error!("Didn't find {}", $name); } #[allow(unused_assignments)] { i += 1; } )* i = 0; $( if unusual_hooks[i]!= 0 { let proc_address = unusual_hooks[i]; let (mut patcher, offset, _guard) = crate::hook_macro::unprotect_memory_for_hook($active, proc_address); patcher.hook_closure_address($hook, $func, offset); } #[allow(unused_assignments)] { i += 1; } )* }} } /// Helper for hook_winapi_exports! macro. pub unsafe fn unprotect_memory_for_hook<'a>( active_patcher: &'a mut whack::Patcher, proc_address: usize, ) -> (whack::ModulePatcher<'a>, usize, Option<windows::MemoryProtectionGuard>) { // Windows has always 4k pages let start = proc_address &!0xfff; let end = ((proc_address + 0x10) | 0xfff) + 1; let len = end - start; // If the unprotection for some reason fails, just keep going and hope the memory // can be written. let start = start as *mut c_void; debug!("Unprotecting memory for hook {:x} @ {:x}~{:x}", proc_address, start as usize, len); let guard = windows::unprotect_memory(start, len).ok(); let patcher = active_patcher.patch_memory(start, start,!0); (patcher, proc_address - start as usize, guard) } /// Determines address for hooking the function. /// /// In addition to just GetProcAddress this follows any unconditional jumps at the /// address returned by GetProcAddress, in order to avoid placing a second hook /// at a address which was already hooked by some system DLL (Nvidia driver). /// This should end up being more stable than otherwise. pub unsafe fn hook_proc_address(lib: &windows::Library, proc: &str) -> Result<usize, io::Error> { let mut address = lib.proc_address(proc)? as *const u8; loop { match *address { // Long jump 0xe9 => { let offset = (address.add(1) as *const i32).read_unaligned() as isize as usize; address = address.wrapping_add(5).wrapping_add(offset); }
// Short jump 0xeb => { let offset = *address.add(1) as i8 as isize as usize; address = address.wrapping_add(2).wrapping_add(offset); } _ => return Ok(address as usize), } } }
random_line_split
hook_macro.rs
//! A macro that handles hooking an exported function that may have already //! been hooked in a way that GetProcAddress doesn't return the expected dll. use std::io; use libc::c_void; use crate::windows; // It would be preferrable to refactor this macro away to some sort of an api like // ``` // let mut hook = WinapiDllHook::new(&mut patcher, "user32"); // hook.hook(ShowWindow, "ShowWindow", show_window_hook); // Does normal hook here, or buffers // // an unusal hook for later. // ... // hook.commit(); // Does unusual_hooks here, if any // ``` // instead, but this was copy-pasted from older code that did it this way so this'll do for now. macro_rules! hook_winapi_exports { ($active:expr, $expected_name:expr, $($name:expr, $hook:ident, $func:ident;)*) => {{ let lib = crate::windows::load_library($expected_name).unwrap(); let mut default_patcher = $active.patch_library($expected_name, 0); const fn zero(_name: &'static str) -> usize { 0 } let mut unusual_hooks = [$(zero($name)),*]; let mut i = 0; $( let proc_address = crate::hook_macro::hook_proc_address(&lib, $name); if let Ok(proc_address) = proc_address { let actual_module = crate::windows::module_from_address(proc_address as *mut c_void); let normal = actual_module.as_ref() .map(|x| x.1 == lib.handle()) .unwrap_or(false); if normal { let addr = proc_address - lib.handle() as usize; default_patcher.hook_closure_address($hook, $func, addr); } else { unusual_hooks[i] = proc_address; } } else { error!("Didn't find {}", $name); } #[allow(unused_assignments)] { i += 1; } )* i = 0; $( if unusual_hooks[i]!= 0 { let proc_address = unusual_hooks[i]; let (mut patcher, offset, _guard) = crate::hook_macro::unprotect_memory_for_hook($active, proc_address); patcher.hook_closure_address($hook, $func, offset); } #[allow(unused_assignments)] { i += 1; } )* }} } /// Helper for hook_winapi_exports! macro. pub unsafe fn unprotect_memory_for_hook<'a>( active_patcher: &'a mut whack::Patcher, proc_address: usize, ) -> (whack::ModulePatcher<'a>, usize, Option<windows::MemoryProtectionGuard>)
/// Determines address for hooking the function. /// /// In addition to just GetProcAddress this follows any unconditional jumps at the /// address returned by GetProcAddress, in order to avoid placing a second hook /// at a address which was already hooked by some system DLL (Nvidia driver). /// This should end up being more stable than otherwise. pub unsafe fn hook_proc_address(lib: &windows::Library, proc: &str) -> Result<usize, io::Error> { let mut address = lib.proc_address(proc)? as *const u8; loop { match *address { // Long jump 0xe9 => { let offset = (address.add(1) as *const i32).read_unaligned() as isize as usize; address = address.wrapping_add(5).wrapping_add(offset); } // Short jump 0xeb => { let offset = *address.add(1) as i8 as isize as usize; address = address.wrapping_add(2).wrapping_add(offset); } _ => return Ok(address as usize), } } }
{ // Windows has always 4k pages let start = proc_address & !0xfff; let end = ((proc_address + 0x10) | 0xfff) + 1; let len = end - start; // If the unprotection for some reason fails, just keep going and hope the memory // can be written. let start = start as *mut c_void; debug!("Unprotecting memory for hook {:x} @ {:x}~{:x}", proc_address, start as usize, len); let guard = windows::unprotect_memory(start, len).ok(); let patcher = active_patcher.patch_memory(start, start, !0); (patcher, proc_address - start as usize, guard) }
identifier_body
global.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/. */ //! Abstractions for global scopes. //! //! This module contains smart pointers to global scopes, to simplify writing //! code that works in workers as well as window scopes. use dom::bindings::codegen::Bindings::WindowBinding::WindowMethods; use dom::bindings::conversions::native_from_reflector_jsmanaged; use dom::bindings::js::{JS, Root}; use dom::bindings::utils::{Reflectable, Reflector}; use dom::document::DocumentHelpers; use dom::workerglobalscope::{WorkerGlobalScope, WorkerGlobalScopeHelpers}; use dom::window::{self, WindowHelpers, ScriptHelpers}; use devtools_traits::ScriptToDevtoolsControlMsg; use script_task::{ScriptChan, ScriptPort, CommonScriptMsg, ScriptTask}; use msg::constellation_msg::{ConstellationChan, PipelineId, WorkerId}; use net_traits::ResourceTask; use profile_traits::mem; use ipc_channel::ipc::IpcSender; use js::{JSCLASS_IS_GLOBAL, JSCLASS_IS_DOMJSCLASS}; use js::jsapi::{GetGlobalForObjectCrossCompartment}; use js::jsapi::{JSContext, JSObject, JS_GetClass, MutableHandleValue}; use url::Url; use util::mem::HeapSizeOf; /// A freely-copyable reference to a rooted global object. #[derive(Copy, Clone)] pub enum GlobalRef<'a> { /// A reference to a `Window` object. Window(&'a window::Window), /// A reference to a `WorkerGlobalScope` object. Worker(&'a WorkerGlobalScope), } /// A stack-based rooted reference to a global object. #[no_move] pub enum GlobalRoot { /// A root for a `Window` object. Window(Root<window::Window>), /// A root for a `WorkerGlobalScope` object. Worker(Root<WorkerGlobalScope>), } /// A traced reference to a global object, for use in fields of traced Rust /// structures. #[derive(JSTraceable, HeapSizeOf)] #[must_root] pub enum GlobalField { /// A field for a `Window` object. Window(JS<window::Window>), /// A field for a `WorkerGlobalScope` object. Worker(JS<WorkerGlobalScope>), } impl<'a> GlobalRef<'a> { /// Get the `JSContext` for the `JSRuntime` associated with the thread /// this global object is on. pub fn get_cx(&self) -> *mut JSContext { match *self { GlobalRef::Window(ref window) => window.get_cx(), GlobalRef::Worker(ref worker) => worker.get_cx(), } } /// Extract a `Window`, causing task failure if the global object is not /// a `Window`. pub fn as_window<'b>(&'b self) -> &'b window::Window { match *self { GlobalRef::Window(window) => window, GlobalRef::Worker(_) => panic!("expected a Window scope"), } } /// Get the `PipelineId` for this global scope. pub fn pipeline(&self) -> PipelineId { match *self { GlobalRef::Window(window) => window.pipeline(), GlobalRef::Worker(worker) => worker.pipeline(), } } /// Get a `mem::ProfilerChan` to send messages to the memory profiler task. pub fn mem_profiler_chan(&self) -> mem::ProfilerChan { match *self { GlobalRef::Window(window) => window.mem_profiler_chan(), GlobalRef::Worker(worker) => worker.mem_profiler_chan(), } } /// Get a `ConstellationChan` to send messages to the constellation channel when available. pub fn constellation_chan(&self) -> ConstellationChan { match *self { GlobalRef::Window(window) => window.constellation_chan(), GlobalRef::Worker(worker) => worker.constellation_chan(), } } /// Get an `IpcSender<ScriptToDevtoolsControlMsg>` to send messages to Devtools /// task when available. pub fn devtools_chan(&self) -> Option<IpcSender<ScriptToDevtoolsControlMsg>> { match *self { GlobalRef::Window(window) => window.devtools_chan(), GlobalRef::Worker(worker) => worker.devtools_chan(), } } /// Get the `ResourceTask` for this global scope. pub fn resource_task(&self) -> ResourceTask { match *self { GlobalRef::Window(ref window) => { let doc = window.Document(); let doc = doc.r(); let loader = doc.loader(); (*loader.resource_task).clone() } GlobalRef::Worker(ref worker) => worker.resource_task().clone(), } } /// Get the worker's id. pub fn get_worker_id(&self) -> Option<WorkerId> { match *self { GlobalRef::Window(_) => None, GlobalRef::Worker(ref worker) => Some(worker.get_worker_id()), } } /// Get next worker id. pub fn get_next_worker_id(&self) -> WorkerId { match *self { GlobalRef::Window(ref window) => window.get_next_worker_id(), GlobalRef::Worker(ref worker) => worker.get_next_worker_id() } } /// Get the URL for this global scope. pub fn get_url(&self) -> Url { match *self { GlobalRef::Window(ref window) => window.get_url(), GlobalRef::Worker(ref worker) => worker.get_url().clone(), } } /// `ScriptChan` used to send messages to the event loop of this global's /// thread. pub fn script_chan(&self) -> Box<ScriptChan+Send> { match *self { GlobalRef::Window(ref window) => window.script_chan(), GlobalRef::Worker(ref worker) => worker.script_chan(), } } /// Create a new sender/receiver pair that can be used to implement an on-demand /// event loop. Used for implementing web APIs that require blocking semantics /// without resorting to nested event loops. pub fn new_script_pair(&self) -> (Box<ScriptChan+Send>, Box<ScriptPort+Send>) { match *self { GlobalRef::Window(ref window) => window.new_script_pair(), GlobalRef::Worker(ref worker) => worker.new_script_pair(), } } /// Process a single event as if it were the next event in the task queue for /// this global. pub fn process_event(&self, msg: CommonScriptMsg) { match *self { GlobalRef::Window(_) => ScriptTask::process_event(msg), GlobalRef::Worker(ref worker) => worker.process_event(msg), } } /// Evaluate the JS messages on the `RootedValue` of this global pub fn evaluate_js_on_global_with_result(&self, code: &str, rval: MutableHandleValue) { match *self { GlobalRef::Window(window) => window.evaluate_js_on_global_with_result(code, rval), GlobalRef::Worker(worker) => worker.evaluate_js_on_global_with_result(code, rval), } } /// Set the `bool` value to indicate whether developer tools has requested /// updates from the global pub fn set_devtools_wants_updates(&self, send_updates: bool) { match *self { GlobalRef::Window(window) => window.set_devtools_wants_updates(send_updates), GlobalRef::Worker(worker) => worker.set_devtools_wants_updates(send_updates), } } } impl<'a> Reflectable for GlobalRef<'a> { fn reflector<'b>(&'b self) -> &'b Reflector { match *self { GlobalRef::Window(ref window) => window.reflector(), GlobalRef::Worker(ref worker) => worker.reflector(), } } } impl GlobalRoot { /// Obtain a safe reference to the global object that cannot outlive the /// lifetime of this root.
} } } impl GlobalField { /// Create a new `GlobalField` from a rooted reference. pub fn from_rooted(global: &GlobalRef) -> GlobalField { match *global { GlobalRef::Window(window) => GlobalField::Window(JS::from_ref(window)), GlobalRef::Worker(worker) => GlobalField::Worker(JS::from_ref(worker)), } } /// Create a stack-bounded root for this reference. pub fn root(&self) -> GlobalRoot { match *self { GlobalField::Window(ref window) => GlobalRoot::Window(window.root()), GlobalField::Worker(ref worker) => GlobalRoot::Worker(worker.root()), } } } /// Returns the global object of the realm that the given JS object was created in. #[allow(unrooted_must_root)] pub fn global_object_for_js_object(obj: *mut JSObject) -> GlobalRoot { unsafe { let global = GetGlobalForObjectCrossCompartment(obj); let clasp = JS_GetClass(global); assert!(((*clasp).flags & (JSCLASS_IS_DOMJSCLASS | JSCLASS_IS_GLOBAL))!= 0); match native_from_reflector_jsmanaged(global) { Ok(window) => return GlobalRoot::Window(window), Err(_) => (), } match native_from_reflector_jsmanaged(global) { Ok(worker) => return GlobalRoot::Worker(worker), Err(_) => (), } panic!("found DOM global that doesn't unwrap to Window or WorkerGlobalScope") } }
pub fn r<'c>(&'c self) -> GlobalRef<'c> { match *self { GlobalRoot::Window(ref window) => GlobalRef::Window(window.r()), GlobalRoot::Worker(ref worker) => GlobalRef::Worker(worker.r()),
random_line_split
global.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/. */ //! Abstractions for global scopes. //! //! This module contains smart pointers to global scopes, to simplify writing //! code that works in workers as well as window scopes. use dom::bindings::codegen::Bindings::WindowBinding::WindowMethods; use dom::bindings::conversions::native_from_reflector_jsmanaged; use dom::bindings::js::{JS, Root}; use dom::bindings::utils::{Reflectable, Reflector}; use dom::document::DocumentHelpers; use dom::workerglobalscope::{WorkerGlobalScope, WorkerGlobalScopeHelpers}; use dom::window::{self, WindowHelpers, ScriptHelpers}; use devtools_traits::ScriptToDevtoolsControlMsg; use script_task::{ScriptChan, ScriptPort, CommonScriptMsg, ScriptTask}; use msg::constellation_msg::{ConstellationChan, PipelineId, WorkerId}; use net_traits::ResourceTask; use profile_traits::mem; use ipc_channel::ipc::IpcSender; use js::{JSCLASS_IS_GLOBAL, JSCLASS_IS_DOMJSCLASS}; use js::jsapi::{GetGlobalForObjectCrossCompartment}; use js::jsapi::{JSContext, JSObject, JS_GetClass, MutableHandleValue}; use url::Url; use util::mem::HeapSizeOf; /// A freely-copyable reference to a rooted global object. #[derive(Copy, Clone)] pub enum GlobalRef<'a> { /// A reference to a `Window` object. Window(&'a window::Window), /// A reference to a `WorkerGlobalScope` object. Worker(&'a WorkerGlobalScope), } /// A stack-based rooted reference to a global object. #[no_move] pub enum GlobalRoot { /// A root for a `Window` object. Window(Root<window::Window>), /// A root for a `WorkerGlobalScope` object. Worker(Root<WorkerGlobalScope>), } /// A traced reference to a global object, for use in fields of traced Rust /// structures. #[derive(JSTraceable, HeapSizeOf)] #[must_root] pub enum GlobalField { /// A field for a `Window` object. Window(JS<window::Window>), /// A field for a `WorkerGlobalScope` object. Worker(JS<WorkerGlobalScope>), } impl<'a> GlobalRef<'a> { /// Get the `JSContext` for the `JSRuntime` associated with the thread /// this global object is on. pub fn get_cx(&self) -> *mut JSContext { match *self { GlobalRef::Window(ref window) => window.get_cx(), GlobalRef::Worker(ref worker) => worker.get_cx(), } } /// Extract a `Window`, causing task failure if the global object is not /// a `Window`. pub fn as_window<'b>(&'b self) -> &'b window::Window { match *self { GlobalRef::Window(window) => window, GlobalRef::Worker(_) => panic!("expected a Window scope"), } } /// Get the `PipelineId` for this global scope. pub fn pipeline(&self) -> PipelineId { match *self { GlobalRef::Window(window) => window.pipeline(), GlobalRef::Worker(worker) => worker.pipeline(), } } /// Get a `mem::ProfilerChan` to send messages to the memory profiler task. pub fn mem_profiler_chan(&self) -> mem::ProfilerChan { match *self { GlobalRef::Window(window) => window.mem_profiler_chan(), GlobalRef::Worker(worker) => worker.mem_profiler_chan(), } } /// Get a `ConstellationChan` to send messages to the constellation channel when available. pub fn constellation_chan(&self) -> ConstellationChan { match *self { GlobalRef::Window(window) => window.constellation_chan(), GlobalRef::Worker(worker) => worker.constellation_chan(), } } /// Get an `IpcSender<ScriptToDevtoolsControlMsg>` to send messages to Devtools /// task when available. pub fn devtools_chan(&self) -> Option<IpcSender<ScriptToDevtoolsControlMsg>> { match *self { GlobalRef::Window(window) => window.devtools_chan(), GlobalRef::Worker(worker) => worker.devtools_chan(), } } /// Get the `ResourceTask` for this global scope. pub fn resource_task(&self) -> ResourceTask { match *self { GlobalRef::Window(ref window) => { let doc = window.Document(); let doc = doc.r(); let loader = doc.loader(); (*loader.resource_task).clone() } GlobalRef::Worker(ref worker) => worker.resource_task().clone(), } } /// Get the worker's id. pub fn get_worker_id(&self) -> Option<WorkerId> { match *self { GlobalRef::Window(_) => None, GlobalRef::Worker(ref worker) => Some(worker.get_worker_id()), } } /// Get next worker id. pub fn get_next_worker_id(&self) -> WorkerId
/// Get the URL for this global scope. pub fn get_url(&self) -> Url { match *self { GlobalRef::Window(ref window) => window.get_url(), GlobalRef::Worker(ref worker) => worker.get_url().clone(), } } /// `ScriptChan` used to send messages to the event loop of this global's /// thread. pub fn script_chan(&self) -> Box<ScriptChan+Send> { match *self { GlobalRef::Window(ref window) => window.script_chan(), GlobalRef::Worker(ref worker) => worker.script_chan(), } } /// Create a new sender/receiver pair that can be used to implement an on-demand /// event loop. Used for implementing web APIs that require blocking semantics /// without resorting to nested event loops. pub fn new_script_pair(&self) -> (Box<ScriptChan+Send>, Box<ScriptPort+Send>) { match *self { GlobalRef::Window(ref window) => window.new_script_pair(), GlobalRef::Worker(ref worker) => worker.new_script_pair(), } } /// Process a single event as if it were the next event in the task queue for /// this global. pub fn process_event(&self, msg: CommonScriptMsg) { match *self { GlobalRef::Window(_) => ScriptTask::process_event(msg), GlobalRef::Worker(ref worker) => worker.process_event(msg), } } /// Evaluate the JS messages on the `RootedValue` of this global pub fn evaluate_js_on_global_with_result(&self, code: &str, rval: MutableHandleValue) { match *self { GlobalRef::Window(window) => window.evaluate_js_on_global_with_result(code, rval), GlobalRef::Worker(worker) => worker.evaluate_js_on_global_with_result(code, rval), } } /// Set the `bool` value to indicate whether developer tools has requested /// updates from the global pub fn set_devtools_wants_updates(&self, send_updates: bool) { match *self { GlobalRef::Window(window) => window.set_devtools_wants_updates(send_updates), GlobalRef::Worker(worker) => worker.set_devtools_wants_updates(send_updates), } } } impl<'a> Reflectable for GlobalRef<'a> { fn reflector<'b>(&'b self) -> &'b Reflector { match *self { GlobalRef::Window(ref window) => window.reflector(), GlobalRef::Worker(ref worker) => worker.reflector(), } } } impl GlobalRoot { /// Obtain a safe reference to the global object that cannot outlive the /// lifetime of this root. pub fn r<'c>(&'c self) -> GlobalRef<'c> { match *self { GlobalRoot::Window(ref window) => GlobalRef::Window(window.r()), GlobalRoot::Worker(ref worker) => GlobalRef::Worker(worker.r()), } } } impl GlobalField { /// Create a new `GlobalField` from a rooted reference. pub fn from_rooted(global: &GlobalRef) -> GlobalField { match *global { GlobalRef::Window(window) => GlobalField::Window(JS::from_ref(window)), GlobalRef::Worker(worker) => GlobalField::Worker(JS::from_ref(worker)), } } /// Create a stack-bounded root for this reference. pub fn root(&self) -> GlobalRoot { match *self { GlobalField::Window(ref window) => GlobalRoot::Window(window.root()), GlobalField::Worker(ref worker) => GlobalRoot::Worker(worker.root()), } } } /// Returns the global object of the realm that the given JS object was created in. #[allow(unrooted_must_root)] pub fn global_object_for_js_object(obj: *mut JSObject) -> GlobalRoot { unsafe { let global = GetGlobalForObjectCrossCompartment(obj); let clasp = JS_GetClass(global); assert!(((*clasp).flags & (JSCLASS_IS_DOMJSCLASS | JSCLASS_IS_GLOBAL))!= 0); match native_from_reflector_jsmanaged(global) { Ok(window) => return GlobalRoot::Window(window), Err(_) => (), } match native_from_reflector_jsmanaged(global) { Ok(worker) => return GlobalRoot::Worker(worker), Err(_) => (), } panic!("found DOM global that doesn't unwrap to Window or WorkerGlobalScope") } }
{ match *self { GlobalRef::Window(ref window) => window.get_next_worker_id(), GlobalRef::Worker(ref worker) => worker.get_next_worker_id() } }
identifier_body
global.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/. */ //! Abstractions for global scopes. //! //! This module contains smart pointers to global scopes, to simplify writing //! code that works in workers as well as window scopes. use dom::bindings::codegen::Bindings::WindowBinding::WindowMethods; use dom::bindings::conversions::native_from_reflector_jsmanaged; use dom::bindings::js::{JS, Root}; use dom::bindings::utils::{Reflectable, Reflector}; use dom::document::DocumentHelpers; use dom::workerglobalscope::{WorkerGlobalScope, WorkerGlobalScopeHelpers}; use dom::window::{self, WindowHelpers, ScriptHelpers}; use devtools_traits::ScriptToDevtoolsControlMsg; use script_task::{ScriptChan, ScriptPort, CommonScriptMsg, ScriptTask}; use msg::constellation_msg::{ConstellationChan, PipelineId, WorkerId}; use net_traits::ResourceTask; use profile_traits::mem; use ipc_channel::ipc::IpcSender; use js::{JSCLASS_IS_GLOBAL, JSCLASS_IS_DOMJSCLASS}; use js::jsapi::{GetGlobalForObjectCrossCompartment}; use js::jsapi::{JSContext, JSObject, JS_GetClass, MutableHandleValue}; use url::Url; use util::mem::HeapSizeOf; /// A freely-copyable reference to a rooted global object. #[derive(Copy, Clone)] pub enum GlobalRef<'a> { /// A reference to a `Window` object. Window(&'a window::Window), /// A reference to a `WorkerGlobalScope` object. Worker(&'a WorkerGlobalScope), } /// A stack-based rooted reference to a global object. #[no_move] pub enum GlobalRoot { /// A root for a `Window` object. Window(Root<window::Window>), /// A root for a `WorkerGlobalScope` object. Worker(Root<WorkerGlobalScope>), } /// A traced reference to a global object, for use in fields of traced Rust /// structures. #[derive(JSTraceable, HeapSizeOf)] #[must_root] pub enum GlobalField { /// A field for a `Window` object. Window(JS<window::Window>), /// A field for a `WorkerGlobalScope` object. Worker(JS<WorkerGlobalScope>), } impl<'a> GlobalRef<'a> { /// Get the `JSContext` for the `JSRuntime` associated with the thread /// this global object is on. pub fn
(&self) -> *mut JSContext { match *self { GlobalRef::Window(ref window) => window.get_cx(), GlobalRef::Worker(ref worker) => worker.get_cx(), } } /// Extract a `Window`, causing task failure if the global object is not /// a `Window`. pub fn as_window<'b>(&'b self) -> &'b window::Window { match *self { GlobalRef::Window(window) => window, GlobalRef::Worker(_) => panic!("expected a Window scope"), } } /// Get the `PipelineId` for this global scope. pub fn pipeline(&self) -> PipelineId { match *self { GlobalRef::Window(window) => window.pipeline(), GlobalRef::Worker(worker) => worker.pipeline(), } } /// Get a `mem::ProfilerChan` to send messages to the memory profiler task. pub fn mem_profiler_chan(&self) -> mem::ProfilerChan { match *self { GlobalRef::Window(window) => window.mem_profiler_chan(), GlobalRef::Worker(worker) => worker.mem_profiler_chan(), } } /// Get a `ConstellationChan` to send messages to the constellation channel when available. pub fn constellation_chan(&self) -> ConstellationChan { match *self { GlobalRef::Window(window) => window.constellation_chan(), GlobalRef::Worker(worker) => worker.constellation_chan(), } } /// Get an `IpcSender<ScriptToDevtoolsControlMsg>` to send messages to Devtools /// task when available. pub fn devtools_chan(&self) -> Option<IpcSender<ScriptToDevtoolsControlMsg>> { match *self { GlobalRef::Window(window) => window.devtools_chan(), GlobalRef::Worker(worker) => worker.devtools_chan(), } } /// Get the `ResourceTask` for this global scope. pub fn resource_task(&self) -> ResourceTask { match *self { GlobalRef::Window(ref window) => { let doc = window.Document(); let doc = doc.r(); let loader = doc.loader(); (*loader.resource_task).clone() } GlobalRef::Worker(ref worker) => worker.resource_task().clone(), } } /// Get the worker's id. pub fn get_worker_id(&self) -> Option<WorkerId> { match *self { GlobalRef::Window(_) => None, GlobalRef::Worker(ref worker) => Some(worker.get_worker_id()), } } /// Get next worker id. pub fn get_next_worker_id(&self) -> WorkerId { match *self { GlobalRef::Window(ref window) => window.get_next_worker_id(), GlobalRef::Worker(ref worker) => worker.get_next_worker_id() } } /// Get the URL for this global scope. pub fn get_url(&self) -> Url { match *self { GlobalRef::Window(ref window) => window.get_url(), GlobalRef::Worker(ref worker) => worker.get_url().clone(), } } /// `ScriptChan` used to send messages to the event loop of this global's /// thread. pub fn script_chan(&self) -> Box<ScriptChan+Send> { match *self { GlobalRef::Window(ref window) => window.script_chan(), GlobalRef::Worker(ref worker) => worker.script_chan(), } } /// Create a new sender/receiver pair that can be used to implement an on-demand /// event loop. Used for implementing web APIs that require blocking semantics /// without resorting to nested event loops. pub fn new_script_pair(&self) -> (Box<ScriptChan+Send>, Box<ScriptPort+Send>) { match *self { GlobalRef::Window(ref window) => window.new_script_pair(), GlobalRef::Worker(ref worker) => worker.new_script_pair(), } } /// Process a single event as if it were the next event in the task queue for /// this global. pub fn process_event(&self, msg: CommonScriptMsg) { match *self { GlobalRef::Window(_) => ScriptTask::process_event(msg), GlobalRef::Worker(ref worker) => worker.process_event(msg), } } /// Evaluate the JS messages on the `RootedValue` of this global pub fn evaluate_js_on_global_with_result(&self, code: &str, rval: MutableHandleValue) { match *self { GlobalRef::Window(window) => window.evaluate_js_on_global_with_result(code, rval), GlobalRef::Worker(worker) => worker.evaluate_js_on_global_with_result(code, rval), } } /// Set the `bool` value to indicate whether developer tools has requested /// updates from the global pub fn set_devtools_wants_updates(&self, send_updates: bool) { match *self { GlobalRef::Window(window) => window.set_devtools_wants_updates(send_updates), GlobalRef::Worker(worker) => worker.set_devtools_wants_updates(send_updates), } } } impl<'a> Reflectable for GlobalRef<'a> { fn reflector<'b>(&'b self) -> &'b Reflector { match *self { GlobalRef::Window(ref window) => window.reflector(), GlobalRef::Worker(ref worker) => worker.reflector(), } } } impl GlobalRoot { /// Obtain a safe reference to the global object that cannot outlive the /// lifetime of this root. pub fn r<'c>(&'c self) -> GlobalRef<'c> { match *self { GlobalRoot::Window(ref window) => GlobalRef::Window(window.r()), GlobalRoot::Worker(ref worker) => GlobalRef::Worker(worker.r()), } } } impl GlobalField { /// Create a new `GlobalField` from a rooted reference. pub fn from_rooted(global: &GlobalRef) -> GlobalField { match *global { GlobalRef::Window(window) => GlobalField::Window(JS::from_ref(window)), GlobalRef::Worker(worker) => GlobalField::Worker(JS::from_ref(worker)), } } /// Create a stack-bounded root for this reference. pub fn root(&self) -> GlobalRoot { match *self { GlobalField::Window(ref window) => GlobalRoot::Window(window.root()), GlobalField::Worker(ref worker) => GlobalRoot::Worker(worker.root()), } } } /// Returns the global object of the realm that the given JS object was created in. #[allow(unrooted_must_root)] pub fn global_object_for_js_object(obj: *mut JSObject) -> GlobalRoot { unsafe { let global = GetGlobalForObjectCrossCompartment(obj); let clasp = JS_GetClass(global); assert!(((*clasp).flags & (JSCLASS_IS_DOMJSCLASS | JSCLASS_IS_GLOBAL))!= 0); match native_from_reflector_jsmanaged(global) { Ok(window) => return GlobalRoot::Window(window), Err(_) => (), } match native_from_reflector_jsmanaged(global) { Ok(worker) => return GlobalRoot::Worker(worker), Err(_) => (), } panic!("found DOM global that doesn't unwrap to Window or WorkerGlobalScope") } }
get_cx
identifier_name
any.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. //! Traits for dynamic typing of any `'static` type (through runtime reflection) //! //! This module implements the `Any` trait, which enables dynamic typing //! of any `'static` type through runtime reflection. //! //! `Any` itself can be used to get a `TypeId`, and has more features when used //! as a trait object. As `&Any` (a borrowed trait object), it has the `is` and //! `as_ref` methods, to test if the contained value is of a given type, and to //! get a reference to the inner value as a type. As`&mut Any`, there is also //! the `as_mut` method, for getting a mutable reference to the inner value. //! `Box<Any>` adds the `move` method, which will unwrap a `Box<T>` from the //! object. See the extension traits (`*Ext`) for the full details. //! //! Note that &Any is limited to testing whether a value is of a specified //! concrete type, and cannot be used to test whether a type implements a trait. //! //! # Examples //! //! Consider a situation where we want to log out a value passed to a function. //! We know the value we're working on implements Show, but we don't know its //! concrete type. We want to give special treatment to certain types: in this //! case printing out the length of String values prior to their value. //! We don't know the concrete type of our value at compile time, so we need to //! use runtime reflection instead. //! //! ```rust //! use std::fmt::Show; //! use std::any::Any; //! //! // Logger function for any type that implements Show. //! fn log<T: Any+Show>(value: &T) { //! let value_any = value as &Any; //! //! // try to convert our value to a String. If successful, we want to //! // output the String's length as well as its value. If not, it's a //! // different type: just print it out unadorned. //! match value_any.downcast_ref::<String>() { //! Some(as_string) => { //! println!("String ({}): {}", as_string.len(), as_string); //! } //! None => { //! println!("{:?}", value); //! } //! } //! } //! //! // This function wants to log its parameter out prior to doing work with it. //! fn do_work<T: Show+'static>(value: &T) { //! log(value); //! //...do some other work //! } //! //! fn main() { //! let my_string = "Hello World".to_string(); //! do_work(&my_string); //! //! let my_i8: i8 = 100; //! do_work(&my_i8); //! } //! ``` #![stable] use mem::{transmute}; use option::Option; use option::Option::{Some, None}; use raw::TraitObject; use intrinsics::TypeId; /////////////////////////////////////////////////////////////////////////////// // Any trait /////////////////////////////////////////////////////////////////////////////// /// The `Any` trait is implemented by all `'static` types, and can be used for /// dynamic typing /// /// Every type with no non-`'static` references implements `Any`, so `Any` can /// be used as a trait object to emulate the effects dynamic typing. #[stable] pub trait Any:'static { /// Get the `TypeId` of `self` #[unstable = "this method will likely be replaced by an associated static"] fn get_type_id(&self) -> TypeId; } impl<T:'static> Any for T { fn get_type_id(&self) -> TypeId { TypeId::of::<T>() } } /////////////////////////////////////////////////////////////////////////////// // Extension methods for Any trait objects. // Implemented as three extension traits so that the methods can be generic. /////////////////////////////////////////////////////////////////////////////// impl Any { /// Returns true if the boxed type is the same as `T` #[stable] #[inline] pub fn is<T:'static>(&self) -> bool { // Get TypeId of the type this function is instantiated with let t = TypeId::of::<T>(); // Get TypeId of the type in the trait object let boxed = self.get_type_id(); // Compare both TypeIds on equality t == boxed } /// Returns some reference to the boxed value if it is of type `T`, or /// `None` if it isn't. #[unstable = "naming conventions around acquiring references may change"] #[inline] pub fn downcast_ref<'a, T:'static>(&'a self) -> Option<&'a T> { if self.is::<T>()
else { None } } /// Returns some mutable reference to the boxed value if it is of type `T`, or /// `None` if it isn't. #[unstable = "naming conventions around acquiring references may change"] #[inline] pub fn downcast_mut<'a, T:'static>(&'a mut self) -> Option<&'a mut T> { if self.is::<T>() { unsafe { // Get the raw representation of the trait object let to: TraitObject = transmute(self); // Extract the data pointer Some(transmute(to.data)) } } else { None } } }
{ unsafe { // Get the raw representation of the trait object let to: TraitObject = transmute(self); // Extract the data pointer Some(transmute(to.data)) } }
conditional_block
any.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. //! Traits for dynamic typing of any `'static` type (through runtime reflection) //! //! This module implements the `Any` trait, which enables dynamic typing //! of any `'static` type through runtime reflection. //! //! `Any` itself can be used to get a `TypeId`, and has more features when used //! as a trait object. As `&Any` (a borrowed trait object), it has the `is` and //! `as_ref` methods, to test if the contained value is of a given type, and to //! get a reference to the inner value as a type. As`&mut Any`, there is also //! the `as_mut` method, for getting a mutable reference to the inner value. //! `Box<Any>` adds the `move` method, which will unwrap a `Box<T>` from the //! object. See the extension traits (`*Ext`) for the full details. //! //! Note that &Any is limited to testing whether a value is of a specified //! concrete type, and cannot be used to test whether a type implements a trait. //! //! # Examples //! //! Consider a situation where we want to log out a value passed to a function. //! We know the value we're working on implements Show, but we don't know its //! concrete type. We want to give special treatment to certain types: in this //! case printing out the length of String values prior to their value. //! We don't know the concrete type of our value at compile time, so we need to //! use runtime reflection instead. //! //! ```rust //! use std::fmt::Show; //! use std::any::Any; //! //! // Logger function for any type that implements Show. //! fn log<T: Any+Show>(value: &T) { //! let value_any = value as &Any; //! //! // try to convert our value to a String. If successful, we want to //! // output the String's length as well as its value. If not, it's a //! // different type: just print it out unadorned. //! match value_any.downcast_ref::<String>() { //! Some(as_string) => { //! println!("String ({}): {}", as_string.len(), as_string); //! } //! None => { //! println!("{:?}", value); //! } //! } //! } //! //! // This function wants to log its parameter out prior to doing work with it. //! fn do_work<T: Show+'static>(value: &T) { //! log(value); //! //...do some other work //! } //! //! fn main() { //! let my_string = "Hello World".to_string(); //! do_work(&my_string); //! //! let my_i8: i8 = 100; //! do_work(&my_i8); //! } //! ``` #![stable] use mem::{transmute}; use option::Option; use option::Option::{Some, None}; use raw::TraitObject; use intrinsics::TypeId; /////////////////////////////////////////////////////////////////////////////// // Any trait /////////////////////////////////////////////////////////////////////////////// /// The `Any` trait is implemented by all `'static` types, and can be used for /// dynamic typing /// /// Every type with no non-`'static` references implements `Any`, so `Any` can /// be used as a trait object to emulate the effects dynamic typing. #[stable] pub trait Any:'static { /// Get the `TypeId` of `self` #[unstable = "this method will likely be replaced by an associated static"] fn get_type_id(&self) -> TypeId; } impl<T:'static> Any for T { fn get_type_id(&self) -> TypeId { TypeId::of::<T>() } } /////////////////////////////////////////////////////////////////////////////// // Extension methods for Any trait objects. // Implemented as three extension traits so that the methods can be generic. /////////////////////////////////////////////////////////////////////////////// impl Any { /// Returns true if the boxed type is the same as `T` #[stable] #[inline] pub fn is<T:'static>(&self) -> bool { // Get TypeId of the type this function is instantiated with let t = TypeId::of::<T>(); // Get TypeId of the type in the trait object let boxed = self.get_type_id(); // Compare both TypeIds on equality t == boxed } /// Returns some reference to the boxed value if it is of type `T`, or /// `None` if it isn't. #[unstable = "naming conventions around acquiring references may change"] #[inline] pub fn downcast_ref<'a, T:'static>(&'a self) -> Option<&'a T> { if self.is::<T>() { unsafe { // Get the raw representation of the trait object let to: TraitObject = transmute(self); // Extract the data pointer Some(transmute(to.data)) } } else { None } } /// Returns some mutable reference to the boxed value if it is of type `T`, or /// `None` if it isn't. #[unstable = "naming conventions around acquiring references may change"] #[inline] pub fn
<'a, T:'static>(&'a mut self) -> Option<&'a mut T> { if self.is::<T>() { unsafe { // Get the raw representation of the trait object let to: TraitObject = transmute(self); // Extract the data pointer Some(transmute(to.data)) } } else { None } } }
downcast_mut
identifier_name
any.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. //! Traits for dynamic typing of any `'static` type (through runtime reflection) //! //! This module implements the `Any` trait, which enables dynamic typing //! of any `'static` type through runtime reflection. //! //! `Any` itself can be used to get a `TypeId`, and has more features when used //! as a trait object. As `&Any` (a borrowed trait object), it has the `is` and //! `as_ref` methods, to test if the contained value is of a given type, and to //! get a reference to the inner value as a type. As`&mut Any`, there is also //! the `as_mut` method, for getting a mutable reference to the inner value. //! `Box<Any>` adds the `move` method, which will unwrap a `Box<T>` from the //! object. See the extension traits (`*Ext`) for the full details. //! //! Note that &Any is limited to testing whether a value is of a specified //! concrete type, and cannot be used to test whether a type implements a trait. //! //! # Examples //! //! Consider a situation where we want to log out a value passed to a function. //! We know the value we're working on implements Show, but we don't know its //! concrete type. We want to give special treatment to certain types: in this //! case printing out the length of String values prior to their value. //! We don't know the concrete type of our value at compile time, so we need to //! use runtime reflection instead. //! //! ```rust //! use std::fmt::Show; //! use std::any::Any; //! //! // Logger function for any type that implements Show. //! fn log<T: Any+Show>(value: &T) { //! let value_any = value as &Any; //! //! // try to convert our value to a String. If successful, we want to //! // output the String's length as well as its value. If not, it's a //! // different type: just print it out unadorned. //! match value_any.downcast_ref::<String>() { //! Some(as_string) => { //! println!("String ({}): {}", as_string.len(), as_string); //! } //! None => { //! println!("{:?}", value); //! } //! } //! } //! //! // This function wants to log its parameter out prior to doing work with it. //! fn do_work<T: Show+'static>(value: &T) { //! log(value); //! //...do some other work //! } //! //! fn main() { //! let my_string = "Hello World".to_string(); //! do_work(&my_string); //! //! let my_i8: i8 = 100; //! do_work(&my_i8); //! } //! ``` #![stable] use mem::{transmute}; use option::Option; use option::Option::{Some, None}; use raw::TraitObject; use intrinsics::TypeId; /////////////////////////////////////////////////////////////////////////////// // Any trait /////////////////////////////////////////////////////////////////////////////// /// The `Any` trait is implemented by all `'static` types, and can be used for
/// be used as a trait object to emulate the effects dynamic typing. #[stable] pub trait Any:'static { /// Get the `TypeId` of `self` #[unstable = "this method will likely be replaced by an associated static"] fn get_type_id(&self) -> TypeId; } impl<T:'static> Any for T { fn get_type_id(&self) -> TypeId { TypeId::of::<T>() } } /////////////////////////////////////////////////////////////////////////////// // Extension methods for Any trait objects. // Implemented as three extension traits so that the methods can be generic. /////////////////////////////////////////////////////////////////////////////// impl Any { /// Returns true if the boxed type is the same as `T` #[stable] #[inline] pub fn is<T:'static>(&self) -> bool { // Get TypeId of the type this function is instantiated with let t = TypeId::of::<T>(); // Get TypeId of the type in the trait object let boxed = self.get_type_id(); // Compare both TypeIds on equality t == boxed } /// Returns some reference to the boxed value if it is of type `T`, or /// `None` if it isn't. #[unstable = "naming conventions around acquiring references may change"] #[inline] pub fn downcast_ref<'a, T:'static>(&'a self) -> Option<&'a T> { if self.is::<T>() { unsafe { // Get the raw representation of the trait object let to: TraitObject = transmute(self); // Extract the data pointer Some(transmute(to.data)) } } else { None } } /// Returns some mutable reference to the boxed value if it is of type `T`, or /// `None` if it isn't. #[unstable = "naming conventions around acquiring references may change"] #[inline] pub fn downcast_mut<'a, T:'static>(&'a mut self) -> Option<&'a mut T> { if self.is::<T>() { unsafe { // Get the raw representation of the trait object let to: TraitObject = transmute(self); // Extract the data pointer Some(transmute(to.data)) } } else { None } } }
/// dynamic typing /// /// Every type with no non-`'static` references implements `Any`, so `Any` can
random_line_split
any.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. //! Traits for dynamic typing of any `'static` type (through runtime reflection) //! //! This module implements the `Any` trait, which enables dynamic typing //! of any `'static` type through runtime reflection. //! //! `Any` itself can be used to get a `TypeId`, and has more features when used //! as a trait object. As `&Any` (a borrowed trait object), it has the `is` and //! `as_ref` methods, to test if the contained value is of a given type, and to //! get a reference to the inner value as a type. As`&mut Any`, there is also //! the `as_mut` method, for getting a mutable reference to the inner value. //! `Box<Any>` adds the `move` method, which will unwrap a `Box<T>` from the //! object. See the extension traits (`*Ext`) for the full details. //! //! Note that &Any is limited to testing whether a value is of a specified //! concrete type, and cannot be used to test whether a type implements a trait. //! //! # Examples //! //! Consider a situation where we want to log out a value passed to a function. //! We know the value we're working on implements Show, but we don't know its //! concrete type. We want to give special treatment to certain types: in this //! case printing out the length of String values prior to their value. //! We don't know the concrete type of our value at compile time, so we need to //! use runtime reflection instead. //! //! ```rust //! use std::fmt::Show; //! use std::any::Any; //! //! // Logger function for any type that implements Show. //! fn log<T: Any+Show>(value: &T) { //! let value_any = value as &Any; //! //! // try to convert our value to a String. If successful, we want to //! // output the String's length as well as its value. If not, it's a //! // different type: just print it out unadorned. //! match value_any.downcast_ref::<String>() { //! Some(as_string) => { //! println!("String ({}): {}", as_string.len(), as_string); //! } //! None => { //! println!("{:?}", value); //! } //! } //! } //! //! // This function wants to log its parameter out prior to doing work with it. //! fn do_work<T: Show+'static>(value: &T) { //! log(value); //! //...do some other work //! } //! //! fn main() { //! let my_string = "Hello World".to_string(); //! do_work(&my_string); //! //! let my_i8: i8 = 100; //! do_work(&my_i8); //! } //! ``` #![stable] use mem::{transmute}; use option::Option; use option::Option::{Some, None}; use raw::TraitObject; use intrinsics::TypeId; /////////////////////////////////////////////////////////////////////////////// // Any trait /////////////////////////////////////////////////////////////////////////////// /// The `Any` trait is implemented by all `'static` types, and can be used for /// dynamic typing /// /// Every type with no non-`'static` references implements `Any`, so `Any` can /// be used as a trait object to emulate the effects dynamic typing. #[stable] pub trait Any:'static { /// Get the `TypeId` of `self` #[unstable = "this method will likely be replaced by an associated static"] fn get_type_id(&self) -> TypeId; } impl<T:'static> Any for T { fn get_type_id(&self) -> TypeId { TypeId::of::<T>() } } /////////////////////////////////////////////////////////////////////////////// // Extension methods for Any trait objects. // Implemented as three extension traits so that the methods can be generic. /////////////////////////////////////////////////////////////////////////////// impl Any { /// Returns true if the boxed type is the same as `T` #[stable] #[inline] pub fn is<T:'static>(&self) -> bool { // Get TypeId of the type this function is instantiated with let t = TypeId::of::<T>(); // Get TypeId of the type in the trait object let boxed = self.get_type_id(); // Compare both TypeIds on equality t == boxed } /// Returns some reference to the boxed value if it is of type `T`, or /// `None` if it isn't. #[unstable = "naming conventions around acquiring references may change"] #[inline] pub fn downcast_ref<'a, T:'static>(&'a self) -> Option<&'a T> { if self.is::<T>() { unsafe { // Get the raw representation of the trait object let to: TraitObject = transmute(self); // Extract the data pointer Some(transmute(to.data)) } } else { None } } /// Returns some mutable reference to the boxed value if it is of type `T`, or /// `None` if it isn't. #[unstable = "naming conventions around acquiring references may change"] #[inline] pub fn downcast_mut<'a, T:'static>(&'a mut self) -> Option<&'a mut T>
}
{ if self.is::<T>() { unsafe { // Get the raw representation of the trait object let to: TraitObject = transmute(self); // Extract the data pointer Some(transmute(to.data)) } } else { None } }
identifier_body
session.rs
use prodbg_api::read_write::{Reader, Writer}; use prodbg_api::backend::{CBackendCallbacks}; use plugins::PluginHandler; use reader_wrapper::{ReaderWrapper, WriterWrapper}; use backend_plugin::{BackendHandle, BackendPlugins}; use libc::{c_void}; #[derive(PartialEq, Eq, Clone, Copy, Debug)] pub struct SessionHandle(pub u64); ///! Session is a major part of ProDBG. There can be several sessions active at the same time ///! and each session has exactly one backend. There are only communication internally in a session ///! sessions can't (at least now) not talk to eachother. ///! ///! A backend can have several views at the same time. Data can be sent between the backend and ///| views using the PDReader/PDWriter APIs (prodbg::Writer prodbg::Reader in Rust) and this is the ///| only way for views and backends to talk with each other. There are several reasons for this ///| approach: ///! ///| 1. No "hacks" on trying to share memory. Plugins can be over a socket/webview/etc. ///! 2. Views and backends makes no assumetions on the inner workings of the others. ///! 3. Backends and views can post messages which anyone can decide to (optionally) act on. ///! pub struct Session { pub handle: SessionHandle, pub reader: Reader, current_writer: usize, writers: [Writer; 2], backend: Option<BackendHandle>, } ///! Connection options for Remote connections. Currently just one Ip adderss ///! pub struct ConnectionSettings<'a> { pub address: &'a str, } impl Session { pub fn new(handle: SessionHandle) -> Session { Session { handle: handle, writers: [ WriterWrapper::create_writer(), WriterWrapper::create_writer(), ], reader: ReaderWrapper::create_reader(), current_writer: 0, backend: None, } } pub fn get_current_writer(&mut self) -> &mut Writer { &mut self.writers[self.current_writer] } pub fn start_remote(_plugin_handler: &PluginHandler, _settings: &ConnectionSettings) {} pub fn start_local(_: &str, _: usize) {} pub fn set_backend(&mut self, backend: Option<BackendHandle>) { self.backend = backend } pub fn update(&mut self, backend_plugins: &mut BackendPlugins) { // swap the writers let c_writer = self.current_writer; let p_writer = (self.current_writer + 1) & 1; self.current_writer = p_writer; ReaderWrapper::init_from_writer(&mut self.reader, &self.writers[p_writer]); ReaderWrapper::reset_writer(&mut self.writers[c_writer]); if let Some(backend) = backend_plugins.get_backend(self.backend) { unsafe { let plugin_funcs = backend.plugin_type.plugin_funcs as *mut CBackendCallbacks; ((*plugin_funcs).update.unwrap())(backend.plugin_data, 0, self.reader.api as *mut c_void, self.writers[p_writer].api as *mut c_void); } } } } /// /// Sessions handler /// pub struct Sessions { instances: Vec<Session>, current: usize, session_counter: SessionHandle, } impl Sessions { pub fn new() -> Sessions { Sessions { instances: Vec::new(), current: 0, session_counter: SessionHandle(0), } } pub fn create_instance(&mut self) -> SessionHandle { let s = Session::new(self.session_counter); let handle = s.handle; self.instances.push(s); self.session_counter.0 += 1; handle } pub fn update(&mut self, backend_plugins: &mut BackendPlugins) { for session in self.instances.iter_mut() { session.update(backend_plugins); } } pub fn get_current(&mut self) -> &mut Session { let current = self.current; &mut self.instances[current] } pub fn get_session(&mut self, handle: SessionHandle) -> Option<&mut Session> { for i in 0..self.instances.len() { if self.instances[i].handle == handle { return Some(&mut self.instances[i]); } } None } } #[cfg(test)] mod tests { use core::reader_wrapper::{ReaderWrapper}; use super::*; #[test] fn create_session() { let _session = Session::new(); } #[test] fn write_simple_event()
}
{ let mut session = Session::new(); session.writers[0].event_begin(0x44); session.writers[0].event_end(); ReaderWrapper::init_from_writer(&mut session.reader, &session.writers[0]); assert_eq!(session.reader.get_event().unwrap(), 0x44); }
identifier_body
session.rs
use prodbg_api::read_write::{Reader, Writer}; use prodbg_api::backend::{CBackendCallbacks}; use plugins::PluginHandler; use reader_wrapper::{ReaderWrapper, WriterWrapper}; use backend_plugin::{BackendHandle, BackendPlugins}; use libc::{c_void}; #[derive(PartialEq, Eq, Clone, Copy, Debug)] pub struct SessionHandle(pub u64); ///! Session is a major part of ProDBG. There can be several sessions active at the same time ///! and each session has exactly one backend. There are only communication internally in a session ///! sessions can't (at least now) not talk to eachother. ///! ///! A backend can have several views at the same time. Data can be sent between the backend and ///| views using the PDReader/PDWriter APIs (prodbg::Writer prodbg::Reader in Rust) and this is the ///| only way for views and backends to talk with each other. There are several reasons for this ///| approach: ///! ///| 1. No "hacks" on trying to share memory. Plugins can be over a socket/webview/etc. ///! 2. Views and backends makes no assumetions on the inner workings of the others. ///! 3. Backends and views can post messages which anyone can decide to (optionally) act on. ///! pub struct Session { pub handle: SessionHandle, pub reader: Reader, current_writer: usize, writers: [Writer; 2], backend: Option<BackendHandle>, } ///! Connection options for Remote connections. Currently just one Ip adderss ///! pub struct ConnectionSettings<'a> { pub address: &'a str, } impl Session { pub fn new(handle: SessionHandle) -> Session { Session { handle: handle, writers: [ WriterWrapper::create_writer(), WriterWrapper::create_writer(), ], reader: ReaderWrapper::create_reader(), current_writer: 0, backend: None, } } pub fn get_current_writer(&mut self) -> &mut Writer { &mut self.writers[self.current_writer] } pub fn start_remote(_plugin_handler: &PluginHandler, _settings: &ConnectionSettings) {} pub fn start_local(_: &str, _: usize) {} pub fn set_backend(&mut self, backend: Option<BackendHandle>) { self.backend = backend } pub fn update(&mut self, backend_plugins: &mut BackendPlugins) { // swap the writers let c_writer = self.current_writer; let p_writer = (self.current_writer + 1) & 1; self.current_writer = p_writer; ReaderWrapper::init_from_writer(&mut self.reader, &self.writers[p_writer]); ReaderWrapper::reset_writer(&mut self.writers[c_writer]); if let Some(backend) = backend_plugins.get_backend(self.backend) { unsafe { let plugin_funcs = backend.plugin_type.plugin_funcs as *mut CBackendCallbacks; ((*plugin_funcs).update.unwrap())(backend.plugin_data, 0, self.reader.api as *mut c_void, self.writers[p_writer].api as *mut c_void); } } } } /// /// Sessions handler /// pub struct Sessions { instances: Vec<Session>, current: usize, session_counter: SessionHandle, } impl Sessions { pub fn new() -> Sessions { Sessions { instances: Vec::new(), current: 0, session_counter: SessionHandle(0), } } pub fn create_instance(&mut self) -> SessionHandle { let s = Session::new(self.session_counter); let handle = s.handle; self.instances.push(s); self.session_counter.0 += 1; handle } pub fn update(&mut self, backend_plugins: &mut BackendPlugins) { for session in self.instances.iter_mut() { session.update(backend_plugins); } } pub fn get_current(&mut self) -> &mut Session { let current = self.current; &mut self.instances[current] } pub fn get_session(&mut self, handle: SessionHandle) -> Option<&mut Session> { for i in 0..self.instances.len() { if self.instances[i].handle == handle {
} } None } } #[cfg(test)] mod tests { use core::reader_wrapper::{ReaderWrapper}; use super::*; #[test] fn create_session() { let _session = Session::new(); } #[test] fn write_simple_event() { let mut session = Session::new(); session.writers[0].event_begin(0x44); session.writers[0].event_end(); ReaderWrapper::init_from_writer(&mut session.reader, &session.writers[0]); assert_eq!(session.reader.get_event().unwrap(), 0x44); } }
return Some(&mut self.instances[i]);
random_line_split
session.rs
use prodbg_api::read_write::{Reader, Writer}; use prodbg_api::backend::{CBackendCallbacks}; use plugins::PluginHandler; use reader_wrapper::{ReaderWrapper, WriterWrapper}; use backend_plugin::{BackendHandle, BackendPlugins}; use libc::{c_void}; #[derive(PartialEq, Eq, Clone, Copy, Debug)] pub struct SessionHandle(pub u64); ///! Session is a major part of ProDBG. There can be several sessions active at the same time ///! and each session has exactly one backend. There are only communication internally in a session ///! sessions can't (at least now) not talk to eachother. ///! ///! A backend can have several views at the same time. Data can be sent between the backend and ///| views using the PDReader/PDWriter APIs (prodbg::Writer prodbg::Reader in Rust) and this is the ///| only way for views and backends to talk with each other. There are several reasons for this ///| approach: ///! ///| 1. No "hacks" on trying to share memory. Plugins can be over a socket/webview/etc. ///! 2. Views and backends makes no assumetions on the inner workings of the others. ///! 3. Backends and views can post messages which anyone can decide to (optionally) act on. ///! pub struct Session { pub handle: SessionHandle, pub reader: Reader, current_writer: usize, writers: [Writer; 2], backend: Option<BackendHandle>, } ///! Connection options for Remote connections. Currently just one Ip adderss ///! pub struct ConnectionSettings<'a> { pub address: &'a str, } impl Session { pub fn new(handle: SessionHandle) -> Session { Session { handle: handle, writers: [ WriterWrapper::create_writer(), WriterWrapper::create_writer(), ], reader: ReaderWrapper::create_reader(), current_writer: 0, backend: None, } } pub fn get_current_writer(&mut self) -> &mut Writer { &mut self.writers[self.current_writer] } pub fn start_remote(_plugin_handler: &PluginHandler, _settings: &ConnectionSettings) {} pub fn start_local(_: &str, _: usize) {} pub fn set_backend(&mut self, backend: Option<BackendHandle>) { self.backend = backend } pub fn update(&mut self, backend_plugins: &mut BackendPlugins) { // swap the writers let c_writer = self.current_writer; let p_writer = (self.current_writer + 1) & 1; self.current_writer = p_writer; ReaderWrapper::init_from_writer(&mut self.reader, &self.writers[p_writer]); ReaderWrapper::reset_writer(&mut self.writers[c_writer]); if let Some(backend) = backend_plugins.get_backend(self.backend)
} } /// /// Sessions handler /// pub struct Sessions { instances: Vec<Session>, current: usize, session_counter: SessionHandle, } impl Sessions { pub fn new() -> Sessions { Sessions { instances: Vec::new(), current: 0, session_counter: SessionHandle(0), } } pub fn create_instance(&mut self) -> SessionHandle { let s = Session::new(self.session_counter); let handle = s.handle; self.instances.push(s); self.session_counter.0 += 1; handle } pub fn update(&mut self, backend_plugins: &mut BackendPlugins) { for session in self.instances.iter_mut() { session.update(backend_plugins); } } pub fn get_current(&mut self) -> &mut Session { let current = self.current; &mut self.instances[current] } pub fn get_session(&mut self, handle: SessionHandle) -> Option<&mut Session> { for i in 0..self.instances.len() { if self.instances[i].handle == handle { return Some(&mut self.instances[i]); } } None } } #[cfg(test)] mod tests { use core::reader_wrapper::{ReaderWrapper}; use super::*; #[test] fn create_session() { let _session = Session::new(); } #[test] fn write_simple_event() { let mut session = Session::new(); session.writers[0].event_begin(0x44); session.writers[0].event_end(); ReaderWrapper::init_from_writer(&mut session.reader, &session.writers[0]); assert_eq!(session.reader.get_event().unwrap(), 0x44); } }
{ unsafe { let plugin_funcs = backend.plugin_type.plugin_funcs as *mut CBackendCallbacks; ((*plugin_funcs).update.unwrap())(backend.plugin_data, 0, self.reader.api as *mut c_void, self.writers[p_writer].api as *mut c_void); } }
conditional_block