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
mod.rs
pub mod event; use self::event::EventStopable; use std::collections::HashMap; pub trait ListenerCallable: PartialEq { fn call(&self, event_name: &str, event: &mut EventStopable); } pub struct EventListener { callback: fn(event_name: &str, event: &mut EventStopable), } impl EventListener { pub fn new (callback: fn(event_name: &str, event: &mut EventStopable)) -> EventListener { EventListener {callback: callback} } } impl ListenerCallable for EventListener { fn call (&self, event_name: &str, event: &mut EventStopable) { let callback = self.callback; callback(event_name, event); } } impl PartialEq for EventListener { fn eq(&self, other: &EventListener) -> bool { (self.callback as *const()) == (other.callback as *const()) } fn ne(&self, other: &EventListener) -> bool { !self.eq(other) } } pub trait Dispatchable<S> where S: EventStopable { fn dispatch (&self, event_name: &str, event: &mut S); } pub struct EventDispatcher<'a, L> where L: 'a + ListenerCallable { listeners: HashMap<&'a str, Vec<&'a L>>, } impl<'a, L: 'a + ListenerCallable> EventDispatcher<'a, L> { pub fn new() -> EventDispatcher<'a, L> { EventDispatcher{listeners: HashMap::new()} } pub fn add_listener(&mut self, event_name: &'a str, listener: &'a L) { if!self.listeners.contains_key(event_name) { self.listeners.insert(event_name, Vec::new()); } if let Some(mut listeners) = self.listeners.get_mut(event_name) { listeners.push(listener); } } pub fn remove_listener(&mut self, event_name: &'a str, listener: &'a mut L) { if self.listeners.contains_key(event_name) { if let Some(mut listeners) = self.listeners.get_mut(event_name) { match listeners.iter().position(|x| *x == listener) { Some(index) =>
, _ => {}, } } } } } impl<'a, S: 'a + EventStopable> Dispatchable<S> for EventDispatcher<'a, EventListener> { fn dispatch(&self, event_name: &str, event: &mut S) { if let Some(listeners) = self.listeners.get(event_name) { for listener in listeners { listener.call(event_name, event); if!event.is_propagation_stopped() { break; } } } } } #[cfg(test)] mod tests { use super::*; use super::event::*; fn print_event_info(event_name: &str, event: &mut EventStopable) { println!("callback from event: {}", event_name); event.stop_propagation(); } #[test] fn test_dispatcher() { let event_name = "test_a"; let mut event = Event::new(); let callback_one: fn(event_name: &str, event: &mut EventStopable) = print_event_info; let mut listener_one = EventListener::new(callback_one); let mut dispatcher = EventDispatcher::new(); dispatcher.dispatch(event_name, &mut event); assert_eq!(false, event.is_propagation_stopped()); dispatcher.dispatch(event_name, &mut event); assert_eq!(false, event.is_propagation_stopped()); dispatcher.add_listener(event_name, &mut listener_one); dispatcher.dispatch(event_name, &mut event); assert_eq!(true, event.is_propagation_stopped()); } }
{ listeners.remove(index); }
conditional_block
mod.rs
pub mod event; use self::event::EventStopable; use std::collections::HashMap; pub trait ListenerCallable: PartialEq { fn call(&self, event_name: &str, event: &mut EventStopable); } pub struct EventListener { callback: fn(event_name: &str, event: &mut EventStopable), } impl EventListener { pub fn new (callback: fn(event_name: &str, event: &mut EventStopable)) -> EventListener { EventListener {callback: callback} } } impl ListenerCallable for EventListener { fn call (&self, event_name: &str, event: &mut EventStopable) { let callback = self.callback; callback(event_name, event); } } impl PartialEq for EventListener { fn eq(&self, other: &EventListener) -> bool { (self.callback as *const()) == (other.callback as *const()) } fn ne(&self, other: &EventListener) -> bool { !self.eq(other) } } pub trait Dispatchable<S> where S: EventStopable { fn dispatch (&self, event_name: &str, event: &mut S); } pub struct EventDispatcher<'a, L> where L: 'a + ListenerCallable { listeners: HashMap<&'a str, Vec<&'a L>>, } impl<'a, L: 'a + ListenerCallable> EventDispatcher<'a, L> { pub fn new() -> EventDispatcher<'a, L> { EventDispatcher{listeners: HashMap::new()} } pub fn add_listener(&mut self, event_name: &'a str, listener: &'a L) {
if let Some(mut listeners) = self.listeners.get_mut(event_name) { listeners.push(listener); } } pub fn remove_listener(&mut self, event_name: &'a str, listener: &'a mut L) { if self.listeners.contains_key(event_name) { if let Some(mut listeners) = self.listeners.get_mut(event_name) { match listeners.iter().position(|x| *x == listener) { Some(index) => { listeners.remove(index); }, _ => {}, } } } } } impl<'a, S: 'a + EventStopable> Dispatchable<S> for EventDispatcher<'a, EventListener> { fn dispatch(&self, event_name: &str, event: &mut S) { if let Some(listeners) = self.listeners.get(event_name) { for listener in listeners { listener.call(event_name, event); if!event.is_propagation_stopped() { break; } } } } } #[cfg(test)] mod tests { use super::*; use super::event::*; fn print_event_info(event_name: &str, event: &mut EventStopable) { println!("callback from event: {}", event_name); event.stop_propagation(); } #[test] fn test_dispatcher() { let event_name = "test_a"; let mut event = Event::new(); let callback_one: fn(event_name: &str, event: &mut EventStopable) = print_event_info; let mut listener_one = EventListener::new(callback_one); let mut dispatcher = EventDispatcher::new(); dispatcher.dispatch(event_name, &mut event); assert_eq!(false, event.is_propagation_stopped()); dispatcher.dispatch(event_name, &mut event); assert_eq!(false, event.is_propagation_stopped()); dispatcher.add_listener(event_name, &mut listener_one); dispatcher.dispatch(event_name, &mut event); assert_eq!(true, event.is_propagation_stopped()); } }
if !self.listeners.contains_key(event_name) { self.listeners.insert(event_name, Vec::new()); }
random_line_split
mod.rs
pub mod event; use self::event::EventStopable; use std::collections::HashMap; pub trait ListenerCallable: PartialEq { fn call(&self, event_name: &str, event: &mut EventStopable); } pub struct EventListener { callback: fn(event_name: &str, event: &mut EventStopable), } impl EventListener { pub fn new (callback: fn(event_name: &str, event: &mut EventStopable)) -> EventListener { EventListener {callback: callback} } } impl ListenerCallable for EventListener { fn call (&self, event_name: &str, event: &mut EventStopable) { let callback = self.callback; callback(event_name, event); } } impl PartialEq for EventListener { fn eq(&self, other: &EventListener) -> bool { (self.callback as *const()) == (other.callback as *const()) } fn ne(&self, other: &EventListener) -> bool { !self.eq(other) } } pub trait Dispatchable<S> where S: EventStopable { fn dispatch (&self, event_name: &str, event: &mut S); } pub struct EventDispatcher<'a, L> where L: 'a + ListenerCallable { listeners: HashMap<&'a str, Vec<&'a L>>, } impl<'a, L: 'a + ListenerCallable> EventDispatcher<'a, L> { pub fn new() -> EventDispatcher<'a, L> { EventDispatcher{listeners: HashMap::new()} } pub fn add_listener(&mut self, event_name: &'a str, listener: &'a L) { if!self.listeners.contains_key(event_name) { self.listeners.insert(event_name, Vec::new()); } if let Some(mut listeners) = self.listeners.get_mut(event_name) { listeners.push(listener); } } pub fn remove_listener(&mut self, event_name: &'a str, listener: &'a mut L) { if self.listeners.contains_key(event_name) { if let Some(mut listeners) = self.listeners.get_mut(event_name) { match listeners.iter().position(|x| *x == listener) { Some(index) => { listeners.remove(index); }, _ => {}, } } } } } impl<'a, S: 'a + EventStopable> Dispatchable<S> for EventDispatcher<'a, EventListener> { fn dispatch(&self, event_name: &str, event: &mut S) { if let Some(listeners) = self.listeners.get(event_name) { for listener in listeners { listener.call(event_name, event); if!event.is_propagation_stopped() { break; } } } } } #[cfg(test)] mod tests { use super::*; use super::event::*; fn
(event_name: &str, event: &mut EventStopable) { println!("callback from event: {}", event_name); event.stop_propagation(); } #[test] fn test_dispatcher() { let event_name = "test_a"; let mut event = Event::new(); let callback_one: fn(event_name: &str, event: &mut EventStopable) = print_event_info; let mut listener_one = EventListener::new(callback_one); let mut dispatcher = EventDispatcher::new(); dispatcher.dispatch(event_name, &mut event); assert_eq!(false, event.is_propagation_stopped()); dispatcher.dispatch(event_name, &mut event); assert_eq!(false, event.is_propagation_stopped()); dispatcher.add_listener(event_name, &mut listener_one); dispatcher.dispatch(event_name, &mut event); assert_eq!(true, event.is_propagation_stopped()); } }
print_event_info
identifier_name
main.rs
extern crate winapi; extern crate user32; use user32::{EnumDisplaySettingsW, ChangeDisplaySettingsW}; use std::env::args as cmd_args; #[inline(always)] fn usage() { println!("Usage: resolution_tool [command] Commands: set [width] [height] Change display settings. show Display current settings of display. "); } #[inline] fn device_name(display_name: &[u16; winapi::winuser::CCHDEVICENAME]) -> String { let len: usize = display_name.iter().position(|&elem| elem == 0).unwrap_or(0); String::from_utf16_lossy(&display_name[..len]) } #[inline] fn enum_display_settings(dev_mode: &mut winapi::DEVMODEW) -> bool { let dev_mode_p: *mut winapi::DEVMODEW = dev_mode; unsafe { EnumDisplaySettingsW(std::ptr::null(), winapi::ENUM_CURRENT_SETTINGS, dev_mode_p)!= 0 } } ///Change display settings wrapper around ```ChangeDisplaySettingsW``` /// ///# Return vale: /// ///* ```true``` if succesful or restart is required. ///* ```false``` Otherwise. fn change_display_settings(dev_mode: &mut winapi::DEVMODEW) -> bool { let dev_mode_p: *mut winapi::DEVMODEW = dev_mode; unsafe { match ChangeDisplaySettingsW(dev_mode_p, winapi::CDS_UPDATEREGISTRY) { winapi::DISP_CHANGE_SUCCESSFUL => { println!(">>Succesfully set."); true }, winapi::DISP_CHANGE_RESTART => { println!(">>To finish set reboot is required."); true }, _ => { println!(">>Failed to set"); false }, } } } ///Set new display resolution. fn display_set() { if cmd_args().len() < 4 { println!(">>set command requires width and height arguments"); return usage(); } let mut dev_mode: winapi::DEVMODEW = unsafe { std::mem::zeroed() }; if enum_display_settings(&mut dev_mode) { let mut set_args = cmd_args().skip(2); let new_width: u32 = set_args.next().unwrap().parse().unwrap_or(0); let new_height: u32 = set_args.next().unwrap().parse().unwrap_or(0); if new_width == 0 || new_height == 0 { println!(">>Specified resolution settings are incorrect"); return; } let name = device_name(&dev_mode.dmDeviceName); println!("Current Display {} settings:\nWidth={}\nHeight={}\n", &name, &dev_mode.dmPelsWidth, &dev_mode.dmPelsHeight); //Print warnings in case if the settings are not changed //Or abort if both are the same let is_same_width = new_width == dev_mode.dmPelsWidth; let is_same_height = new_height == dev_mode.dmPelsHeight; if is_same_width && is_same_height { println!(">>Specified resolution settings are the same. Nothing to do here."); return; } if is_same_width { println!(">>The width({}) is the same as original", new_width); } if is_same_height { println!(">>The height({}) is the same as original", new_height); } dev_mode.dmPelsWidth = new_width; dev_mode.dmPelsHeight = new_height; if change_display_settings(&mut dev_mode) { println!("New Display {} settings:\nWidth={}\nHeight={}", &name, &dev_mode.dmPelsWidth, &dev_mode.dmPelsHeight); } } else { println!("Failed to retrieve display settings"); } } ///Shows current display resolution. fn display_show()
fn main() { if cmd_args().len() < 2 { return usage(); } match cmd_args().skip(1).next().unwrap().as_ref() { "set" => display_set(), "show" => display_show(), arg @ _ => { println!("Incorrect command {}", &arg); usage(); } } }
{ let mut dev_mode: winapi::DEVMODEW = unsafe { std::mem::zeroed() }; if enum_display_settings(&mut dev_mode) { println!("Display {}:\nWidth={}\nHeight={}", device_name(&dev_mode.dmDeviceName), &dev_mode.dmPelsWidth, &dev_mode.dmPelsHeight); } else { println!("Failed to retrieve display settings"); } }
identifier_body
main.rs
extern crate winapi; extern crate user32; use user32::{EnumDisplaySettingsW, ChangeDisplaySettingsW}; use std::env::args as cmd_args; #[inline(always)] fn usage() { println!("Usage: resolution_tool [command] Commands: set [width] [height] Change display settings. show Display current settings of display. "); } #[inline] fn device_name(display_name: &[u16; winapi::winuser::CCHDEVICENAME]) -> String { let len: usize = display_name.iter().position(|&elem| elem == 0).unwrap_or(0); String::from_utf16_lossy(&display_name[..len]) } #[inline] fn enum_display_settings(dev_mode: &mut winapi::DEVMODEW) -> bool { let dev_mode_p: *mut winapi::DEVMODEW = dev_mode; unsafe { EnumDisplaySettingsW(std::ptr::null(), winapi::ENUM_CURRENT_SETTINGS, dev_mode_p)!= 0 } } ///Change display settings wrapper around ```ChangeDisplaySettingsW``` /// ///# Return vale: /// ///* ```true``` if succesful or restart is required. ///* ```false``` Otherwise. fn change_display_settings(dev_mode: &mut winapi::DEVMODEW) -> bool { let dev_mode_p: *mut winapi::DEVMODEW = dev_mode; unsafe { match ChangeDisplaySettingsW(dev_mode_p, winapi::CDS_UPDATEREGISTRY) { winapi::DISP_CHANGE_SUCCESSFUL => { println!(">>Succesfully set."); true }, winapi::DISP_CHANGE_RESTART => { println!(">>To finish set reboot is required."); true }, _ => { println!(">>Failed to set"); false }, } } } ///Set new display resolution. fn display_set() { if cmd_args().len() < 4 { println!(">>set command requires width and height arguments"); return usage(); } let mut dev_mode: winapi::DEVMODEW = unsafe { std::mem::zeroed() }; if enum_display_settings(&mut dev_mode) { let mut set_args = cmd_args().skip(2); let new_width: u32 = set_args.next().unwrap().parse().unwrap_or(0); let new_height: u32 = set_args.next().unwrap().parse().unwrap_or(0); if new_width == 0 || new_height == 0 { println!(">>Specified resolution settings are incorrect"); return; } let name = device_name(&dev_mode.dmDeviceName); println!("Current Display {} settings:\nWidth={}\nHeight={}\n", &name, &dev_mode.dmPelsWidth, &dev_mode.dmPelsHeight); //Print warnings in case if the settings are not changed //Or abort if both are the same let is_same_width = new_width == dev_mode.dmPelsWidth; let is_same_height = new_height == dev_mode.dmPelsHeight; if is_same_width && is_same_height { println!(">>Specified resolution settings are the same. Nothing to do here."); return; } if is_same_width { println!(">>The width({}) is the same as original", new_width); } if is_same_height { println!(">>The height({}) is the same as original", new_height); } dev_mode.dmPelsWidth = new_width; dev_mode.dmPelsHeight = new_height; if change_display_settings(&mut dev_mode) { println!("New Display {} settings:\nWidth={}\nHeight={}", &name, &dev_mode.dmPelsWidth, &dev_mode.dmPelsHeight); } } else { println!("Failed to retrieve display settings"); } }
fn display_show() { let mut dev_mode: winapi::DEVMODEW = unsafe { std::mem::zeroed() }; if enum_display_settings(&mut dev_mode) { println!("Display {}:\nWidth={}\nHeight={}", device_name(&dev_mode.dmDeviceName), &dev_mode.dmPelsWidth, &dev_mode.dmPelsHeight); } else { println!("Failed to retrieve display settings"); } } fn main() { if cmd_args().len() < 2 { return usage(); } match cmd_args().skip(1).next().unwrap().as_ref() { "set" => display_set(), "show" => display_show(), arg @ _ => { println!("Incorrect command {}", &arg); usage(); } } }
///Shows current display resolution.
random_line_split
main.rs
extern crate winapi; extern crate user32; use user32::{EnumDisplaySettingsW, ChangeDisplaySettingsW}; use std::env::args as cmd_args; #[inline(always)] fn usage() { println!("Usage: resolution_tool [command] Commands: set [width] [height] Change display settings. show Display current settings of display. "); } #[inline] fn
(display_name: &[u16; winapi::winuser::CCHDEVICENAME]) -> String { let len: usize = display_name.iter().position(|&elem| elem == 0).unwrap_or(0); String::from_utf16_lossy(&display_name[..len]) } #[inline] fn enum_display_settings(dev_mode: &mut winapi::DEVMODEW) -> bool { let dev_mode_p: *mut winapi::DEVMODEW = dev_mode; unsafe { EnumDisplaySettingsW(std::ptr::null(), winapi::ENUM_CURRENT_SETTINGS, dev_mode_p)!= 0 } } ///Change display settings wrapper around ```ChangeDisplaySettingsW``` /// ///# Return vale: /// ///* ```true``` if succesful or restart is required. ///* ```false``` Otherwise. fn change_display_settings(dev_mode: &mut winapi::DEVMODEW) -> bool { let dev_mode_p: *mut winapi::DEVMODEW = dev_mode; unsafe { match ChangeDisplaySettingsW(dev_mode_p, winapi::CDS_UPDATEREGISTRY) { winapi::DISP_CHANGE_SUCCESSFUL => { println!(">>Succesfully set."); true }, winapi::DISP_CHANGE_RESTART => { println!(">>To finish set reboot is required."); true }, _ => { println!(">>Failed to set"); false }, } } } ///Set new display resolution. fn display_set() { if cmd_args().len() < 4 { println!(">>set command requires width and height arguments"); return usage(); } let mut dev_mode: winapi::DEVMODEW = unsafe { std::mem::zeroed() }; if enum_display_settings(&mut dev_mode) { let mut set_args = cmd_args().skip(2); let new_width: u32 = set_args.next().unwrap().parse().unwrap_or(0); let new_height: u32 = set_args.next().unwrap().parse().unwrap_or(0); if new_width == 0 || new_height == 0 { println!(">>Specified resolution settings are incorrect"); return; } let name = device_name(&dev_mode.dmDeviceName); println!("Current Display {} settings:\nWidth={}\nHeight={}\n", &name, &dev_mode.dmPelsWidth, &dev_mode.dmPelsHeight); //Print warnings in case if the settings are not changed //Or abort if both are the same let is_same_width = new_width == dev_mode.dmPelsWidth; let is_same_height = new_height == dev_mode.dmPelsHeight; if is_same_width && is_same_height { println!(">>Specified resolution settings are the same. Nothing to do here."); return; } if is_same_width { println!(">>The width({}) is the same as original", new_width); } if is_same_height { println!(">>The height({}) is the same as original", new_height); } dev_mode.dmPelsWidth = new_width; dev_mode.dmPelsHeight = new_height; if change_display_settings(&mut dev_mode) { println!("New Display {} settings:\nWidth={}\nHeight={}", &name, &dev_mode.dmPelsWidth, &dev_mode.dmPelsHeight); } } else { println!("Failed to retrieve display settings"); } } ///Shows current display resolution. fn display_show() { let mut dev_mode: winapi::DEVMODEW = unsafe { std::mem::zeroed() }; if enum_display_settings(&mut dev_mode) { println!("Display {}:\nWidth={}\nHeight={}", device_name(&dev_mode.dmDeviceName), &dev_mode.dmPelsWidth, &dev_mode.dmPelsHeight); } else { println!("Failed to retrieve display settings"); } } fn main() { if cmd_args().len() < 2 { return usage(); } match cmd_args().skip(1).next().unwrap().as_ref() { "set" => display_set(), "show" => display_show(), arg @ _ => { println!("Incorrect command {}", &arg); usage(); } } }
device_name
identifier_name
main.rs
extern crate winapi; extern crate user32; use user32::{EnumDisplaySettingsW, ChangeDisplaySettingsW}; use std::env::args as cmd_args; #[inline(always)] fn usage() { println!("Usage: resolution_tool [command] Commands: set [width] [height] Change display settings. show Display current settings of display. "); } #[inline] fn device_name(display_name: &[u16; winapi::winuser::CCHDEVICENAME]) -> String { let len: usize = display_name.iter().position(|&elem| elem == 0).unwrap_or(0); String::from_utf16_lossy(&display_name[..len]) } #[inline] fn enum_display_settings(dev_mode: &mut winapi::DEVMODEW) -> bool { let dev_mode_p: *mut winapi::DEVMODEW = dev_mode; unsafe { EnumDisplaySettingsW(std::ptr::null(), winapi::ENUM_CURRENT_SETTINGS, dev_mode_p)!= 0 } } ///Change display settings wrapper around ```ChangeDisplaySettingsW``` /// ///# Return vale: /// ///* ```true``` if succesful or restart is required. ///* ```false``` Otherwise. fn change_display_settings(dev_mode: &mut winapi::DEVMODEW) -> bool { let dev_mode_p: *mut winapi::DEVMODEW = dev_mode; unsafe { match ChangeDisplaySettingsW(dev_mode_p, winapi::CDS_UPDATEREGISTRY) { winapi::DISP_CHANGE_SUCCESSFUL => { println!(">>Succesfully set."); true }, winapi::DISP_CHANGE_RESTART => { println!(">>To finish set reboot is required."); true }, _ => { println!(">>Failed to set"); false }, } } } ///Set new display resolution. fn display_set() { if cmd_args().len() < 4 { println!(">>set command requires width and height arguments"); return usage(); } let mut dev_mode: winapi::DEVMODEW = unsafe { std::mem::zeroed() }; if enum_display_settings(&mut dev_mode) { let mut set_args = cmd_args().skip(2); let new_width: u32 = set_args.next().unwrap().parse().unwrap_or(0); let new_height: u32 = set_args.next().unwrap().parse().unwrap_or(0); if new_width == 0 || new_height == 0 { println!(">>Specified resolution settings are incorrect"); return; } let name = device_name(&dev_mode.dmDeviceName); println!("Current Display {} settings:\nWidth={}\nHeight={}\n", &name, &dev_mode.dmPelsWidth, &dev_mode.dmPelsHeight); //Print warnings in case if the settings are not changed //Or abort if both are the same let is_same_width = new_width == dev_mode.dmPelsWidth; let is_same_height = new_height == dev_mode.dmPelsHeight; if is_same_width && is_same_height { println!(">>Specified resolution settings are the same. Nothing to do here."); return; } if is_same_width { println!(">>The width({}) is the same as original", new_width); } if is_same_height { println!(">>The height({}) is the same as original", new_height); } dev_mode.dmPelsWidth = new_width; dev_mode.dmPelsHeight = new_height; if change_display_settings(&mut dev_mode) { println!("New Display {} settings:\nWidth={}\nHeight={}", &name, &dev_mode.dmPelsWidth, &dev_mode.dmPelsHeight); } } else { println!("Failed to retrieve display settings"); } } ///Shows current display resolution. fn display_show() { let mut dev_mode: winapi::DEVMODEW = unsafe { std::mem::zeroed() }; if enum_display_settings(&mut dev_mode) { println!("Display {}:\nWidth={}\nHeight={}", device_name(&dev_mode.dmDeviceName), &dev_mode.dmPelsWidth, &dev_mode.dmPelsHeight); } else { println!("Failed to retrieve display settings"); } } fn main() { if cmd_args().len() < 2 { return usage(); } match cmd_args().skip(1).next().unwrap().as_ref() { "set" => display_set(), "show" => display_show(), arg @ _ =>
} }
{ println!("Incorrect command {}", &arg); usage(); }
conditional_block
days.rs
extern crate aoc_2018; #[macro_use] extern crate bencher; use std::fs::File; use std::io::Read; use bencher::Bencher; use aoc_2018::get_impl; fn get_input(day: u32) -> Vec<u8> { let filename = format!("inputs/{:02}.txt", day); let mut buf = Vec::new(); let mut file = File::open(&filename).unwrap(); file.read_to_end(&mut buf).unwrap(); buf } fn test_part1(day: u32, bench: &mut Bencher) { let input = get_input(day); bench.iter(|| {
fn test_part2(day: u32, bench: &mut Bencher) { let input = get_input(day); bench.iter(|| { let mut instance = get_impl(day); instance.part2(&mut input.as_slice()) }) } macro_rules! day_bench { ( $name:ident, $day:expr ) => { pub mod $name { use super::*; pub fn part1(bench: &mut Bencher) { test_part1($day, bench); } pub fn part2(bench: &mut Bencher) { test_part2($day, bench); } } benchmark_group!($name, $name::part1, $name::part2); }; } day_bench!(day01, 1); day_bench!(day02, 2); day_bench!(day03, 3); day_bench!(day04, 4); day_bench!(day05, 5); day_bench!(day06, 6); day_bench!(day07, 7); day_bench!(day08, 8); day_bench!(day09, 9); day_bench!(day10, 10); day_bench!(day11, 11); day_bench!(day12, 12); day_bench!(day13, 13); day_bench!(day14, 14); day_bench!(day15, 15); day_bench!(day16, 16); day_bench!(day17, 17); day_bench!(day18, 18); day_bench!(day19, 19); day_bench!(day20, 20); day_bench!(day21, 21); day_bench!(day22, 22); day_bench!(day23, 23); day_bench!(day24, 24); day_bench!(day25, 25); benchmark_main!(day01, day02, day03, day04, day05, day06, day07, day08, day09, day10, day11, day12, day13, day14, day15, day16, day17, day18, day19, day20, day21, day22, day23, day24, day25);
let mut instance = get_impl(day); instance.part1(&mut input.as_slice()) }) }
random_line_split
days.rs
extern crate aoc_2018; #[macro_use] extern crate bencher; use std::fs::File; use std::io::Read; use bencher::Bencher; use aoc_2018::get_impl; fn get_input(day: u32) -> Vec<u8> { let filename = format!("inputs/{:02}.txt", day); let mut buf = Vec::new(); let mut file = File::open(&filename).unwrap(); file.read_to_end(&mut buf).unwrap(); buf } fn test_part1(day: u32, bench: &mut Bencher)
fn test_part2(day: u32, bench: &mut Bencher) { let input = get_input(day); bench.iter(|| { let mut instance = get_impl(day); instance.part2(&mut input.as_slice()) }) } macro_rules! day_bench { ( $name:ident, $day:expr ) => { pub mod $name { use super::*; pub fn part1(bench: &mut Bencher) { test_part1($day, bench); } pub fn part2(bench: &mut Bencher) { test_part2($day, bench); } } benchmark_group!($name, $name::part1, $name::part2); }; } day_bench!(day01, 1); day_bench!(day02, 2); day_bench!(day03, 3); day_bench!(day04, 4); day_bench!(day05, 5); day_bench!(day06, 6); day_bench!(day07, 7); day_bench!(day08, 8); day_bench!(day09, 9); day_bench!(day10, 10); day_bench!(day11, 11); day_bench!(day12, 12); day_bench!(day13, 13); day_bench!(day14, 14); day_bench!(day15, 15); day_bench!(day16, 16); day_bench!(day17, 17); day_bench!(day18, 18); day_bench!(day19, 19); day_bench!(day20, 20); day_bench!(day21, 21); day_bench!(day22, 22); day_bench!(day23, 23); day_bench!(day24, 24); day_bench!(day25, 25); benchmark_main!(day01, day02, day03, day04, day05, day06, day07, day08, day09, day10, day11, day12, day13, day14, day15, day16, day17, day18, day19, day20, day21, day22, day23, day24, day25);
{ let input = get_input(day); bench.iter(|| { let mut instance = get_impl(day); instance.part1(&mut input.as_slice()) }) }
identifier_body
days.rs
extern crate aoc_2018; #[macro_use] extern crate bencher; use std::fs::File; use std::io::Read; use bencher::Bencher; use aoc_2018::get_impl; fn
(day: u32) -> Vec<u8> { let filename = format!("inputs/{:02}.txt", day); let mut buf = Vec::new(); let mut file = File::open(&filename).unwrap(); file.read_to_end(&mut buf).unwrap(); buf } fn test_part1(day: u32, bench: &mut Bencher) { let input = get_input(day); bench.iter(|| { let mut instance = get_impl(day); instance.part1(&mut input.as_slice()) }) } fn test_part2(day: u32, bench: &mut Bencher) { let input = get_input(day); bench.iter(|| { let mut instance = get_impl(day); instance.part2(&mut input.as_slice()) }) } macro_rules! day_bench { ( $name:ident, $day:expr ) => { pub mod $name { use super::*; pub fn part1(bench: &mut Bencher) { test_part1($day, bench); } pub fn part2(bench: &mut Bencher) { test_part2($day, bench); } } benchmark_group!($name, $name::part1, $name::part2); }; } day_bench!(day01, 1); day_bench!(day02, 2); day_bench!(day03, 3); day_bench!(day04, 4); day_bench!(day05, 5); day_bench!(day06, 6); day_bench!(day07, 7); day_bench!(day08, 8); day_bench!(day09, 9); day_bench!(day10, 10); day_bench!(day11, 11); day_bench!(day12, 12); day_bench!(day13, 13); day_bench!(day14, 14); day_bench!(day15, 15); day_bench!(day16, 16); day_bench!(day17, 17); day_bench!(day18, 18); day_bench!(day19, 19); day_bench!(day20, 20); day_bench!(day21, 21); day_bench!(day22, 22); day_bench!(day23, 23); day_bench!(day24, 24); day_bench!(day25, 25); benchmark_main!(day01, day02, day03, day04, day05, day06, day07, day08, day09, day10, day11, day12, day13, day14, day15, day16, day17, day18, day19, day20, day21, day22, day23, day24, day25);
get_input
identifier_name
syntax_test_dyn.rs
// SYNTAX TEST "Packages/Rust Enhanced/RustEnhanced.sublime-syntax" // dyn trait fn f(x: dyn T, y: Box<dyn T +'static>, z: &dyn T, // ^^^ meta.function.parameters storage.type.trait // ^^^ meta.function.parameters meta.generic storage.type.trait // ^^^ meta.function.parameters storage.type.trait f: &dyn Fn(CrateNum) -> bool) -> dyn T {
let y: Box<dyn Display +'static> = Box::new(BYTE); // ^^^ meta.generic storage.type.trait let _: &dyn (Display) = &BYTE; // ^^^ storage.type.trait let _: &dyn (::std::fmt::Display) = &BYTE; // ^^^ storage.type.trait const DT: &'static dyn C = &V; // ^^^ storage.type.trait struct S { f: dyn T // ^^^ meta.struct storage.type.trait } type D4 = dyn (::module::Trait); // ^^^ storage.type.trait } // dyn is not a keyword in all situations (a "weak" keyword). type A0 = dyn; // ^^^ -storage.type.trait type A1 = dyn::dyn; // ^^^^^ meta.path -storage.type.trait // ^^^ -storage.type.trait type A2 = dyn<dyn, dyn>; // ^^^ meta.generic -storage.type.trait // ^^^ meta.generic -storage.type.trait // ^^^ meta.generic -storage.type.trait // This is incorrect. `identifier` should not match on the keyword `as`. // However, avoiding keywords is a little complicated and slow. type A3 = dyn<<dyn as dyn>::dyn>; // ^^^ meta.generic -storage.type.trait // ^^^ meta.generic storage.type.trait // ^^^ meta.generic -storage.type.trait // ^^^ meta.generic -storage.type.trait
// ^^^ meta.function.parameters storage.type.trait // ^^^ meta.function.return-type storage.type.trait let x: &(dyn 'static + Display) = &BYTE; // ^^^ meta.group storage.type.trait
random_line_split
syntax_test_dyn.rs
// SYNTAX TEST "Packages/Rust Enhanced/RustEnhanced.sublime-syntax" // dyn trait fn
(x: dyn T, y: Box<dyn T +'static>, z: &dyn T, // ^^^ meta.function.parameters storage.type.trait // ^^^ meta.function.parameters meta.generic storage.type.trait // ^^^ meta.function.parameters storage.type.trait f: &dyn Fn(CrateNum) -> bool) -> dyn T { // ^^^ meta.function.parameters storage.type.trait // ^^^ meta.function.return-type storage.type.trait let x: &(dyn'static + Display) = &BYTE; // ^^^ meta.group storage.type.trait let y: Box<dyn Display +'static> = Box::new(BYTE); // ^^^ meta.generic storage.type.trait let _: &dyn (Display) = &BYTE; // ^^^ storage.type.trait let _: &dyn (::std::fmt::Display) = &BYTE; // ^^^ storage.type.trait const DT: &'static dyn C = &V; // ^^^ storage.type.trait struct S { f: dyn T // ^^^ meta.struct storage.type.trait } type D4 = dyn (::module::Trait); // ^^^ storage.type.trait } // dyn is not a keyword in all situations (a "weak" keyword). type A0 = dyn; // ^^^ -storage.type.trait type A1 = dyn::dyn; // ^^^^^ meta.path -storage.type.trait // ^^^ -storage.type.trait type A2 = dyn<dyn, dyn>; // ^^^ meta.generic -storage.type.trait // ^^^ meta.generic -storage.type.trait // ^^^ meta.generic -storage.type.trait // This is incorrect. `identifier` should not match on the keyword `as`. // However, avoiding keywords is a little complicated and slow. type A3 = dyn<<dyn as dyn>::dyn>; // ^^^ meta.generic -storage.type.trait // ^^^ meta.generic storage.type.trait // ^^^ meta.generic -storage.type.trait // ^^^ meta.generic -storage.type.trait
f
identifier_name
syntax_test_dyn.rs
// SYNTAX TEST "Packages/Rust Enhanced/RustEnhanced.sublime-syntax" // dyn trait fn f(x: dyn T, y: Box<dyn T +'static>, z: &dyn T, // ^^^ meta.function.parameters storage.type.trait // ^^^ meta.function.parameters meta.generic storage.type.trait // ^^^ meta.function.parameters storage.type.trait f: &dyn Fn(CrateNum) -> bool) -> dyn T
// dyn is not a keyword in all situations (a "weak" keyword). type A0 = dyn; // ^^^ -storage.type.trait type A1 = dyn::dyn; // ^^^^^ meta.path -storage.type.trait // ^^^ -storage.type.trait type A2 = dyn<dyn, dyn>; // ^^^ meta.generic -storage.type.trait // ^^^ meta.generic -storage.type.trait // ^^^ meta.generic -storage.type.trait // This is incorrect. `identifier` should not match on the keyword `as`. // However, avoiding keywords is a little complicated and slow. type A3 = dyn<<dyn as dyn>::dyn>; // ^^^ meta.generic -storage.type.trait // ^^^ meta.generic storage.type.trait // ^^^ meta.generic -storage.type.trait // ^^^ meta.generic -storage.type.trait
{ // ^^^ meta.function.parameters storage.type.trait // ^^^ meta.function.return-type storage.type.trait let x: &(dyn 'static + Display) = &BYTE; // ^^^ meta.group storage.type.trait let y: Box<dyn Display + 'static> = Box::new(BYTE); // ^^^ meta.generic storage.type.trait let _: &dyn (Display) = &BYTE; // ^^^ storage.type.trait let _: &dyn (::std::fmt::Display) = &BYTE; // ^^^ storage.type.trait const DT: &'static dyn C = &V; // ^^^ storage.type.trait struct S { f: dyn T // ^^^ meta.struct storage.type.trait } type D4 = dyn (::module::Trait); // ^^^ storage.type.trait }
identifier_body
transform.rs
//! Utilities for graph transformations. use std::cell::{Ref, RefCell, RefMut}; use std::default::Default; use super::interface::{ConcreteGraphMut, Id}; use util::splitvec::SplitVec; // ---------------------------------------------------------------- /// Target-node specifier for use with `Builder::append_edge`. #[derive(Copy, Clone, Debug, PartialEq)] pub enum Target<I> where I: Id { /// Use the specified target node, and ensure that it is in the outputs /// list Output(I), /// Use all current output nodes, creating one if none exist AllOutputs, /// Use the first available output node if one exists, or create one and /// add it to the outputs list AutoOutput, /// Unconditionally create a new node, and add it to the outputs list NewOutput, /// Use the specified target node, but do not add it to the outputs list Intermediate(I), /// Create a new target node, but do not add it to the outputs list AutoIntermediate, /// Use each input node as the output. InputOutput } impl<I> Target<I> where I: Id { /// Check if the target specifies a node that should be added to the /// Builder's outputs list. pub fn is_output(&self) -> bool { match self { &Target::Output(_) | &Target::AutoOutput | &Target::NewOutput | &Target::InputOutput | &Target::AllOutputs => true, &Target::Intermediate(_) | &Target::AutoIntermediate => false } } /// Resolve the target into a node id, potentially creating a new node /// /// `auto_output_candidate` is the calling Builder's first output (or None if /// no outputs currently exist). /// /// `f` is called when a new node should be created, and must return that /// node's ID. pub fn node_id<'a, F>(&self, auto_output_candidate: Option<I>, mut f: F) -> I where F: FnMut() -> I { match self { &Target::AutoOutput => auto_output_candidate.unwrap_or_else(|| f()), &Target::Output(id) | &Target::Intermediate(id) => id,
=> f(), &Target::AllOutputs => panic!("cannot handle `Target::AllOutputs` variant from `node_id`"), &Target::InputOutput => panic!("cannot handle `Target::InputOutput` variant from `node_id`") } } /// Fetch the ID contained in an `Output` or `Intermediate` variant. pub fn unwrap_id(&self) -> I { match self { &Target::Output(id) | &Target::Intermediate(id) => id, _ => panic!("Attempted to unwrap Target instance without a specific id") } } } // ---------------------------------------------------------------- /// Trait describing bounds on graph-construction functions and closures passed /// to `Builder`'s methods. pub trait BuildFn<G, I>: FnMut(&mut Builder<G>, Target<G::NodeId>, I) -> G::NodeId where G: ConcreteGraphMut {} impl<G, I, F> BuildFn<G, I> for F where F: FnMut(&mut Builder<G>, Target<G::NodeId>, I) -> G::NodeId, G: ConcreteGraphMut {} /// Trait describing bounds on graph-construction functions and closures passed /// to `Builder` that are only called once. pub trait BuildOnceFn<G, I>: FnOnce(&mut Builder<G>, Target<G::NodeId>, I) -> G::NodeId where G: ConcreteGraphMut {} impl<G, I, F> BuildOnceFn<G, I> for F where F: FnOnce(&mut Builder<G>, Target<G::NodeId>, I) -> G::NodeId, G: ConcreteGraphMut {} /// Closure type used when a new node must be created on a graph pub trait NodeFn<G, E>: FnMut(&mut G, &E) -> G::NodeId where G: ConcreteGraphMut {} impl<G, E, F> NodeFn<G, E> for F where F: FnMut(&mut G, &E) -> G::NodeId, G: ConcreteGraphMut {} // ---------------------------------------------------------------- /// Handles node and edge addition for each stage of a graph /// under construction. #[derive(Clone, Debug)] pub struct Builder<G> where G: ConcreteGraphMut { graph: RefCell<G>, /// "out" nodes from the previous stage pub inputs: SplitVec<G::NodeId>, /// "out" nodes for the stage under construction pub outputs: SplitVec<G::NodeId>, } impl<G> Builder<G> where G: ConcreteGraphMut { /// Create an empty `Builder` instance for the given entry node pub fn new() -> Self where G: Default { Builder{graph: RefCell::new(Default::default()), inputs: SplitVec::new(), outputs: SplitVec::new()} } /// Create a new Builder with the specified graph and (optionally) /// entry node. pub fn with_graph(g: G, entry: Option<G::NodeId>) -> Self { let inputs = if let Some(entry) = entry { vec![entry].into() } else { SplitVec::new() }; Builder{graph: RefCell::new(g), inputs: inputs, outputs: SplitVec::new()} } /// Consume the Builder object, returning the built graph. pub fn finish(self) -> G { self.graph.into_inner() } /// Get a reference to the builder's graph pub fn graph(&self) -> Ref<G> { self.graph.borrow() } /// Get a reference to the builder's graph pub fn graph_mut(&mut self) -> &mut G { self.graph.get_mut() } /// Fetch a slice over the IDs of nodes that act as inputs for this stage pub fn stage_inputs(&self) -> &[G::NodeId] { &self.inputs[..] } /// Fetch a slice over the IDs of nodes that act as outputs for this stage pub fn stage_outputs(&self) -> &[G::NodeId] { &self.outputs[..] } /// Run the given function or closure, providing mutable access to the /// underlying graph. pub fn with_graph_mut<F, R>(&mut self, f: F) -> R where F: FnOnce(&Self, RefMut<G>) -> R { f(self, self.graph.borrow_mut()) } /// Append an edge between all inputs for the stage and some target node. /// /// pub fn append_edge<E, F>(&mut self, tgt: Target<G::NodeId>, e: E, mut f: F) -> G::NodeId where F: NodeFn<G, E>, (G::NodeId, G::NodeId, E): Into<G::Edge>, E: Clone { match tgt { Target::InputOutput => { for prev in self.inputs.iter() { self.graph.get_mut().add_edge((*prev, *prev, e.clone())); } *self.inputs.first().unwrap() }, Target::AllOutputs => { // If the stage has no outputs, create one. if self.outputs.is_empty() { self.outputs.push(f(self.graph.get_mut(), &e)); } for next in self.outputs.iter() { for prev in self.inputs.iter() { self.graph.get_mut().add_edge((*prev, *next, e.clone())); } } *self.outputs.first().unwrap() }, _ => { let next = tgt.node_id(self.outputs.first().cloned(), || f(self.graph.get_mut(), &e)); if tgt.is_output() { self.mark_output(next); } // For ALL inputs from the previous stage, add an edge from that input // to the specified output. for prev in self.inputs.iter() { self.graph.get_mut().add_edge((*prev, next, e.clone())); } next } } } /// Add an edge from a *specific* source node to some target node pub fn append_edge_from<E, F>(&mut self, source: G::NodeId, target: Target<G::NodeId>, e: E, mut f: F) -> G::NodeId where F: NodeFn<G, E>, (G::NodeId, G::NodeId, E): Into<G::Edge>, E: Clone { let next = target.node_id(self.outputs.first().cloned(), || f(self.graph.get_mut(), &e)); if target.is_output() { self.mark_output(next); } self.graph.get_mut().add_edge((source, next, e)); next } /// Ensure that a particular node id is included in the current /// stage's outputs. pub fn mark_output(&mut self, id: G::NodeId) -> G::NodeId { if! self.outputs.contains(&id) { self.outputs.push(id); } id } /// Mark all stage inputs as outputs. pub fn mark_inputs_as_outputs(&mut self) { for id in self.inputs.iter_mut() { self.outputs.push(*id) } } /// Build _within_ the current stage, preserving the list of stage inputs. pub fn recurse<F, I>(&mut self, next: Target<G::NodeId>, input: I, build: F) -> G::NodeId where F: BuildOnceFn<G, I> { self.inputs.dedup(); self.inputs.push_and_copy_state(); let o = build(self, next, input); self.inputs.pop_state(); o } /// Chain together the subgraphs built from the elements produced by /// an iterator. /// /// If the given target specifies a node, that node will be used as the /// terminal end of the subgraph chain in addition to being marked as /// a stage output. /// /// This method will **panic** if called with an empty iterator. pub fn chain<F, I, R>(&mut self, target: Target<G::NodeId>, input: R, mut build: F) -> G::NodeId where R: IntoIterator<Item=I>, F: BuildFn<G, I>, { let mut o = None; let mut iter = input.into_iter().peekable(); let build = &mut build; self.inputs.push_and_copy_state(); self.outputs.push_state(); while let Some(elt) = iter.next() { if iter.peek().is_some() { // If there's another element after this one, create a pristine // node to connect it to the one we're about to build o = Some(build(self, Target::NewOutput, elt)); self.advance(); } else { // Last element; connect to the specified target. match target { Target::InputOutput => { // When `InputOutput` was specified, we need to // copy the *chain* inputs -- i.e., the inputs to // the _first_ stage in the chain -- to the current // outputs list. self.outputs.truncate(0); self.outputs.extend_from_slice(self.inputs.prev_state().unwrap()); o = Some(build(self, Target::AllOutputs, elt)); self.outputs.pop_state(); self.outputs.extend_from_slice(self.inputs.prev_state().unwrap()); }, _ => { self.outputs.pop_state(); o = Some(build(self, target, elt)); } } } } self.inputs.pop_state(); o.unwrap() } /// Build subgraphs from the elements of an iterator between the current /// stage's inputs and some specified output. pub fn branch<F, I, R>(&mut self, target: Target<G::NodeId>, input: R, mut build: F) -> G::NodeId where R: IntoIterator<Item=I>, F: BuildFn<G, I> + BuildOnceFn<G, I>, { let mut target = target; for elt in input { target = Target::Output(self.recurse(target, elt.into(), &mut build)); } target.unwrap_id() } /// Finalize the current stage. /// /// This overwrites the current list of input nodes with the list of output /// nodes, and truncates the output-node list. pub fn advance(&mut self) { if self.outputs.len() > 0 { self.inputs.truncate(0); self.inputs.extend_from_slice(&self.outputs[..]); self.outputs.truncate(0); } } } // ---------------------------------------------------------------- /// Trait encapsulating node-creation methods for the Build trait family. pub trait BuildNodes<G, I> where G: ConcreteGraphMut { /// Create the entry node for the given input, returning its ID. fn entry_node(&mut self, g: &mut G, input: &I) -> G::NodeId; /// Create the target node for the given edge data, returning the ID of the /// new node. fn target_node<E>(&mut self, g: &mut G, e: &E) -> G::NodeId where (G::NodeId, G::NodeId, E): Into<G::Edge>; } /// Composable graph-building interface for arbitrary element types. pub trait Build<G, I> where G: ConcreteGraphMut { /// Construct the graph stage for the given input and target node. /// /// Returns the actual ID of the target node used, if any fn build(&mut self, builder: &mut Builder<G>, next: Target<G::NodeId>, input: I) -> G::NodeId; } /// Graph-building interface. pub trait BuildFull<G, I>: Build<G, I> + BuildNodes<G, I> where G: ConcreteGraphMut { /// Perform any finalization on the builder or the built graph. #[inline] fn finish(&mut self, &mut Builder<G>) { } // /// Create a subgraph describing the given input, and return its // /// entry and exit node IDs. // /// // /// @return Tuple containing the stand-alone graph's entry- and // /// exit-node IDs. // fn build_subgraph<'g>(ep: &mut Builder<'g, G>, // input: Self::Input) -> (G::NodeId, // G::NodeId) { // Self::build_recursive(ep, input); // } /// Convert the given input into a graph. /// /// Returns the resulting graph and the entry node. fn build_full(mut self, input: I) -> (G, G::NodeId) where Self: Sized, G: Default { let mut g = G::new(); let entry = self.entry_node(&mut g, &input); let mut builder = Builder::with_graph(g, Some(entry)); self.build(&mut builder, Target::AutoOutput, input); self.finish(&mut builder); (builder.finish(), entry) } }
&Target::NewOutput | &Target::AutoIntermediate
random_line_split
transform.rs
//! Utilities for graph transformations. use std::cell::{Ref, RefCell, RefMut}; use std::default::Default; use super::interface::{ConcreteGraphMut, Id}; use util::splitvec::SplitVec; // ---------------------------------------------------------------- /// Target-node specifier for use with `Builder::append_edge`. #[derive(Copy, Clone, Debug, PartialEq)] pub enum Target<I> where I: Id { /// Use the specified target node, and ensure that it is in the outputs /// list Output(I), /// Use all current output nodes, creating one if none exist AllOutputs, /// Use the first available output node if one exists, or create one and /// add it to the outputs list AutoOutput, /// Unconditionally create a new node, and add it to the outputs list NewOutput, /// Use the specified target node, but do not add it to the outputs list Intermediate(I), /// Create a new target node, but do not add it to the outputs list AutoIntermediate, /// Use each input node as the output. InputOutput } impl<I> Target<I> where I: Id { /// Check if the target specifies a node that should be added to the /// Builder's outputs list. pub fn is_output(&self) -> bool { match self { &Target::Output(_) | &Target::AutoOutput | &Target::NewOutput | &Target::InputOutput | &Target::AllOutputs => true, &Target::Intermediate(_) | &Target::AutoIntermediate => false } } /// Resolve the target into a node id, potentially creating a new node /// /// `auto_output_candidate` is the calling Builder's first output (or None if /// no outputs currently exist). /// /// `f` is called when a new node should be created, and must return that /// node's ID. pub fn node_id<'a, F>(&self, auto_output_candidate: Option<I>, mut f: F) -> I where F: FnMut() -> I { match self { &Target::AutoOutput => auto_output_candidate.unwrap_or_else(|| f()), &Target::Output(id) | &Target::Intermediate(id) => id, &Target::NewOutput | &Target::AutoIntermediate => f(), &Target::AllOutputs => panic!("cannot handle `Target::AllOutputs` variant from `node_id`"), &Target::InputOutput => panic!("cannot handle `Target::InputOutput` variant from `node_id`") } } /// Fetch the ID contained in an `Output` or `Intermediate` variant. pub fn unwrap_id(&self) -> I { match self { &Target::Output(id) | &Target::Intermediate(id) => id, _ => panic!("Attempted to unwrap Target instance without a specific id") } } } // ---------------------------------------------------------------- /// Trait describing bounds on graph-construction functions and closures passed /// to `Builder`'s methods. pub trait BuildFn<G, I>: FnMut(&mut Builder<G>, Target<G::NodeId>, I) -> G::NodeId where G: ConcreteGraphMut {} impl<G, I, F> BuildFn<G, I> for F where F: FnMut(&mut Builder<G>, Target<G::NodeId>, I) -> G::NodeId, G: ConcreteGraphMut {} /// Trait describing bounds on graph-construction functions and closures passed /// to `Builder` that are only called once. pub trait BuildOnceFn<G, I>: FnOnce(&mut Builder<G>, Target<G::NodeId>, I) -> G::NodeId where G: ConcreteGraphMut {} impl<G, I, F> BuildOnceFn<G, I> for F where F: FnOnce(&mut Builder<G>, Target<G::NodeId>, I) -> G::NodeId, G: ConcreteGraphMut {} /// Closure type used when a new node must be created on a graph pub trait NodeFn<G, E>: FnMut(&mut G, &E) -> G::NodeId where G: ConcreteGraphMut {} impl<G, E, F> NodeFn<G, E> for F where F: FnMut(&mut G, &E) -> G::NodeId, G: ConcreteGraphMut {} // ---------------------------------------------------------------- /// Handles node and edge addition for each stage of a graph /// under construction. #[derive(Clone, Debug)] pub struct Builder<G> where G: ConcreteGraphMut { graph: RefCell<G>, /// "out" nodes from the previous stage pub inputs: SplitVec<G::NodeId>, /// "out" nodes for the stage under construction pub outputs: SplitVec<G::NodeId>, } impl<G> Builder<G> where G: ConcreteGraphMut { /// Create an empty `Builder` instance for the given entry node pub fn new() -> Self where G: Default { Builder{graph: RefCell::new(Default::default()), inputs: SplitVec::new(), outputs: SplitVec::new()} } /// Create a new Builder with the specified graph and (optionally) /// entry node. pub fn with_graph(g: G, entry: Option<G::NodeId>) -> Self { let inputs = if let Some(entry) = entry { vec![entry].into() } else { SplitVec::new() }; Builder{graph: RefCell::new(g), inputs: inputs, outputs: SplitVec::new()} } /// Consume the Builder object, returning the built graph. pub fn finish(self) -> G { self.graph.into_inner() } /// Get a reference to the builder's graph pub fn graph(&self) -> Ref<G> { self.graph.borrow() } /// Get a reference to the builder's graph pub fn graph_mut(&mut self) -> &mut G { self.graph.get_mut() } /// Fetch a slice over the IDs of nodes that act as inputs for this stage pub fn stage_inputs(&self) -> &[G::NodeId] { &self.inputs[..] } /// Fetch a slice over the IDs of nodes that act as outputs for this stage pub fn stage_outputs(&self) -> &[G::NodeId] { &self.outputs[..] } /// Run the given function or closure, providing mutable access to the /// underlying graph. pub fn with_graph_mut<F, R>(&mut self, f: F) -> R where F: FnOnce(&Self, RefMut<G>) -> R { f(self, self.graph.borrow_mut()) } /// Append an edge between all inputs for the stage and some target node. /// /// pub fn
<E, F>(&mut self, tgt: Target<G::NodeId>, e: E, mut f: F) -> G::NodeId where F: NodeFn<G, E>, (G::NodeId, G::NodeId, E): Into<G::Edge>, E: Clone { match tgt { Target::InputOutput => { for prev in self.inputs.iter() { self.graph.get_mut().add_edge((*prev, *prev, e.clone())); } *self.inputs.first().unwrap() }, Target::AllOutputs => { // If the stage has no outputs, create one. if self.outputs.is_empty() { self.outputs.push(f(self.graph.get_mut(), &e)); } for next in self.outputs.iter() { for prev in self.inputs.iter() { self.graph.get_mut().add_edge((*prev, *next, e.clone())); } } *self.outputs.first().unwrap() }, _ => { let next = tgt.node_id(self.outputs.first().cloned(), || f(self.graph.get_mut(), &e)); if tgt.is_output() { self.mark_output(next); } // For ALL inputs from the previous stage, add an edge from that input // to the specified output. for prev in self.inputs.iter() { self.graph.get_mut().add_edge((*prev, next, e.clone())); } next } } } /// Add an edge from a *specific* source node to some target node pub fn append_edge_from<E, F>(&mut self, source: G::NodeId, target: Target<G::NodeId>, e: E, mut f: F) -> G::NodeId where F: NodeFn<G, E>, (G::NodeId, G::NodeId, E): Into<G::Edge>, E: Clone { let next = target.node_id(self.outputs.first().cloned(), || f(self.graph.get_mut(), &e)); if target.is_output() { self.mark_output(next); } self.graph.get_mut().add_edge((source, next, e)); next } /// Ensure that a particular node id is included in the current /// stage's outputs. pub fn mark_output(&mut self, id: G::NodeId) -> G::NodeId { if! self.outputs.contains(&id) { self.outputs.push(id); } id } /// Mark all stage inputs as outputs. pub fn mark_inputs_as_outputs(&mut self) { for id in self.inputs.iter_mut() { self.outputs.push(*id) } } /// Build _within_ the current stage, preserving the list of stage inputs. pub fn recurse<F, I>(&mut self, next: Target<G::NodeId>, input: I, build: F) -> G::NodeId where F: BuildOnceFn<G, I> { self.inputs.dedup(); self.inputs.push_and_copy_state(); let o = build(self, next, input); self.inputs.pop_state(); o } /// Chain together the subgraphs built from the elements produced by /// an iterator. /// /// If the given target specifies a node, that node will be used as the /// terminal end of the subgraph chain in addition to being marked as /// a stage output. /// /// This method will **panic** if called with an empty iterator. pub fn chain<F, I, R>(&mut self, target: Target<G::NodeId>, input: R, mut build: F) -> G::NodeId where R: IntoIterator<Item=I>, F: BuildFn<G, I>, { let mut o = None; let mut iter = input.into_iter().peekable(); let build = &mut build; self.inputs.push_and_copy_state(); self.outputs.push_state(); while let Some(elt) = iter.next() { if iter.peek().is_some() { // If there's another element after this one, create a pristine // node to connect it to the one we're about to build o = Some(build(self, Target::NewOutput, elt)); self.advance(); } else { // Last element; connect to the specified target. match target { Target::InputOutput => { // When `InputOutput` was specified, we need to // copy the *chain* inputs -- i.e., the inputs to // the _first_ stage in the chain -- to the current // outputs list. self.outputs.truncate(0); self.outputs.extend_from_slice(self.inputs.prev_state().unwrap()); o = Some(build(self, Target::AllOutputs, elt)); self.outputs.pop_state(); self.outputs.extend_from_slice(self.inputs.prev_state().unwrap()); }, _ => { self.outputs.pop_state(); o = Some(build(self, target, elt)); } } } } self.inputs.pop_state(); o.unwrap() } /// Build subgraphs from the elements of an iterator between the current /// stage's inputs and some specified output. pub fn branch<F, I, R>(&mut self, target: Target<G::NodeId>, input: R, mut build: F) -> G::NodeId where R: IntoIterator<Item=I>, F: BuildFn<G, I> + BuildOnceFn<G, I>, { let mut target = target; for elt in input { target = Target::Output(self.recurse(target, elt.into(), &mut build)); } target.unwrap_id() } /// Finalize the current stage. /// /// This overwrites the current list of input nodes with the list of output /// nodes, and truncates the output-node list. pub fn advance(&mut self) { if self.outputs.len() > 0 { self.inputs.truncate(0); self.inputs.extend_from_slice(&self.outputs[..]); self.outputs.truncate(0); } } } // ---------------------------------------------------------------- /// Trait encapsulating node-creation methods for the Build trait family. pub trait BuildNodes<G, I> where G: ConcreteGraphMut { /// Create the entry node for the given input, returning its ID. fn entry_node(&mut self, g: &mut G, input: &I) -> G::NodeId; /// Create the target node for the given edge data, returning the ID of the /// new node. fn target_node<E>(&mut self, g: &mut G, e: &E) -> G::NodeId where (G::NodeId, G::NodeId, E): Into<G::Edge>; } /// Composable graph-building interface for arbitrary element types. pub trait Build<G, I> where G: ConcreteGraphMut { /// Construct the graph stage for the given input and target node. /// /// Returns the actual ID of the target node used, if any fn build(&mut self, builder: &mut Builder<G>, next: Target<G::NodeId>, input: I) -> G::NodeId; } /// Graph-building interface. pub trait BuildFull<G, I>: Build<G, I> + BuildNodes<G, I> where G: ConcreteGraphMut { /// Perform any finalization on the builder or the built graph. #[inline] fn finish(&mut self, &mut Builder<G>) { } // /// Create a subgraph describing the given input, and return its // /// entry and exit node IDs. // /// // /// @return Tuple containing the stand-alone graph's entry- and // /// exit-node IDs. // fn build_subgraph<'g>(ep: &mut Builder<'g, G>, // input: Self::Input) -> (G::NodeId, // G::NodeId) { // Self::build_recursive(ep, input); // } /// Convert the given input into a graph. /// /// Returns the resulting graph and the entry node. fn build_full(mut self, input: I) -> (G, G::NodeId) where Self: Sized, G: Default { let mut g = G::new(); let entry = self.entry_node(&mut g, &input); let mut builder = Builder::with_graph(g, Some(entry)); self.build(&mut builder, Target::AutoOutput, input); self.finish(&mut builder); (builder.finish(), entry) } }
append_edge
identifier_name
regions-outlives-nominal-type-region-rev.rs
// Copyright 2014 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. // Test that a nominal type (like `Foo<'a>`) outlives `'b` if its // arguments (like `'a`) outlive `'b`. // // Rule OutlivesNominalType from RFC 1214. #![allow(dead_code)] mod rev_variant_struct_region { struct
<'a> { x: fn(&'a i32), } trait Trait<'a, 'b> { type Out; } impl<'a, 'b> Trait<'a, 'b> for usize { type Out = &'a Foo<'b>; //~ ERROR reference has a longer lifetime } } fn main() { }
Foo
identifier_name
regions-outlives-nominal-type-region-rev.rs
// Copyright 2014 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. // Test that a nominal type (like `Foo<'a>`) outlives `'b` if its // arguments (like `'a`) outlive `'b`. // // Rule OutlivesNominalType from RFC 1214.
mod rev_variant_struct_region { struct Foo<'a> { x: fn(&'a i32), } trait Trait<'a, 'b> { type Out; } impl<'a, 'b> Trait<'a, 'b> for usize { type Out = &'a Foo<'b>; //~ ERROR reference has a longer lifetime } } fn main() { }
#![allow(dead_code)]
random_line_split
codec.rs
/* Copyright (C) 2013 Tox project All Rights Reserved. Copyright © 2017 Zetok Zalbavar <[email protected]> Copyright © 2017 Roman Proskuryakov <[email protected]> This file is part of Tox. Tox is libre 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. Tox 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 Tox. If not, see <http://www.gnu.org/licenses/>. */ /*! Codec implementation for encoding/decoding TCP Packets in terms of tokio-io */ use toxcore::tcp::packet::*; use toxcore::tcp::secure::*; use toxcore::tcp::binary_io::*; use nom::Offset; use std::io::{Error, ErrorKind}; use bytes::BytesMut; use tokio_io::codec::{Decoder, Encoder}; /// implements tokio-io's Decoder and Encoder to deal with Packet pub struct Codec {
channel: Channel } impl Codec { /// create a new Codec with the given Channel pub fn new(channel: Channel) -> Codec { Codec { channel: channel } } } impl Decoder for Codec { type Item = Packet; type Error = Error; fn decode(&mut self, buf: &mut BytesMut) -> Result<Option<Self::Item>, Self::Error> { // deserialize EncryptedPacket let (consumed, encrypted_packet) = match EncryptedPacket::from_bytes(buf) { IResult::Incomplete(_) => { return Ok(None) }, IResult::Error(e) => { return Err(Error::new(ErrorKind::Other, format!("EncryptedPacket deserialize error: {:?}", e))) }, IResult::Done(i, encrypted_packet) => { (buf.offset(i), encrypted_packet) } }; // decrypt payload let decrypted_data = self.channel.decrypt(&encrypted_packet.payload) .map_err(|_| Error::new(ErrorKind::Other, "EncryptedPacket decrypt failed") )?; // deserialize Packet match Packet::from_bytes(&decrypted_data) { IResult::Incomplete(_) => { Err(Error::new(ErrorKind::Other, "Packet should not be incomplete")) }, IResult::Error(e) => { Err(Error::new(ErrorKind::Other, format!("deserialize Packet error: {:?}", e))) }, IResult::Done(_, packet) => { buf.split_to(consumed); Ok(Some(packet)) } } } } impl Encoder for Codec { type Item = Packet; type Error = Error; fn encode(&mut self, packet: Self::Item, buf: &mut BytesMut) -> Result<(), Self::Error> { // serialize Packet let mut packet_buf = [0; MAX_TCP_PACKET_SIZE]; let (_, packet_size) = packet.to_bytes((&mut packet_buf, 0)) .map_err(|e| Error::new(ErrorKind::Other, format!("Packet serialize error: {:?}", e)) )?; // encrypt it let encrypted = self.channel.encrypt(&packet_buf[..packet_size]); // create EncryptedPacket let encrypted_packet = EncryptedPacket { payload: encrypted }; // serialize EncryptedPacket to binary form let mut encrypted_packet_buf = [0; MAX_TCP_ENC_PACKET_SIZE]; let (_, encrypted_packet_size) = encrypted_packet.to_bytes((&mut encrypted_packet_buf, 0)) .expect("EncryptedPacket serialize failed"); // there is nothing to fail since // serialized Packet is not longer than 2032 bytes // and we provided 2050 bytes for EncryptedPacket buf.extend_from_slice(&encrypted_packet_buf[..encrypted_packet_size]); Ok(()) } } #[cfg(test)] mod tests { use ::toxcore::crypto_core::*; use ::toxcore::tcp::codec::*; fn create_channels() -> (Channel, Channel) { let alice_session = Session::new(); let bob_session = Session::new(); // assume we got Alice's PK & Nonce via handshake let alice_pk = *alice_session.pk(); let alice_nonce = *alice_session.nonce(); // assume we got Bob's PK & Nonce via handshake let bob_pk = *bob_session.pk(); let bob_nonce = *bob_session.nonce(); // Now both Alice and Bob may create secure Channels let alice_channel = Channel::new(alice_session, &bob_pk, &bob_nonce); let bob_channel = Channel::new(bob_session, &alice_pk, &alice_nonce); (alice_channel, bob_channel) } #[test] fn encode_decode() { let (pk, _) = gen_keypair(); let (alice_channel, bob_channel) = create_channels(); let mut buf = BytesMut::new(); let mut alice_codec = Codec::new(alice_channel); let mut bob_codec = Codec::new(bob_channel); let test_packets = vec![ Packet::RouteRequest( RouteRequest { pk: pk } ), Packet::RouteResponse( RouteResponse { connection_id: 42, pk: pk } ), Packet::ConnectNotification( ConnectNotification { connection_id: 42 } ), Packet::DisconnectNotification( DisconnectNotification { connection_id: 42 } ), Packet::PingRequest( PingRequest { ping_id: 4242 } ), Packet::PongResponse( PongResponse { ping_id: 4242 } ), Packet::OobSend( OobSend { destination_pk: pk, data: vec![13; 42] } ), Packet::OobReceive( OobReceive { sender_pk: pk, data: vec![13; 24] } ), Packet::Data( Data { connection_id: 42, data: vec![13; 2031] } ) ]; for packet in test_packets { alice_codec.encode(packet.clone(), &mut buf).expect("Alice should encode"); let res = bob_codec.decode(&mut buf).unwrap().expect("Bob should decode"); assert_eq!(packet, res); bob_codec.encode(packet.clone(), &mut buf).expect("Bob should encode"); let res = alice_codec.decode(&mut buf).unwrap().expect("Alice should decode"); assert_eq!(packet, res); } } #[test] fn decode_encrypted_packet_incomplete() { let (alice_channel, _) = create_channels(); let mut buf = BytesMut::new(); buf.extend_from_slice(b"\x00"); let mut alice_codec = Codec::new(alice_channel); // not enought bytes to decode EncryptedPacket assert_eq!(alice_codec.decode(&mut buf).unwrap(), None); } #[test] fn decode_encrypted_packet_zero_length() { let (alice_channel, _) = create_channels(); let mut buf = BytesMut::new(); buf.extend_from_slice(b"\x00\x00"); let mut alice_codec = Codec::new(alice_channel); // not enought bytes to decode EncryptedPacket assert!(alice_codec.decode(&mut buf).is_err()); } #[test] fn decode_encrypted_packet_wrong_key() { let (alice_channel, _) = create_channels(); let (mallory_channel, _) = create_channels(); let mut alice_codec = Codec::new(alice_channel); let mut mallory_codec = Codec::new(mallory_channel); let mut buf = BytesMut::new(); let packet = Packet::PingRequest( PingRequest { ping_id: 4242 } ); alice_codec.encode(packet.clone(), &mut buf).expect("Alice should encode"); // Mallory cannot decode the payload of EncryptedPacket assert!(mallory_codec.decode(&mut buf).err().is_some()); } fn encode_bytes_to_packet(channel: &Channel, bytes: &[u8]) -> Vec<u8> { // encrypt it let encrypted = channel.encrypt(bytes); // create EncryptedPacket let encrypted_packet = EncryptedPacket { payload: encrypted }; // serialize EncryptedPacket to binary form let mut stack_buf = [0; MAX_TCP_ENC_PACKET_SIZE]; let (_, encrypted_packet_size) = encrypted_packet.to_bytes((&mut stack_buf, 0)).unwrap(); stack_buf[..encrypted_packet_size].to_vec() } #[test] fn decode_packet_imcomplete() { let (alice_channel, bob_channel) = create_channels(); let mut buf = BytesMut::from(encode_bytes_to_packet(&alice_channel,b"\x00")); let mut bob_codec = Codec::new(bob_channel); // not enought bytes to decode Packet assert!(bob_codec.decode(&mut buf).err().is_some()); } #[test] fn decode_packet_error() { let (alice_channel, bob_channel) = create_channels(); let mut alice_codec = Codec::new(alice_channel); let mut bob_codec = Codec::new(bob_channel); let mut buf = BytesMut::new(); // bad Data with connection id = 0x0F let packet = Packet::Data( Data { connection_id: 0x0F, data: vec![13; 42] } ); alice_codec.encode(packet.clone(), &mut buf).expect("Alice should encode"); assert!(bob_codec.decode(&mut buf).is_err()); buf.clear(); // bad Data with connection id = 0xF0 let packet = Packet::Data( Data { connection_id: 0xF0, data: vec![13; 42] } ); alice_codec.encode(packet.clone(), &mut buf).expect("Alice should encode"); assert!(bob_codec.decode(&mut buf).is_err()); } #[test] fn encode_packet_too_big() { let (alice_channel, _) = create_channels(); let mut buf = BytesMut::new(); let mut alice_codec = Codec::new(alice_channel); let packet = Packet::Data( Data { connection_id: 42, data: vec![13; 2032] } ); // Alice cannot serialize Packet because it is too long assert!(alice_codec.encode(packet, &mut buf).is_err()); } }
random_line_split
codec.rs
/* Copyright (C) 2013 Tox project All Rights Reserved. Copyright © 2017 Zetok Zalbavar <[email protected]> Copyright © 2017 Roman Proskuryakov <[email protected]> This file is part of Tox. Tox is libre 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. Tox 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 Tox. If not, see <http://www.gnu.org/licenses/>. */ /*! Codec implementation for encoding/decoding TCP Packets in terms of tokio-io */ use toxcore::tcp::packet::*; use toxcore::tcp::secure::*; use toxcore::tcp::binary_io::*; use nom::Offset; use std::io::{Error, ErrorKind}; use bytes::BytesMut; use tokio_io::codec::{Decoder, Encoder}; /// implements tokio-io's Decoder and Encoder to deal with Packet pub struct Codec { channel: Channel } impl Codec { /// create a new Codec with the given Channel pub fn new(channel: Channel) -> Codec { Codec { channel: channel } } } impl Decoder for Codec { type Item = Packet; type Error = Error; fn decode(&mut self, buf: &mut BytesMut) -> Result<Option<Self::Item>, Self::Error> { // deserialize EncryptedPacket let (consumed, encrypted_packet) = match EncryptedPacket::from_bytes(buf) { IResult::Incomplete(_) => { return Ok(None) }, IResult::Error(e) => { return Err(Error::new(ErrorKind::Other, format!("EncryptedPacket deserialize error: {:?}", e))) }, IResult::Done(i, encrypted_packet) => { (buf.offset(i), encrypted_packet) } }; // decrypt payload let decrypted_data = self.channel.decrypt(&encrypted_packet.payload) .map_err(|_| Error::new(ErrorKind::Other, "EncryptedPacket decrypt failed") )?; // deserialize Packet match Packet::from_bytes(&decrypted_data) { IResult::Incomplete(_) => {
IResult::Error(e) => { Err(Error::new(ErrorKind::Other, format!("deserialize Packet error: {:?}", e))) }, IResult::Done(_, packet) => { buf.split_to(consumed); Ok(Some(packet)) } } } } impl Encoder for Codec { type Item = Packet; type Error = Error; fn encode(&mut self, packet: Self::Item, buf: &mut BytesMut) -> Result<(), Self::Error> { // serialize Packet let mut packet_buf = [0; MAX_TCP_PACKET_SIZE]; let (_, packet_size) = packet.to_bytes((&mut packet_buf, 0)) .map_err(|e| Error::new(ErrorKind::Other, format!("Packet serialize error: {:?}", e)) )?; // encrypt it let encrypted = self.channel.encrypt(&packet_buf[..packet_size]); // create EncryptedPacket let encrypted_packet = EncryptedPacket { payload: encrypted }; // serialize EncryptedPacket to binary form let mut encrypted_packet_buf = [0; MAX_TCP_ENC_PACKET_SIZE]; let (_, encrypted_packet_size) = encrypted_packet.to_bytes((&mut encrypted_packet_buf, 0)) .expect("EncryptedPacket serialize failed"); // there is nothing to fail since // serialized Packet is not longer than 2032 bytes // and we provided 2050 bytes for EncryptedPacket buf.extend_from_slice(&encrypted_packet_buf[..encrypted_packet_size]); Ok(()) } } #[cfg(test)] mod tests { use ::toxcore::crypto_core::*; use ::toxcore::tcp::codec::*; fn create_channels() -> (Channel, Channel) { let alice_session = Session::new(); let bob_session = Session::new(); // assume we got Alice's PK & Nonce via handshake let alice_pk = *alice_session.pk(); let alice_nonce = *alice_session.nonce(); // assume we got Bob's PK & Nonce via handshake let bob_pk = *bob_session.pk(); let bob_nonce = *bob_session.nonce(); // Now both Alice and Bob may create secure Channels let alice_channel = Channel::new(alice_session, &bob_pk, &bob_nonce); let bob_channel = Channel::new(bob_session, &alice_pk, &alice_nonce); (alice_channel, bob_channel) } #[test] fn encode_decode() { let (pk, _) = gen_keypair(); let (alice_channel, bob_channel) = create_channels(); let mut buf = BytesMut::new(); let mut alice_codec = Codec::new(alice_channel); let mut bob_codec = Codec::new(bob_channel); let test_packets = vec![ Packet::RouteRequest( RouteRequest { pk: pk } ), Packet::RouteResponse( RouteResponse { connection_id: 42, pk: pk } ), Packet::ConnectNotification( ConnectNotification { connection_id: 42 } ), Packet::DisconnectNotification( DisconnectNotification { connection_id: 42 } ), Packet::PingRequest( PingRequest { ping_id: 4242 } ), Packet::PongResponse( PongResponse { ping_id: 4242 } ), Packet::OobSend( OobSend { destination_pk: pk, data: vec![13; 42] } ), Packet::OobReceive( OobReceive { sender_pk: pk, data: vec![13; 24] } ), Packet::Data( Data { connection_id: 42, data: vec![13; 2031] } ) ]; for packet in test_packets { alice_codec.encode(packet.clone(), &mut buf).expect("Alice should encode"); let res = bob_codec.decode(&mut buf).unwrap().expect("Bob should decode"); assert_eq!(packet, res); bob_codec.encode(packet.clone(), &mut buf).expect("Bob should encode"); let res = alice_codec.decode(&mut buf).unwrap().expect("Alice should decode"); assert_eq!(packet, res); } } #[test] fn decode_encrypted_packet_incomplete() { let (alice_channel, _) = create_channels(); let mut buf = BytesMut::new(); buf.extend_from_slice(b"\x00"); let mut alice_codec = Codec::new(alice_channel); // not enought bytes to decode EncryptedPacket assert_eq!(alice_codec.decode(&mut buf).unwrap(), None); } #[test] fn decode_encrypted_packet_zero_length() { let (alice_channel, _) = create_channels(); let mut buf = BytesMut::new(); buf.extend_from_slice(b"\x00\x00"); let mut alice_codec = Codec::new(alice_channel); // not enought bytes to decode EncryptedPacket assert!(alice_codec.decode(&mut buf).is_err()); } #[test] fn decode_encrypted_packet_wrong_key() { let (alice_channel, _) = create_channels(); let (mallory_channel, _) = create_channels(); let mut alice_codec = Codec::new(alice_channel); let mut mallory_codec = Codec::new(mallory_channel); let mut buf = BytesMut::new(); let packet = Packet::PingRequest( PingRequest { ping_id: 4242 } ); alice_codec.encode(packet.clone(), &mut buf).expect("Alice should encode"); // Mallory cannot decode the payload of EncryptedPacket assert!(mallory_codec.decode(&mut buf).err().is_some()); } fn encode_bytes_to_packet(channel: &Channel, bytes: &[u8]) -> Vec<u8> { // encrypt it let encrypted = channel.encrypt(bytes); // create EncryptedPacket let encrypted_packet = EncryptedPacket { payload: encrypted }; // serialize EncryptedPacket to binary form let mut stack_buf = [0; MAX_TCP_ENC_PACKET_SIZE]; let (_, encrypted_packet_size) = encrypted_packet.to_bytes((&mut stack_buf, 0)).unwrap(); stack_buf[..encrypted_packet_size].to_vec() } #[test] fn decode_packet_imcomplete() { let (alice_channel, bob_channel) = create_channels(); let mut buf = BytesMut::from(encode_bytes_to_packet(&alice_channel,b"\x00")); let mut bob_codec = Codec::new(bob_channel); // not enought bytes to decode Packet assert!(bob_codec.decode(&mut buf).err().is_some()); } #[test] fn decode_packet_error() { let (alice_channel, bob_channel) = create_channels(); let mut alice_codec = Codec::new(alice_channel); let mut bob_codec = Codec::new(bob_channel); let mut buf = BytesMut::new(); // bad Data with connection id = 0x0F let packet = Packet::Data( Data { connection_id: 0x0F, data: vec![13; 42] } ); alice_codec.encode(packet.clone(), &mut buf).expect("Alice should encode"); assert!(bob_codec.decode(&mut buf).is_err()); buf.clear(); // bad Data with connection id = 0xF0 let packet = Packet::Data( Data { connection_id: 0xF0, data: vec![13; 42] } ); alice_codec.encode(packet.clone(), &mut buf).expect("Alice should encode"); assert!(bob_codec.decode(&mut buf).is_err()); } #[test] fn encode_packet_too_big() { let (alice_channel, _) = create_channels(); let mut buf = BytesMut::new(); let mut alice_codec = Codec::new(alice_channel); let packet = Packet::Data( Data { connection_id: 42, data: vec![13; 2032] } ); // Alice cannot serialize Packet because it is too long assert!(alice_codec.encode(packet, &mut buf).is_err()); } }
Err(Error::new(ErrorKind::Other, "Packet should not be incomplete")) },
conditional_block
codec.rs
/* Copyright (C) 2013 Tox project All Rights Reserved. Copyright © 2017 Zetok Zalbavar <[email protected]> Copyright © 2017 Roman Proskuryakov <[email protected]> This file is part of Tox. Tox is libre 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. Tox 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 Tox. If not, see <http://www.gnu.org/licenses/>. */ /*! Codec implementation for encoding/decoding TCP Packets in terms of tokio-io */ use toxcore::tcp::packet::*; use toxcore::tcp::secure::*; use toxcore::tcp::binary_io::*; use nom::Offset; use std::io::{Error, ErrorKind}; use bytes::BytesMut; use tokio_io::codec::{Decoder, Encoder}; /// implements tokio-io's Decoder and Encoder to deal with Packet pub struct Codec { channel: Channel } impl Codec { /// create a new Codec with the given Channel pub fn new(channel: Channel) -> Codec { Codec { channel: channel } } } impl Decoder for Codec { type Item = Packet; type Error = Error; fn decode(&mut self, buf: &mut BytesMut) -> Result<Option<Self::Item>, Self::Error> { // deserialize EncryptedPacket let (consumed, encrypted_packet) = match EncryptedPacket::from_bytes(buf) { IResult::Incomplete(_) => { return Ok(None) }, IResult::Error(e) => { return Err(Error::new(ErrorKind::Other, format!("EncryptedPacket deserialize error: {:?}", e))) }, IResult::Done(i, encrypted_packet) => { (buf.offset(i), encrypted_packet) } }; // decrypt payload let decrypted_data = self.channel.decrypt(&encrypted_packet.payload) .map_err(|_| Error::new(ErrorKind::Other, "EncryptedPacket decrypt failed") )?; // deserialize Packet match Packet::from_bytes(&decrypted_data) { IResult::Incomplete(_) => { Err(Error::new(ErrorKind::Other, "Packet should not be incomplete")) }, IResult::Error(e) => { Err(Error::new(ErrorKind::Other, format!("deserialize Packet error: {:?}", e))) }, IResult::Done(_, packet) => { buf.split_to(consumed); Ok(Some(packet)) } } } } impl Encoder for Codec { type Item = Packet; type Error = Error; fn encode(&mut self, packet: Self::Item, buf: &mut BytesMut) -> Result<(), Self::Error> { // serialize Packet let mut packet_buf = [0; MAX_TCP_PACKET_SIZE]; let (_, packet_size) = packet.to_bytes((&mut packet_buf, 0)) .map_err(|e| Error::new(ErrorKind::Other, format!("Packet serialize error: {:?}", e)) )?; // encrypt it let encrypted = self.channel.encrypt(&packet_buf[..packet_size]); // create EncryptedPacket let encrypted_packet = EncryptedPacket { payload: encrypted }; // serialize EncryptedPacket to binary form let mut encrypted_packet_buf = [0; MAX_TCP_ENC_PACKET_SIZE]; let (_, encrypted_packet_size) = encrypted_packet.to_bytes((&mut encrypted_packet_buf, 0)) .expect("EncryptedPacket serialize failed"); // there is nothing to fail since // serialized Packet is not longer than 2032 bytes // and we provided 2050 bytes for EncryptedPacket buf.extend_from_slice(&encrypted_packet_buf[..encrypted_packet_size]); Ok(()) } } #[cfg(test)] mod tests { use ::toxcore::crypto_core::*; use ::toxcore::tcp::codec::*; fn create_channels() -> (Channel, Channel) { let alice_session = Session::new(); let bob_session = Session::new(); // assume we got Alice's PK & Nonce via handshake let alice_pk = *alice_session.pk(); let alice_nonce = *alice_session.nonce(); // assume we got Bob's PK & Nonce via handshake let bob_pk = *bob_session.pk(); let bob_nonce = *bob_session.nonce(); // Now both Alice and Bob may create secure Channels let alice_channel = Channel::new(alice_session, &bob_pk, &bob_nonce); let bob_channel = Channel::new(bob_session, &alice_pk, &alice_nonce); (alice_channel, bob_channel) } #[test] fn en
{ let (pk, _) = gen_keypair(); let (alice_channel, bob_channel) = create_channels(); let mut buf = BytesMut::new(); let mut alice_codec = Codec::new(alice_channel); let mut bob_codec = Codec::new(bob_channel); let test_packets = vec![ Packet::RouteRequest( RouteRequest { pk: pk } ), Packet::RouteResponse( RouteResponse { connection_id: 42, pk: pk } ), Packet::ConnectNotification( ConnectNotification { connection_id: 42 } ), Packet::DisconnectNotification( DisconnectNotification { connection_id: 42 } ), Packet::PingRequest( PingRequest { ping_id: 4242 } ), Packet::PongResponse( PongResponse { ping_id: 4242 } ), Packet::OobSend( OobSend { destination_pk: pk, data: vec![13; 42] } ), Packet::OobReceive( OobReceive { sender_pk: pk, data: vec![13; 24] } ), Packet::Data( Data { connection_id: 42, data: vec![13; 2031] } ) ]; for packet in test_packets { alice_codec.encode(packet.clone(), &mut buf).expect("Alice should encode"); let res = bob_codec.decode(&mut buf).unwrap().expect("Bob should decode"); assert_eq!(packet, res); bob_codec.encode(packet.clone(), &mut buf).expect("Bob should encode"); let res = alice_codec.decode(&mut buf).unwrap().expect("Alice should decode"); assert_eq!(packet, res); } } #[test] fn decode_encrypted_packet_incomplete() { let (alice_channel, _) = create_channels(); let mut buf = BytesMut::new(); buf.extend_from_slice(b"\x00"); let mut alice_codec = Codec::new(alice_channel); // not enought bytes to decode EncryptedPacket assert_eq!(alice_codec.decode(&mut buf).unwrap(), None); } #[test] fn decode_encrypted_packet_zero_length() { let (alice_channel, _) = create_channels(); let mut buf = BytesMut::new(); buf.extend_from_slice(b"\x00\x00"); let mut alice_codec = Codec::new(alice_channel); // not enought bytes to decode EncryptedPacket assert!(alice_codec.decode(&mut buf).is_err()); } #[test] fn decode_encrypted_packet_wrong_key() { let (alice_channel, _) = create_channels(); let (mallory_channel, _) = create_channels(); let mut alice_codec = Codec::new(alice_channel); let mut mallory_codec = Codec::new(mallory_channel); let mut buf = BytesMut::new(); let packet = Packet::PingRequest( PingRequest { ping_id: 4242 } ); alice_codec.encode(packet.clone(), &mut buf).expect("Alice should encode"); // Mallory cannot decode the payload of EncryptedPacket assert!(mallory_codec.decode(&mut buf).err().is_some()); } fn encode_bytes_to_packet(channel: &Channel, bytes: &[u8]) -> Vec<u8> { // encrypt it let encrypted = channel.encrypt(bytes); // create EncryptedPacket let encrypted_packet = EncryptedPacket { payload: encrypted }; // serialize EncryptedPacket to binary form let mut stack_buf = [0; MAX_TCP_ENC_PACKET_SIZE]; let (_, encrypted_packet_size) = encrypted_packet.to_bytes((&mut stack_buf, 0)).unwrap(); stack_buf[..encrypted_packet_size].to_vec() } #[test] fn decode_packet_imcomplete() { let (alice_channel, bob_channel) = create_channels(); let mut buf = BytesMut::from(encode_bytes_to_packet(&alice_channel,b"\x00")); let mut bob_codec = Codec::new(bob_channel); // not enought bytes to decode Packet assert!(bob_codec.decode(&mut buf).err().is_some()); } #[test] fn decode_packet_error() { let (alice_channel, bob_channel) = create_channels(); let mut alice_codec = Codec::new(alice_channel); let mut bob_codec = Codec::new(bob_channel); let mut buf = BytesMut::new(); // bad Data with connection id = 0x0F let packet = Packet::Data( Data { connection_id: 0x0F, data: vec![13; 42] } ); alice_codec.encode(packet.clone(), &mut buf).expect("Alice should encode"); assert!(bob_codec.decode(&mut buf).is_err()); buf.clear(); // bad Data with connection id = 0xF0 let packet = Packet::Data( Data { connection_id: 0xF0, data: vec![13; 42] } ); alice_codec.encode(packet.clone(), &mut buf).expect("Alice should encode"); assert!(bob_codec.decode(&mut buf).is_err()); } #[test] fn encode_packet_too_big() { let (alice_channel, _) = create_channels(); let mut buf = BytesMut::new(); let mut alice_codec = Codec::new(alice_channel); let packet = Packet::Data( Data { connection_id: 42, data: vec![13; 2032] } ); // Alice cannot serialize Packet because it is too long assert!(alice_codec.encode(packet, &mut buf).is_err()); } }
code_decode()
identifier_name
codec.rs
/* Copyright (C) 2013 Tox project All Rights Reserved. Copyright © 2017 Zetok Zalbavar <[email protected]> Copyright © 2017 Roman Proskuryakov <[email protected]> This file is part of Tox. Tox is libre 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. Tox 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 Tox. If not, see <http://www.gnu.org/licenses/>. */ /*! Codec implementation for encoding/decoding TCP Packets in terms of tokio-io */ use toxcore::tcp::packet::*; use toxcore::tcp::secure::*; use toxcore::tcp::binary_io::*; use nom::Offset; use std::io::{Error, ErrorKind}; use bytes::BytesMut; use tokio_io::codec::{Decoder, Encoder}; /// implements tokio-io's Decoder and Encoder to deal with Packet pub struct Codec { channel: Channel } impl Codec { /// create a new Codec with the given Channel pub fn new(channel: Channel) -> Codec { Codec { channel: channel } } } impl Decoder for Codec { type Item = Packet; type Error = Error; fn decode(&mut self, buf: &mut BytesMut) -> Result<Option<Self::Item>, Self::Error> { // deserialize EncryptedPacket let (consumed, encrypted_packet) = match EncryptedPacket::from_bytes(buf) { IResult::Incomplete(_) => { return Ok(None) }, IResult::Error(e) => { return Err(Error::new(ErrorKind::Other, format!("EncryptedPacket deserialize error: {:?}", e))) }, IResult::Done(i, encrypted_packet) => { (buf.offset(i), encrypted_packet) } }; // decrypt payload let decrypted_data = self.channel.decrypt(&encrypted_packet.payload) .map_err(|_| Error::new(ErrorKind::Other, "EncryptedPacket decrypt failed") )?; // deserialize Packet match Packet::from_bytes(&decrypted_data) { IResult::Incomplete(_) => { Err(Error::new(ErrorKind::Other, "Packet should not be incomplete")) }, IResult::Error(e) => { Err(Error::new(ErrorKind::Other, format!("deserialize Packet error: {:?}", e))) }, IResult::Done(_, packet) => { buf.split_to(consumed); Ok(Some(packet)) } } } } impl Encoder for Codec { type Item = Packet; type Error = Error; fn encode(&mut self, packet: Self::Item, buf: &mut BytesMut) -> Result<(), Self::Error> { // serialize Packet let mut packet_buf = [0; MAX_TCP_PACKET_SIZE]; let (_, packet_size) = packet.to_bytes((&mut packet_buf, 0)) .map_err(|e| Error::new(ErrorKind::Other, format!("Packet serialize error: {:?}", e)) )?; // encrypt it let encrypted = self.channel.encrypt(&packet_buf[..packet_size]); // create EncryptedPacket let encrypted_packet = EncryptedPacket { payload: encrypted }; // serialize EncryptedPacket to binary form let mut encrypted_packet_buf = [0; MAX_TCP_ENC_PACKET_SIZE]; let (_, encrypted_packet_size) = encrypted_packet.to_bytes((&mut encrypted_packet_buf, 0)) .expect("EncryptedPacket serialize failed"); // there is nothing to fail since // serialized Packet is not longer than 2032 bytes // and we provided 2050 bytes for EncryptedPacket buf.extend_from_slice(&encrypted_packet_buf[..encrypted_packet_size]); Ok(()) } } #[cfg(test)] mod tests { use ::toxcore::crypto_core::*; use ::toxcore::tcp::codec::*; fn create_channels() -> (Channel, Channel) { let alice_session = Session::new(); let bob_session = Session::new(); // assume we got Alice's PK & Nonce via handshake let alice_pk = *alice_session.pk(); let alice_nonce = *alice_session.nonce(); // assume we got Bob's PK & Nonce via handshake let bob_pk = *bob_session.pk(); let bob_nonce = *bob_session.nonce(); // Now both Alice and Bob may create secure Channels let alice_channel = Channel::new(alice_session, &bob_pk, &bob_nonce); let bob_channel = Channel::new(bob_session, &alice_pk, &alice_nonce); (alice_channel, bob_channel) } #[test] fn encode_decode() { let (pk, _) = gen_keypair(); let (alice_channel, bob_channel) = create_channels(); let mut buf = BytesMut::new(); let mut alice_codec = Codec::new(alice_channel); let mut bob_codec = Codec::new(bob_channel); let test_packets = vec![ Packet::RouteRequest( RouteRequest { pk: pk } ), Packet::RouteResponse( RouteResponse { connection_id: 42, pk: pk } ), Packet::ConnectNotification( ConnectNotification { connection_id: 42 } ), Packet::DisconnectNotification( DisconnectNotification { connection_id: 42 } ), Packet::PingRequest( PingRequest { ping_id: 4242 } ), Packet::PongResponse( PongResponse { ping_id: 4242 } ), Packet::OobSend( OobSend { destination_pk: pk, data: vec![13; 42] } ), Packet::OobReceive( OobReceive { sender_pk: pk, data: vec![13; 24] } ), Packet::Data( Data { connection_id: 42, data: vec![13; 2031] } ) ]; for packet in test_packets { alice_codec.encode(packet.clone(), &mut buf).expect("Alice should encode"); let res = bob_codec.decode(&mut buf).unwrap().expect("Bob should decode"); assert_eq!(packet, res); bob_codec.encode(packet.clone(), &mut buf).expect("Bob should encode"); let res = alice_codec.decode(&mut buf).unwrap().expect("Alice should decode"); assert_eq!(packet, res); } } #[test] fn decode_encrypted_packet_incomplete() { let (alice_channel, _) = create_channels(); let mut buf = BytesMut::new(); buf.extend_from_slice(b"\x00"); let mut alice_codec = Codec::new(alice_channel); // not enought bytes to decode EncryptedPacket assert_eq!(alice_codec.decode(&mut buf).unwrap(), None); } #[test] fn decode_encrypted_packet_zero_length() { let (alice_channel, _) = create_channels(); let mut buf = BytesMut::new(); buf.extend_from_slice(b"\x00\x00"); let mut alice_codec = Codec::new(alice_channel); // not enought bytes to decode EncryptedPacket assert!(alice_codec.decode(&mut buf).is_err()); } #[test] fn decode_encrypted_packet_wrong_key() { let (alice_channel, _) = create_channels(); let (mallory_channel, _) = create_channels(); let mut alice_codec = Codec::new(alice_channel); let mut mallory_codec = Codec::new(mallory_channel); let mut buf = BytesMut::new(); let packet = Packet::PingRequest( PingRequest { ping_id: 4242 } ); alice_codec.encode(packet.clone(), &mut buf).expect("Alice should encode"); // Mallory cannot decode the payload of EncryptedPacket assert!(mallory_codec.decode(&mut buf).err().is_some()); } fn encode_bytes_to_packet(channel: &Channel, bytes: &[u8]) -> Vec<u8> { // encrypt it let encrypted = channel.encrypt(bytes); // create EncryptedPacket let encrypted_packet = EncryptedPacket { payload: encrypted }; // serialize EncryptedPacket to binary form let mut stack_buf = [0; MAX_TCP_ENC_PACKET_SIZE]; let (_, encrypted_packet_size) = encrypted_packet.to_bytes((&mut stack_buf, 0)).unwrap(); stack_buf[..encrypted_packet_size].to_vec() } #[test] fn decode_packet_imcomplete() {
#[test] fn decode_packet_error() { let (alice_channel, bob_channel) = create_channels(); let mut alice_codec = Codec::new(alice_channel); let mut bob_codec = Codec::new(bob_channel); let mut buf = BytesMut::new(); // bad Data with connection id = 0x0F let packet = Packet::Data( Data { connection_id: 0x0F, data: vec![13; 42] } ); alice_codec.encode(packet.clone(), &mut buf).expect("Alice should encode"); assert!(bob_codec.decode(&mut buf).is_err()); buf.clear(); // bad Data with connection id = 0xF0 let packet = Packet::Data( Data { connection_id: 0xF0, data: vec![13; 42] } ); alice_codec.encode(packet.clone(), &mut buf).expect("Alice should encode"); assert!(bob_codec.decode(&mut buf).is_err()); } #[test] fn encode_packet_too_big() { let (alice_channel, _) = create_channels(); let mut buf = BytesMut::new(); let mut alice_codec = Codec::new(alice_channel); let packet = Packet::Data( Data { connection_id: 42, data: vec![13; 2032] } ); // Alice cannot serialize Packet because it is too long assert!(alice_codec.encode(packet, &mut buf).is_err()); } }
let (alice_channel, bob_channel) = create_channels(); let mut buf = BytesMut::from(encode_bytes_to_packet(&alice_channel,b"\x00")); let mut bob_codec = Codec::new(bob_channel); // not enought bytes to decode Packet assert!(bob_codec.decode(&mut buf).err().is_some()); }
identifier_body
font.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ use app_units::Au; use font::{FontHandleMethods, FontMetrics, FontTableMethods}; use font::{FontTableTag, FractionalPixel, GPOS, GSUB, KERN}; use freetype::freetype::{FT_Done_Face, FT_New_Memory_Face}; use freetype::freetype::{FT_F26Dot6, FT_Face, FT_FaceRec}; use freetype::freetype::{FT_Get_Char_Index, FT_Get_Postscript_Name}; use freetype::freetype::{FT_Get_Kerning, FT_Get_Sfnt_Table, FT_Load_Sfnt_Table}; use freetype::freetype::{FT_GlyphSlot, FT_Library, FT_Long, FT_ULong}; use freetype::freetype::{FT_Int32, FT_Kerning_Mode, FT_STYLE_FLAG_ITALIC}; use freetype::freetype::{FT_Load_Glyph, FT_Set_Char_Size}; use freetype::freetype::{FT_SizeRec, FT_Size_Metrics, FT_UInt, FT_Vector}; use freetype::freetype::FT_Sfnt_Tag; use freetype::tt_os2::TT_OS2; use platform::font_context::FontContextHandle; use platform::font_template::FontTemplateData; use servo_atoms::Atom; use std::{mem, ptr}; use std::os::raw::{c_char, c_long}; use std::sync::Arc; use style::computed_values::font_stretch::T as FontStretch; use style::computed_values::font_weight::T as FontWeight; use super::c_str_to_string; use text::glyph::GlyphId; use text::util::fixed_to_float; // This constant is not present in the freetype // bindings due to bindgen not handling the way // the macro is defined. const FT_LOAD_TARGET_LIGHT: FT_Int32 = 1 << 16; // Default to slight hinting, which is what most // Linux distros use by default, and is a better // default than no hinting. // TODO(gw): Make this configurable. const GLYPH_LOAD_FLAGS: FT_Int32 = FT_LOAD_TARGET_LIGHT; fn fixed_to_float_ft(f: i32) -> f64 { fixed_to_float(6, f) } #[derive(Debug)] pub struct FontTable { buffer: Vec<u8>, } impl FontTableMethods for FontTable { fn buffer(&self) -> &[u8] { &self.buffer } } /// Data from the OS/2 table of an OpenType font. /// See https://www.microsoft.com/typography/otspec/os2.htm #[derive(Debug)] struct OS2Table { us_weight_class: u16, us_width_class: u16, y_strikeout_size: i16, y_strikeout_position: i16, sx_height: i16, } #[derive(Debug)] pub struct FontHandle { // The font binary. This must stay valid for the lifetime of the font, // if the font is created using FT_Memory_Face. font_data: Arc<FontTemplateData>, face: FT_Face, handle: FontContextHandle, can_do_fast_shaping: bool, } impl Drop for FontHandle { fn drop(&mut self) { assert!(!self.face.is_null()); unsafe { if!FT_Done_Face(self.face).succeeded()
} } } impl FontHandleMethods for FontHandle { fn new_from_template(fctx: &FontContextHandle, template: Arc<FontTemplateData>, pt_size: Option<Au>) -> Result<FontHandle, ()> { let ft_ctx: FT_Library = fctx.ctx.ctx; if ft_ctx.is_null() { return Err(()); } return create_face_from_buffer(ft_ctx, &template.bytes, pt_size).map(|face| { let mut handle = FontHandle { face: face, font_data: template.clone(), handle: fctx.clone(), can_do_fast_shaping: false, }; // TODO (#11310): Implement basic support for GPOS and GSUB. handle.can_do_fast_shaping = handle.has_table(KERN) && !handle.has_table(GPOS) && !handle.has_table(GSUB); handle }); fn create_face_from_buffer(lib: FT_Library, buffer: &[u8], pt_size: Option<Au>) -> Result<FT_Face, ()> { unsafe { let mut face: FT_Face = ptr::null_mut(); let face_index = 0 as FT_Long; let result = FT_New_Memory_Face(lib, buffer.as_ptr(), buffer.len() as FT_Long, face_index, &mut face); if!result.succeeded() || face.is_null() { return Err(()); } if let Some(s) = pt_size { FontHandle::set_char_size(face, s).or(Err(()))? } Ok(face) } } } fn template(&self) -> Arc<FontTemplateData> { self.font_data.clone() } fn family_name(&self) -> String { unsafe { c_str_to_string((*self.face).family_name as *const c_char) } } fn face_name(&self) -> Option<String> { unsafe { let name = FT_Get_Postscript_Name(self.face) as *const c_char; if!name.is_null() { Some(c_str_to_string(name)) } else { None } } } fn is_italic(&self) -> bool { unsafe { (*self.face).style_flags & FT_STYLE_FLAG_ITALIC as c_long!= 0 } } fn boldness(&self) -> FontWeight { if let Some(os2) = self.os2_table() { let weight = os2.us_weight_class as i32; if weight < 10 { FontWeight::from_int(weight * 100).unwrap() } else if weight >= 100 && weight < 1000 { FontWeight::from_int(weight / 100 * 100).unwrap() } else { FontWeight::normal() } } else { FontWeight::normal() } } fn stretchiness(&self) -> FontStretch { if let Some(os2) = self.os2_table() { match os2.us_width_class { 1 => FontStretch::UltraCondensed, 2 => FontStretch::ExtraCondensed, 3 => FontStretch::Condensed, 4 => FontStretch::SemiCondensed, 5 => FontStretch::Normal, 6 => FontStretch::SemiExpanded, 7 => FontStretch::Expanded, 8 => FontStretch::ExtraExpanded, 9 => FontStretch::UltraExpanded, _ => FontStretch::Normal } } else { FontStretch::Normal } } fn glyph_index(&self, codepoint: char) -> Option<GlyphId> { assert!(!self.face.is_null()); unsafe { let idx = FT_Get_Char_Index(self.face, codepoint as FT_ULong); if idx!= 0 as FT_UInt { Some(idx as GlyphId) } else { debug!("Invalid codepoint: {}", codepoint); None } } } fn glyph_h_kerning(&self, first_glyph: GlyphId, second_glyph: GlyphId) -> FractionalPixel { assert!(!self.face.is_null()); let mut delta = FT_Vector { x: 0, y: 0 }; unsafe { FT_Get_Kerning(self.face, first_glyph, second_glyph, FT_Kerning_Mode::FT_KERNING_DEFAULT as FT_UInt, &mut delta); } fixed_to_float_ft(delta.x as i32) } fn can_do_fast_shaping(&self) -> bool { self.can_do_fast_shaping } fn glyph_h_advance(&self, glyph: GlyphId) -> Option<FractionalPixel> { assert!(!self.face.is_null()); unsafe { let res = FT_Load_Glyph(self.face, glyph as FT_UInt, GLYPH_LOAD_FLAGS); if res.succeeded() { let void_glyph = (*self.face).glyph; let slot: FT_GlyphSlot = mem::transmute(void_glyph); assert!(!slot.is_null()); let advance = (*slot).metrics.horiAdvance; debug!("h_advance for {} is {}", glyph, advance); let advance = advance as i32; Some(fixed_to_float_ft(advance) as FractionalPixel) } else { debug!("Unable to load glyph {}. reason: {:?}", glyph, res); None } } } fn metrics(&self) -> FontMetrics { /* TODO(Issue #76): complete me */ let face = self.face_rec_mut(); let underline_size = self.font_units_to_au(face.underline_thickness as f64); let underline_offset = self.font_units_to_au(face.underline_position as f64); let em_size = self.font_units_to_au(face.units_per_EM as f64); let ascent = self.font_units_to_au(face.ascender as f64); let descent = self.font_units_to_au(face.descender as f64); let max_advance = self.font_units_to_au(face.max_advance_width as f64); // 'leading' is supposed to be the vertical distance between two baselines, // reflected by the height attribute in freetype. On OS X (w/ CTFont), // leading represents the distance between the bottom of a line descent to // the top of the next line's ascent or: (line_height - ascent - descent), // see http://stackoverflow.com/a/5635981 for CTFont implementation. // Convert using a formula similar to what CTFont returns for consistency. let height = self.font_units_to_au(face.height as f64); let leading = height - (ascent + descent); let mut strikeout_size = Au(0); let mut strikeout_offset = Au(0); let mut x_height = Au(0); if let Some(os2) = self.os2_table() { strikeout_size = self.font_units_to_au(os2.y_strikeout_size as f64); strikeout_offset = self.font_units_to_au(os2.y_strikeout_position as f64); x_height = self.font_units_to_au(os2.sx_height as f64); } let average_advance = self.glyph_index('0') .and_then(|idx| self.glyph_h_advance(idx)) .map_or(max_advance, |advance| self.font_units_to_au(advance)); let metrics = FontMetrics { underline_size: underline_size, underline_offset: underline_offset, strikeout_size: strikeout_size, strikeout_offset: strikeout_offset, leading: leading, x_height: x_height, em_size: em_size, ascent: ascent, descent: -descent, // linux font's seem to use the opposite sign from mac max_advance: max_advance, average_advance: average_advance, line_gap: height, }; debug!("Font metrics (@{}px): {:?}", em_size.to_f32_px(), metrics); metrics } fn table_for_tag(&self, tag: FontTableTag) -> Option<FontTable> { let tag = tag as FT_ULong; unsafe { // Get the length let mut len = 0; if!FT_Load_Sfnt_Table(self.face, tag, 0, ptr::null_mut(), &mut len).succeeded() { return None } // Get the bytes let mut buf = vec![0u8; len as usize]; if!FT_Load_Sfnt_Table(self.face, tag, 0, buf.as_mut_ptr(), &mut len).succeeded() { return None } Some(FontTable { buffer: buf }) } } fn identifier(&self) -> Atom { self.font_data.identifier.clone() } } impl<'a> FontHandle { fn set_char_size(face: FT_Face, pt_size: Au) -> Result<(), ()>{ let char_size = pt_size.to_f64_px() * 64.0 + 0.5; unsafe { let result = FT_Set_Char_Size(face, char_size as FT_F26Dot6, 0, 0, 0); if result.succeeded() { Ok(()) } else { Err(()) } } } fn has_table(&self, tag: FontTableTag) -> bool { unsafe { FT_Load_Sfnt_Table(self.face, tag as FT_ULong, 0, ptr::null_mut(), &mut 0).succeeded() } } fn face_rec_mut(&'a self) -> &'a mut FT_FaceRec { unsafe { &mut (*self.face) } } fn font_units_to_au(&self, value: f64) -> Au { let face = self.face_rec_mut(); // face.size is a *c_void in the bindings, presumably to avoid // recursive structural types let size: &FT_SizeRec = unsafe { mem::transmute(&(*face.size)) }; let metrics: &FT_Size_Metrics = &(*size).metrics; let em_size = face.units_per_EM as f64; let x_scale = (metrics.x_ppem as f64) / em_size as f64; // If this isn't true then we're scaling one of the axes wrong assert_eq!(metrics.x_ppem, metrics.y_ppem); Au::from_f64_px(value * x_scale) } fn os2_table(&self) -> Option<OS2Table> { unsafe { let os2 = FT_Get_Sfnt_Table(self.face_rec_mut(), FT_Sfnt_Tag::FT_SFNT_OS2) as *mut TT_OS2; let valid =!os2.is_null() && (*os2).version!= 0xffff; if!valid { return None } Some(OS2Table { us_weight_class: (*os2).usWeightClass, us_width_class: (*os2).usWidthClass, y_strikeout_size: (*os2).yStrikeoutSize, y_strikeout_position: (*os2).yStrikeoutPosition, sx_height: (*os2).sxHeight, }) } } }
{ panic!("FT_Done_Face failed"); }
conditional_block
font.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ use app_units::Au; use font::{FontHandleMethods, FontMetrics, FontTableMethods}; use font::{FontTableTag, FractionalPixel, GPOS, GSUB, KERN}; use freetype::freetype::{FT_Done_Face, FT_New_Memory_Face}; use freetype::freetype::{FT_F26Dot6, FT_Face, FT_FaceRec}; use freetype::freetype::{FT_Get_Char_Index, FT_Get_Postscript_Name}; use freetype::freetype::{FT_Get_Kerning, FT_Get_Sfnt_Table, FT_Load_Sfnt_Table}; use freetype::freetype::{FT_GlyphSlot, FT_Library, FT_Long, FT_ULong}; use freetype::freetype::{FT_Int32, FT_Kerning_Mode, FT_STYLE_FLAG_ITALIC}; use freetype::freetype::{FT_Load_Glyph, FT_Set_Char_Size}; use freetype::freetype::{FT_SizeRec, FT_Size_Metrics, FT_UInt, FT_Vector}; use freetype::freetype::FT_Sfnt_Tag; use freetype::tt_os2::TT_OS2; use platform::font_context::FontContextHandle; use platform::font_template::FontTemplateData; use servo_atoms::Atom; use std::{mem, ptr}; use std::os::raw::{c_char, c_long}; use std::sync::Arc; use style::computed_values::font_stretch::T as FontStretch; use style::computed_values::font_weight::T as FontWeight; use super::c_str_to_string; use text::glyph::GlyphId; use text::util::fixed_to_float; // This constant is not present in the freetype // bindings due to bindgen not handling the way // the macro is defined. const FT_LOAD_TARGET_LIGHT: FT_Int32 = 1 << 16; // Default to slight hinting, which is what most // Linux distros use by default, and is a better // default than no hinting. // TODO(gw): Make this configurable. const GLYPH_LOAD_FLAGS: FT_Int32 = FT_LOAD_TARGET_LIGHT; fn fixed_to_float_ft(f: i32) -> f64 { fixed_to_float(6, f) } #[derive(Debug)] pub struct FontTable { buffer: Vec<u8>, } impl FontTableMethods for FontTable { fn buffer(&self) -> &[u8] { &self.buffer } } /// Data from the OS/2 table of an OpenType font. /// See https://www.microsoft.com/typography/otspec/os2.htm #[derive(Debug)] struct OS2Table { us_weight_class: u16, us_width_class: u16, y_strikeout_size: i16, y_strikeout_position: i16, sx_height: i16, } #[derive(Debug)] pub struct FontHandle { // The font binary. This must stay valid for the lifetime of the font, // if the font is created using FT_Memory_Face. font_data: Arc<FontTemplateData>, face: FT_Face, handle: FontContextHandle, can_do_fast_shaping: bool, } impl Drop for FontHandle { fn drop(&mut self) { assert!(!self.face.is_null()); unsafe { if!FT_Done_Face(self.face).succeeded() { panic!("FT_Done_Face failed"); } } } } impl FontHandleMethods for FontHandle { fn new_from_template(fctx: &FontContextHandle, template: Arc<FontTemplateData>, pt_size: Option<Au>) -> Result<FontHandle, ()> { let ft_ctx: FT_Library = fctx.ctx.ctx; if ft_ctx.is_null() { return Err(()); } return create_face_from_buffer(ft_ctx, &template.bytes, pt_size).map(|face| { let mut handle = FontHandle { face: face, font_data: template.clone(), handle: fctx.clone(), can_do_fast_shaping: false, }; // TODO (#11310): Implement basic support for GPOS and GSUB. handle.can_do_fast_shaping = handle.has_table(KERN) && !handle.has_table(GPOS) && !handle.has_table(GSUB); handle }); fn create_face_from_buffer(lib: FT_Library, buffer: &[u8], pt_size: Option<Au>) -> Result<FT_Face, ()> { unsafe { let mut face: FT_Face = ptr::null_mut(); let face_index = 0 as FT_Long; let result = FT_New_Memory_Face(lib, buffer.as_ptr(), buffer.len() as FT_Long, face_index, &mut face); if!result.succeeded() || face.is_null() { return Err(()); } if let Some(s) = pt_size { FontHandle::set_char_size(face, s).or(Err(()))? } Ok(face) } } } fn template(&self) -> Arc<FontTemplateData> { self.font_data.clone() } fn family_name(&self) -> String { unsafe { c_str_to_string((*self.face).family_name as *const c_char) } } fn face_name(&self) -> Option<String> { unsafe { let name = FT_Get_Postscript_Name(self.face) as *const c_char; if!name.is_null() { Some(c_str_to_string(name)) } else { None } } } fn is_italic(&self) -> bool { unsafe { (*self.face).style_flags & FT_STYLE_FLAG_ITALIC as c_long!= 0 } } fn boldness(&self) -> FontWeight { if let Some(os2) = self.os2_table() { let weight = os2.us_weight_class as i32; if weight < 10 { FontWeight::from_int(weight * 100).unwrap() } else if weight >= 100 && weight < 1000 { FontWeight::from_int(weight / 100 * 100).unwrap() } else { FontWeight::normal() } } else { FontWeight::normal() } } fn stretchiness(&self) -> FontStretch { if let Some(os2) = self.os2_table() { match os2.us_width_class { 1 => FontStretch::UltraCondensed, 2 => FontStretch::ExtraCondensed, 3 => FontStretch::Condensed, 4 => FontStretch::SemiCondensed, 5 => FontStretch::Normal, 6 => FontStretch::SemiExpanded, 7 => FontStretch::Expanded, 8 => FontStretch::ExtraExpanded, 9 => FontStretch::UltraExpanded, _ => FontStretch::Normal } } else { FontStretch::Normal } } fn glyph_index(&self, codepoint: char) -> Option<GlyphId> { assert!(!self.face.is_null()); unsafe { let idx = FT_Get_Char_Index(self.face, codepoint as FT_ULong); if idx!= 0 as FT_UInt { Some(idx as GlyphId) } else { debug!("Invalid codepoint: {}", codepoint); None } } } fn glyph_h_kerning(&self, first_glyph: GlyphId, second_glyph: GlyphId) -> FractionalPixel { assert!(!self.face.is_null()); let mut delta = FT_Vector { x: 0, y: 0 }; unsafe { FT_Get_Kerning(self.face, first_glyph, second_glyph, FT_Kerning_Mode::FT_KERNING_DEFAULT as FT_UInt, &mut delta); } fixed_to_float_ft(delta.x as i32) } fn can_do_fast_shaping(&self) -> bool { self.can_do_fast_shaping } fn glyph_h_advance(&self, glyph: GlyphId) -> Option<FractionalPixel> { assert!(!self.face.is_null()); unsafe { let res = FT_Load_Glyph(self.face, glyph as FT_UInt, GLYPH_LOAD_FLAGS); if res.succeeded() { let void_glyph = (*self.face).glyph; let slot: FT_GlyphSlot = mem::transmute(void_glyph); assert!(!slot.is_null()); let advance = (*slot).metrics.horiAdvance; debug!("h_advance for {} is {}", glyph, advance); let advance = advance as i32; Some(fixed_to_float_ft(advance) as FractionalPixel) } else { debug!("Unable to load glyph {}. reason: {:?}", glyph, res); None } } } fn
(&self) -> FontMetrics { /* TODO(Issue #76): complete me */ let face = self.face_rec_mut(); let underline_size = self.font_units_to_au(face.underline_thickness as f64); let underline_offset = self.font_units_to_au(face.underline_position as f64); let em_size = self.font_units_to_au(face.units_per_EM as f64); let ascent = self.font_units_to_au(face.ascender as f64); let descent = self.font_units_to_au(face.descender as f64); let max_advance = self.font_units_to_au(face.max_advance_width as f64); // 'leading' is supposed to be the vertical distance between two baselines, // reflected by the height attribute in freetype. On OS X (w/ CTFont), // leading represents the distance between the bottom of a line descent to // the top of the next line's ascent or: (line_height - ascent - descent), // see http://stackoverflow.com/a/5635981 for CTFont implementation. // Convert using a formula similar to what CTFont returns for consistency. let height = self.font_units_to_au(face.height as f64); let leading = height - (ascent + descent); let mut strikeout_size = Au(0); let mut strikeout_offset = Au(0); let mut x_height = Au(0); if let Some(os2) = self.os2_table() { strikeout_size = self.font_units_to_au(os2.y_strikeout_size as f64); strikeout_offset = self.font_units_to_au(os2.y_strikeout_position as f64); x_height = self.font_units_to_au(os2.sx_height as f64); } let average_advance = self.glyph_index('0') .and_then(|idx| self.glyph_h_advance(idx)) .map_or(max_advance, |advance| self.font_units_to_au(advance)); let metrics = FontMetrics { underline_size: underline_size, underline_offset: underline_offset, strikeout_size: strikeout_size, strikeout_offset: strikeout_offset, leading: leading, x_height: x_height, em_size: em_size, ascent: ascent, descent: -descent, // linux font's seem to use the opposite sign from mac max_advance: max_advance, average_advance: average_advance, line_gap: height, }; debug!("Font metrics (@{}px): {:?}", em_size.to_f32_px(), metrics); metrics } fn table_for_tag(&self, tag: FontTableTag) -> Option<FontTable> { let tag = tag as FT_ULong; unsafe { // Get the length let mut len = 0; if!FT_Load_Sfnt_Table(self.face, tag, 0, ptr::null_mut(), &mut len).succeeded() { return None } // Get the bytes let mut buf = vec![0u8; len as usize]; if!FT_Load_Sfnt_Table(self.face, tag, 0, buf.as_mut_ptr(), &mut len).succeeded() { return None } Some(FontTable { buffer: buf }) } } fn identifier(&self) -> Atom { self.font_data.identifier.clone() } } impl<'a> FontHandle { fn set_char_size(face: FT_Face, pt_size: Au) -> Result<(), ()>{ let char_size = pt_size.to_f64_px() * 64.0 + 0.5; unsafe { let result = FT_Set_Char_Size(face, char_size as FT_F26Dot6, 0, 0, 0); if result.succeeded() { Ok(()) } else { Err(()) } } } fn has_table(&self, tag: FontTableTag) -> bool { unsafe { FT_Load_Sfnt_Table(self.face, tag as FT_ULong, 0, ptr::null_mut(), &mut 0).succeeded() } } fn face_rec_mut(&'a self) -> &'a mut FT_FaceRec { unsafe { &mut (*self.face) } } fn font_units_to_au(&self, value: f64) -> Au { let face = self.face_rec_mut(); // face.size is a *c_void in the bindings, presumably to avoid // recursive structural types let size: &FT_SizeRec = unsafe { mem::transmute(&(*face.size)) }; let metrics: &FT_Size_Metrics = &(*size).metrics; let em_size = face.units_per_EM as f64; let x_scale = (metrics.x_ppem as f64) / em_size as f64; // If this isn't true then we're scaling one of the axes wrong assert_eq!(metrics.x_ppem, metrics.y_ppem); Au::from_f64_px(value * x_scale) } fn os2_table(&self) -> Option<OS2Table> { unsafe { let os2 = FT_Get_Sfnt_Table(self.face_rec_mut(), FT_Sfnt_Tag::FT_SFNT_OS2) as *mut TT_OS2; let valid =!os2.is_null() && (*os2).version!= 0xffff; if!valid { return None } Some(OS2Table { us_weight_class: (*os2).usWeightClass, us_width_class: (*os2).usWidthClass, y_strikeout_size: (*os2).yStrikeoutSize, y_strikeout_position: (*os2).yStrikeoutPosition, sx_height: (*os2).sxHeight, }) } } }
metrics
identifier_name
font.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ use app_units::Au; use font::{FontHandleMethods, FontMetrics, FontTableMethods}; use font::{FontTableTag, FractionalPixel, GPOS, GSUB, KERN}; use freetype::freetype::{FT_Done_Face, FT_New_Memory_Face}; use freetype::freetype::{FT_F26Dot6, FT_Face, FT_FaceRec}; use freetype::freetype::{FT_Get_Char_Index, FT_Get_Postscript_Name}; use freetype::freetype::{FT_Get_Kerning, FT_Get_Sfnt_Table, FT_Load_Sfnt_Table}; use freetype::freetype::{FT_GlyphSlot, FT_Library, FT_Long, FT_ULong}; use freetype::freetype::{FT_Int32, FT_Kerning_Mode, FT_STYLE_FLAG_ITALIC}; use freetype::freetype::{FT_Load_Glyph, FT_Set_Char_Size};
use freetype::tt_os2::TT_OS2; use platform::font_context::FontContextHandle; use platform::font_template::FontTemplateData; use servo_atoms::Atom; use std::{mem, ptr}; use std::os::raw::{c_char, c_long}; use std::sync::Arc; use style::computed_values::font_stretch::T as FontStretch; use style::computed_values::font_weight::T as FontWeight; use super::c_str_to_string; use text::glyph::GlyphId; use text::util::fixed_to_float; // This constant is not present in the freetype // bindings due to bindgen not handling the way // the macro is defined. const FT_LOAD_TARGET_LIGHT: FT_Int32 = 1 << 16; // Default to slight hinting, which is what most // Linux distros use by default, and is a better // default than no hinting. // TODO(gw): Make this configurable. const GLYPH_LOAD_FLAGS: FT_Int32 = FT_LOAD_TARGET_LIGHT; fn fixed_to_float_ft(f: i32) -> f64 { fixed_to_float(6, f) } #[derive(Debug)] pub struct FontTable { buffer: Vec<u8>, } impl FontTableMethods for FontTable { fn buffer(&self) -> &[u8] { &self.buffer } } /// Data from the OS/2 table of an OpenType font. /// See https://www.microsoft.com/typography/otspec/os2.htm #[derive(Debug)] struct OS2Table { us_weight_class: u16, us_width_class: u16, y_strikeout_size: i16, y_strikeout_position: i16, sx_height: i16, } #[derive(Debug)] pub struct FontHandle { // The font binary. This must stay valid for the lifetime of the font, // if the font is created using FT_Memory_Face. font_data: Arc<FontTemplateData>, face: FT_Face, handle: FontContextHandle, can_do_fast_shaping: bool, } impl Drop for FontHandle { fn drop(&mut self) { assert!(!self.face.is_null()); unsafe { if!FT_Done_Face(self.face).succeeded() { panic!("FT_Done_Face failed"); } } } } impl FontHandleMethods for FontHandle { fn new_from_template(fctx: &FontContextHandle, template: Arc<FontTemplateData>, pt_size: Option<Au>) -> Result<FontHandle, ()> { let ft_ctx: FT_Library = fctx.ctx.ctx; if ft_ctx.is_null() { return Err(()); } return create_face_from_buffer(ft_ctx, &template.bytes, pt_size).map(|face| { let mut handle = FontHandle { face: face, font_data: template.clone(), handle: fctx.clone(), can_do_fast_shaping: false, }; // TODO (#11310): Implement basic support for GPOS and GSUB. handle.can_do_fast_shaping = handle.has_table(KERN) && !handle.has_table(GPOS) && !handle.has_table(GSUB); handle }); fn create_face_from_buffer(lib: FT_Library, buffer: &[u8], pt_size: Option<Au>) -> Result<FT_Face, ()> { unsafe { let mut face: FT_Face = ptr::null_mut(); let face_index = 0 as FT_Long; let result = FT_New_Memory_Face(lib, buffer.as_ptr(), buffer.len() as FT_Long, face_index, &mut face); if!result.succeeded() || face.is_null() { return Err(()); } if let Some(s) = pt_size { FontHandle::set_char_size(face, s).or(Err(()))? } Ok(face) } } } fn template(&self) -> Arc<FontTemplateData> { self.font_data.clone() } fn family_name(&self) -> String { unsafe { c_str_to_string((*self.face).family_name as *const c_char) } } fn face_name(&self) -> Option<String> { unsafe { let name = FT_Get_Postscript_Name(self.face) as *const c_char; if!name.is_null() { Some(c_str_to_string(name)) } else { None } } } fn is_italic(&self) -> bool { unsafe { (*self.face).style_flags & FT_STYLE_FLAG_ITALIC as c_long!= 0 } } fn boldness(&self) -> FontWeight { if let Some(os2) = self.os2_table() { let weight = os2.us_weight_class as i32; if weight < 10 { FontWeight::from_int(weight * 100).unwrap() } else if weight >= 100 && weight < 1000 { FontWeight::from_int(weight / 100 * 100).unwrap() } else { FontWeight::normal() } } else { FontWeight::normal() } } fn stretchiness(&self) -> FontStretch { if let Some(os2) = self.os2_table() { match os2.us_width_class { 1 => FontStretch::UltraCondensed, 2 => FontStretch::ExtraCondensed, 3 => FontStretch::Condensed, 4 => FontStretch::SemiCondensed, 5 => FontStretch::Normal, 6 => FontStretch::SemiExpanded, 7 => FontStretch::Expanded, 8 => FontStretch::ExtraExpanded, 9 => FontStretch::UltraExpanded, _ => FontStretch::Normal } } else { FontStretch::Normal } } fn glyph_index(&self, codepoint: char) -> Option<GlyphId> { assert!(!self.face.is_null()); unsafe { let idx = FT_Get_Char_Index(self.face, codepoint as FT_ULong); if idx!= 0 as FT_UInt { Some(idx as GlyphId) } else { debug!("Invalid codepoint: {}", codepoint); None } } } fn glyph_h_kerning(&self, first_glyph: GlyphId, second_glyph: GlyphId) -> FractionalPixel { assert!(!self.face.is_null()); let mut delta = FT_Vector { x: 0, y: 0 }; unsafe { FT_Get_Kerning(self.face, first_glyph, second_glyph, FT_Kerning_Mode::FT_KERNING_DEFAULT as FT_UInt, &mut delta); } fixed_to_float_ft(delta.x as i32) } fn can_do_fast_shaping(&self) -> bool { self.can_do_fast_shaping } fn glyph_h_advance(&self, glyph: GlyphId) -> Option<FractionalPixel> { assert!(!self.face.is_null()); unsafe { let res = FT_Load_Glyph(self.face, glyph as FT_UInt, GLYPH_LOAD_FLAGS); if res.succeeded() { let void_glyph = (*self.face).glyph; let slot: FT_GlyphSlot = mem::transmute(void_glyph); assert!(!slot.is_null()); let advance = (*slot).metrics.horiAdvance; debug!("h_advance for {} is {}", glyph, advance); let advance = advance as i32; Some(fixed_to_float_ft(advance) as FractionalPixel) } else { debug!("Unable to load glyph {}. reason: {:?}", glyph, res); None } } } fn metrics(&self) -> FontMetrics { /* TODO(Issue #76): complete me */ let face = self.face_rec_mut(); let underline_size = self.font_units_to_au(face.underline_thickness as f64); let underline_offset = self.font_units_to_au(face.underline_position as f64); let em_size = self.font_units_to_au(face.units_per_EM as f64); let ascent = self.font_units_to_au(face.ascender as f64); let descent = self.font_units_to_au(face.descender as f64); let max_advance = self.font_units_to_au(face.max_advance_width as f64); // 'leading' is supposed to be the vertical distance between two baselines, // reflected by the height attribute in freetype. On OS X (w/ CTFont), // leading represents the distance between the bottom of a line descent to // the top of the next line's ascent or: (line_height - ascent - descent), // see http://stackoverflow.com/a/5635981 for CTFont implementation. // Convert using a formula similar to what CTFont returns for consistency. let height = self.font_units_to_au(face.height as f64); let leading = height - (ascent + descent); let mut strikeout_size = Au(0); let mut strikeout_offset = Au(0); let mut x_height = Au(0); if let Some(os2) = self.os2_table() { strikeout_size = self.font_units_to_au(os2.y_strikeout_size as f64); strikeout_offset = self.font_units_to_au(os2.y_strikeout_position as f64); x_height = self.font_units_to_au(os2.sx_height as f64); } let average_advance = self.glyph_index('0') .and_then(|idx| self.glyph_h_advance(idx)) .map_or(max_advance, |advance| self.font_units_to_au(advance)); let metrics = FontMetrics { underline_size: underline_size, underline_offset: underline_offset, strikeout_size: strikeout_size, strikeout_offset: strikeout_offset, leading: leading, x_height: x_height, em_size: em_size, ascent: ascent, descent: -descent, // linux font's seem to use the opposite sign from mac max_advance: max_advance, average_advance: average_advance, line_gap: height, }; debug!("Font metrics (@{}px): {:?}", em_size.to_f32_px(), metrics); metrics } fn table_for_tag(&self, tag: FontTableTag) -> Option<FontTable> { let tag = tag as FT_ULong; unsafe { // Get the length let mut len = 0; if!FT_Load_Sfnt_Table(self.face, tag, 0, ptr::null_mut(), &mut len).succeeded() { return None } // Get the bytes let mut buf = vec![0u8; len as usize]; if!FT_Load_Sfnt_Table(self.face, tag, 0, buf.as_mut_ptr(), &mut len).succeeded() { return None } Some(FontTable { buffer: buf }) } } fn identifier(&self) -> Atom { self.font_data.identifier.clone() } } impl<'a> FontHandle { fn set_char_size(face: FT_Face, pt_size: Au) -> Result<(), ()>{ let char_size = pt_size.to_f64_px() * 64.0 + 0.5; unsafe { let result = FT_Set_Char_Size(face, char_size as FT_F26Dot6, 0, 0, 0); if result.succeeded() { Ok(()) } else { Err(()) } } } fn has_table(&self, tag: FontTableTag) -> bool { unsafe { FT_Load_Sfnt_Table(self.face, tag as FT_ULong, 0, ptr::null_mut(), &mut 0).succeeded() } } fn face_rec_mut(&'a self) -> &'a mut FT_FaceRec { unsafe { &mut (*self.face) } } fn font_units_to_au(&self, value: f64) -> Au { let face = self.face_rec_mut(); // face.size is a *c_void in the bindings, presumably to avoid // recursive structural types let size: &FT_SizeRec = unsafe { mem::transmute(&(*face.size)) }; let metrics: &FT_Size_Metrics = &(*size).metrics; let em_size = face.units_per_EM as f64; let x_scale = (metrics.x_ppem as f64) / em_size as f64; // If this isn't true then we're scaling one of the axes wrong assert_eq!(metrics.x_ppem, metrics.y_ppem); Au::from_f64_px(value * x_scale) } fn os2_table(&self) -> Option<OS2Table> { unsafe { let os2 = FT_Get_Sfnt_Table(self.face_rec_mut(), FT_Sfnt_Tag::FT_SFNT_OS2) as *mut TT_OS2; let valid =!os2.is_null() && (*os2).version!= 0xffff; if!valid { return None } Some(OS2Table { us_weight_class: (*os2).usWeightClass, us_width_class: (*os2).usWidthClass, y_strikeout_size: (*os2).yStrikeoutSize, y_strikeout_position: (*os2).yStrikeoutPosition, sx_height: (*os2).sxHeight, }) } } }
use freetype::freetype::{FT_SizeRec, FT_Size_Metrics, FT_UInt, FT_Vector}; use freetype::freetype::FT_Sfnt_Tag;
random_line_split
issue-25757.rs
// Copyright 2015 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. // run-pass struct Foo { a: u32 } impl Foo { fn
(&mut self) { self.a = 5; } } const FUNC: &'static Fn(&mut Foo) -> () = &Foo::x; fn main() { let mut foo = Foo { a: 137 }; FUNC(&mut foo); assert_eq!(foo.a, 5); }
x
identifier_name
issue-25757.rs
// Copyright 2015 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
a: u32 } impl Foo { fn x(&mut self) { self.a = 5; } } const FUNC: &'static Fn(&mut Foo) -> () = &Foo::x; fn main() { let mut foo = Foo { a: 137 }; FUNC(&mut foo); assert_eq!(foo.a, 5); }
// option. This file may not be copied, modified, or distributed // except according to those terms. // run-pass struct Foo {
random_line_split
error.rs
// // imag - the personal information management suite for the commandline // Copyright (C) 2015, 2016 Matthias Beyer <[email protected]> and contributors // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public // License as published by the Free Software Foundation; version // 2.1 of the License. // // This library 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 // Lesser General Public License for more details. // // You should have received a copy of the GNU Lesser General Public // License along with this library; if not, write to the Free Software // Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA //
error_chain! { types { EntryUtilError, EntryUtilErrorKind, ResultExt, Result; } foreign_links { TomlQueryError(::toml_query::error::Error); } errors { } }
random_line_split
empty-allocation-non-null.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. // FIXME (#22405): Replace `Box::new` with `box` here when/if possible. pub fn main() { assert!(Some(Box::new(())).is_some()); let xs: Box<[()]> = Box::<[(); 0]>::new([]); assert!(Some(xs).is_some());
struct Foo; assert!(Some(Box::new(Foo)).is_some()); let ys: Box<[Foo]> = Box::<[Foo; 0]>::new([]); assert!(Some(ys).is_some()); }
random_line_split
empty-allocation-non-null.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. // FIXME (#22405): Replace `Box::new` with `box` here when/if possible. pub fn main() { assert!(Some(Box::new(())).is_some()); let xs: Box<[()]> = Box::<[(); 0]>::new([]); assert!(Some(xs).is_some()); struct
; assert!(Some(Box::new(Foo)).is_some()); let ys: Box<[Foo]> = Box::<[Foo; 0]>::new([]); assert!(Some(ys).is_some()); }
Foo
identifier_name
method.rs
//! The HTTP request method use std::fmt; use std::str::FromStr; use std::convert::AsRef; use error::Error; use self::Method::{Options, Get, Post, Put, Delete, Head, Trace, Connect, Patch, Extension}; #[cfg(feature = "serde-serialization")] use serde::{Deserialize, Deserializer, Serialize, Serializer}; /// The Request Method (VERB) /// /// Currently includes 8 variants representing the 8 methods defined in /// [RFC 7230](https://tools.ietf.org/html/rfc7231#section-4.1), plus PATCH, /// and an Extension variant for all extensions. /// /// It may make sense to grow this to include all variants currently /// registered with IANA, if they are at all common to use. #[derive(Clone, PartialEq, Eq, Hash, Debug)] pub enum Method { /// OPTIONS Options, /// GET Get, /// POST Post, /// PUT Put, /// DELETE Delete, /// HEAD Head, /// TRACE Trace, /// CONNECT Connect, /// PATCH Patch, /// Method extensions. An example would be `let m = Extension("FOO".to_string())`. Extension(String) } impl AsRef<str> for Method { fn as_ref(&self) -> &str { match *self { Options => "OPTIONS", Get => "GET", Post => "POST", Put => "PUT", Delete => "DELETE", Head => "HEAD", Trace => "TRACE", Connect => "CONNECT", Patch => "PATCH", Extension(ref s) => s.as_ref() } } } impl Method { /// Whether a method is considered "safe", meaning the request is /// essentially read-only. /// /// See [the spec](https://tools.ietf.org/html/rfc7231#section-4.2.1) /// for more words. pub fn safe(&self) -> bool { match *self { Get | Head | Options | Trace => true, _ => false } } /// Whether a method is considered "idempotent", meaning the request has /// the same result is executed multiple times. /// /// See [the spec](https://tools.ietf.org/html/rfc7231#section-4.2.2) for /// more words. pub fn idempotent(&self) -> bool { if self.safe() { true } else { match *self { Put | Delete => true, _ => false } } } } impl FromStr for Method { type Err = Error; fn from_str(s: &str) -> Result<Method, Error> { if s == "" { Err(Error::Method) } else { Ok(match s { "OPTIONS" => Options, "GET" => Get, "POST" => Post, "PUT" => Put, "DELETE" => Delete, "HEAD" => Head, "TRACE" => Trace, "CONNECT" => Connect, "PATCH" => Patch, _ => Extension(s.to_owned()) }) } } } impl fmt::Display for Method { fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result
} #[cfg(feature = "serde-serialization")] impl Serialize for Method { fn serialize<S>(&self, serializer: &mut S) -> Result<(), S::Error> where S: Serializer { format!("{}", self).serialize(serializer) } } #[cfg(feature = "serde-serialization")] impl Deserialize for Method { fn deserialize<D>(deserializer: &mut D) -> Result<Method, D::Error> where D: Deserializer { let string_representation: String = try!(Deserialize::deserialize(deserializer)); Ok(FromStr::from_str(&string_representation[..]).unwrap()) } } #[cfg(test)] mod tests { use std::collections::HashMap; use std::str::FromStr; use error::Error; use super::Method; use super::Method::{Get, Post, Put, Extension}; #[test] fn test_safe() { assert_eq!(true, Get.safe()); assert_eq!(false, Post.safe()); } #[test] fn test_idempotent() { assert_eq!(true, Get.idempotent()); assert_eq!(true, Put.idempotent()); assert_eq!(false, Post.idempotent()); } #[test] fn test_from_str() { assert_eq!(Get, FromStr::from_str("GET").unwrap()); assert_eq!(Extension("MOVE".to_owned()), FromStr::from_str("MOVE").unwrap()); let x: Result<Method, _> = FromStr::from_str(""); if let Err(Error::Method) = x { } else { panic!("An empty method is invalid!") } } #[test] fn test_fmt() { assert_eq!("GET".to_owned(), format!("{}", Get)); assert_eq!("MOVE".to_owned(), format!("{}", Extension("MOVE".to_owned()))); } #[test] fn test_hashable() { let mut counter: HashMap<Method,usize> = HashMap::new(); counter.insert(Get, 1); assert_eq!(Some(&1), counter.get(&Get)); } #[test] fn test_as_str() { assert_eq!(Get.as_ref(), "GET"); assert_eq!(Post.as_ref(), "POST"); assert_eq!(Put.as_ref(), "PUT"); assert_eq!(Extension("MOVE".to_owned()).as_ref(), "MOVE"); } }
{ fmt.write_str(match *self { Options => "OPTIONS", Get => "GET", Post => "POST", Put => "PUT", Delete => "DELETE", Head => "HEAD", Trace => "TRACE", Connect => "CONNECT", Patch => "PATCH", Extension(ref s) => s.as_ref() }) }
identifier_body
method.rs
//! The HTTP request method use std::fmt; use std::str::FromStr; use std::convert::AsRef; use error::Error; use self::Method::{Options, Get, Post, Put, Delete, Head, Trace, Connect, Patch, Extension}; #[cfg(feature = "serde-serialization")] use serde::{Deserialize, Deserializer, Serialize, Serializer}; /// The Request Method (VERB) /// /// Currently includes 8 variants representing the 8 methods defined in /// [RFC 7230](https://tools.ietf.org/html/rfc7231#section-4.1), plus PATCH, /// and an Extension variant for all extensions. /// /// It may make sense to grow this to include all variants currently /// registered with IANA, if they are at all common to use. #[derive(Clone, PartialEq, Eq, Hash, Debug)] pub enum Method { /// OPTIONS Options, /// GET Get, /// POST Post, /// PUT Put, /// DELETE Delete, /// HEAD Head, /// TRACE Trace, /// CONNECT Connect, /// PATCH Patch, /// Method extensions. An example would be `let m = Extension("FOO".to_string())`. Extension(String) } impl AsRef<str> for Method { fn as_ref(&self) -> &str { match *self { Options => "OPTIONS", Get => "GET", Post => "POST", Put => "PUT", Delete => "DELETE", Head => "HEAD", Trace => "TRACE", Connect => "CONNECT", Patch => "PATCH", Extension(ref s) => s.as_ref() } } } impl Method { /// Whether a method is considered "safe", meaning the request is /// essentially read-only. /// /// See [the spec](https://tools.ietf.org/html/rfc7231#section-4.2.1) /// for more words. pub fn safe(&self) -> bool { match *self { Get | Head | Options | Trace => true, _ => false } } /// Whether a method is considered "idempotent", meaning the request has /// the same result is executed multiple times. /// /// See [the spec](https://tools.ietf.org/html/rfc7231#section-4.2.2) for /// more words. pub fn idempotent(&self) -> bool { if self.safe() { true } else { match *self { Put | Delete => true, _ => false } } } } impl FromStr for Method { type Err = Error; fn from_str(s: &str) -> Result<Method, Error> { if s == "" { Err(Error::Method) } else { Ok(match s { "OPTIONS" => Options, "GET" => Get, "POST" => Post, "PUT" => Put, "DELETE" => Delete, "HEAD" => Head, "TRACE" => Trace, "CONNECT" => Connect, "PATCH" => Patch, _ => Extension(s.to_owned()) }) } } } impl fmt::Display for Method { fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result { fmt.write_str(match *self { Options => "OPTIONS", Get => "GET", Post => "POST", Put => "PUT", Delete => "DELETE", Head => "HEAD", Trace => "TRACE", Connect => "CONNECT", Patch => "PATCH", Extension(ref s) => s.as_ref() }) } } #[cfg(feature = "serde-serialization")] impl Serialize for Method { fn serialize<S>(&self, serializer: &mut S) -> Result<(), S::Error> where S: Serializer { format!("{}", self).serialize(serializer) } } #[cfg(feature = "serde-serialization")] impl Deserialize for Method {
} #[cfg(test)] mod tests { use std::collections::HashMap; use std::str::FromStr; use error::Error; use super::Method; use super::Method::{Get, Post, Put, Extension}; #[test] fn test_safe() { assert_eq!(true, Get.safe()); assert_eq!(false, Post.safe()); } #[test] fn test_idempotent() { assert_eq!(true, Get.idempotent()); assert_eq!(true, Put.idempotent()); assert_eq!(false, Post.idempotent()); } #[test] fn test_from_str() { assert_eq!(Get, FromStr::from_str("GET").unwrap()); assert_eq!(Extension("MOVE".to_owned()), FromStr::from_str("MOVE").unwrap()); let x: Result<Method, _> = FromStr::from_str(""); if let Err(Error::Method) = x { } else { panic!("An empty method is invalid!") } } #[test] fn test_fmt() { assert_eq!("GET".to_owned(), format!("{}", Get)); assert_eq!("MOVE".to_owned(), format!("{}", Extension("MOVE".to_owned()))); } #[test] fn test_hashable() { let mut counter: HashMap<Method,usize> = HashMap::new(); counter.insert(Get, 1); assert_eq!(Some(&1), counter.get(&Get)); } #[test] fn test_as_str() { assert_eq!(Get.as_ref(), "GET"); assert_eq!(Post.as_ref(), "POST"); assert_eq!(Put.as_ref(), "PUT"); assert_eq!(Extension("MOVE".to_owned()).as_ref(), "MOVE"); } }
fn deserialize<D>(deserializer: &mut D) -> Result<Method, D::Error> where D: Deserializer { let string_representation: String = try!(Deserialize::deserialize(deserializer)); Ok(FromStr::from_str(&string_representation[..]).unwrap()) }
random_line_split
method.rs
//! The HTTP request method use std::fmt; use std::str::FromStr; use std::convert::AsRef; use error::Error; use self::Method::{Options, Get, Post, Put, Delete, Head, Trace, Connect, Patch, Extension}; #[cfg(feature = "serde-serialization")] use serde::{Deserialize, Deserializer, Serialize, Serializer}; /// The Request Method (VERB) /// /// Currently includes 8 variants representing the 8 methods defined in /// [RFC 7230](https://tools.ietf.org/html/rfc7231#section-4.1), plus PATCH, /// and an Extension variant for all extensions. /// /// It may make sense to grow this to include all variants currently /// registered with IANA, if they are at all common to use. #[derive(Clone, PartialEq, Eq, Hash, Debug)] pub enum Method { /// OPTIONS Options, /// GET Get, /// POST Post, /// PUT Put, /// DELETE Delete, /// HEAD Head, /// TRACE Trace, /// CONNECT Connect, /// PATCH Patch, /// Method extensions. An example would be `let m = Extension("FOO".to_string())`. Extension(String) } impl AsRef<str> for Method { fn as_ref(&self) -> &str { match *self { Options => "OPTIONS", Get => "GET", Post => "POST", Put => "PUT", Delete => "DELETE", Head => "HEAD", Trace => "TRACE", Connect => "CONNECT", Patch => "PATCH", Extension(ref s) => s.as_ref() } } } impl Method { /// Whether a method is considered "safe", meaning the request is /// essentially read-only. /// /// See [the spec](https://tools.ietf.org/html/rfc7231#section-4.2.1) /// for more words. pub fn safe(&self) -> bool { match *self { Get | Head | Options | Trace => true, _ => false } } /// Whether a method is considered "idempotent", meaning the request has /// the same result is executed multiple times. /// /// See [the spec](https://tools.ietf.org/html/rfc7231#section-4.2.2) for /// more words. pub fn idempotent(&self) -> bool { if self.safe() { true } else { match *self { Put | Delete => true, _ => false } } } } impl FromStr for Method { type Err = Error; fn from_str(s: &str) -> Result<Method, Error> { if s == "" { Err(Error::Method) } else { Ok(match s { "OPTIONS" => Options, "GET" => Get, "POST" => Post, "PUT" => Put, "DELETE" => Delete, "HEAD" => Head, "TRACE" => Trace, "CONNECT" => Connect, "PATCH" => Patch, _ => Extension(s.to_owned()) }) } } } impl fmt::Display for Method { fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result { fmt.write_str(match *self { Options => "OPTIONS", Get => "GET", Post => "POST", Put => "PUT", Delete => "DELETE", Head => "HEAD", Trace => "TRACE", Connect => "CONNECT", Patch => "PATCH", Extension(ref s) => s.as_ref() }) } } #[cfg(feature = "serde-serialization")] impl Serialize for Method { fn serialize<S>(&self, serializer: &mut S) -> Result<(), S::Error> where S: Serializer { format!("{}", self).serialize(serializer) } } #[cfg(feature = "serde-serialization")] impl Deserialize for Method { fn deserialize<D>(deserializer: &mut D) -> Result<Method, D::Error> where D: Deserializer { let string_representation: String = try!(Deserialize::deserialize(deserializer)); Ok(FromStr::from_str(&string_representation[..]).unwrap()) } } #[cfg(test)] mod tests { use std::collections::HashMap; use std::str::FromStr; use error::Error; use super::Method; use super::Method::{Get, Post, Put, Extension}; #[test] fn test_safe() { assert_eq!(true, Get.safe()); assert_eq!(false, Post.safe()); } #[test] fn
() { assert_eq!(true, Get.idempotent()); assert_eq!(true, Put.idempotent()); assert_eq!(false, Post.idempotent()); } #[test] fn test_from_str() { assert_eq!(Get, FromStr::from_str("GET").unwrap()); assert_eq!(Extension("MOVE".to_owned()), FromStr::from_str("MOVE").unwrap()); let x: Result<Method, _> = FromStr::from_str(""); if let Err(Error::Method) = x { } else { panic!("An empty method is invalid!") } } #[test] fn test_fmt() { assert_eq!("GET".to_owned(), format!("{}", Get)); assert_eq!("MOVE".to_owned(), format!("{}", Extension("MOVE".to_owned()))); } #[test] fn test_hashable() { let mut counter: HashMap<Method,usize> = HashMap::new(); counter.insert(Get, 1); assert_eq!(Some(&1), counter.get(&Get)); } #[test] fn test_as_str() { assert_eq!(Get.as_ref(), "GET"); assert_eq!(Post.as_ref(), "POST"); assert_eq!(Put.as_ref(), "PUT"); assert_eq!(Extension("MOVE".to_owned()).as_ref(), "MOVE"); } }
test_idempotent
identifier_name
unique-vec-res.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. #![feature(unsafe_destructor)] use std::cell::Cell; #[deriving(Show)] struct r<'a> { i: &'a Cell<int>, } #[unsafe_destructor] impl<'a> Drop for r<'a> { fn drop(&mut self) { unsafe { self.i.set(self.i.get() + 1); } } } fn f<T>(_i: Vec<T>, _j: Vec<T> ) { } fn clone<T: Clone>(t: &T) -> T { t.clone() } fn main()
{ let i1 = &Cell::new(0); let i2 = &Cell::new(1); let r1 = vec!(box r { i: i1 }); let r2 = vec!(box r { i: i2 }); f(clone(&r1), clone(&r2)); //~^ ERROR the trait `core::clone::Clone` is not implemented for the type //~^^ ERROR the trait `core::clone::Clone` is not implemented for the type println!("{}", (r2, i1.get())); println!("{}", (r1, i2.get())); }
identifier_body
unique-vec-res.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. #![feature(unsafe_destructor)] use std::cell::Cell; #[deriving(Show)] struct r<'a> { i: &'a Cell<int>, } #[unsafe_destructor] impl<'a> Drop for r<'a> { fn drop(&mut self) { unsafe { self.i.set(self.i.get() + 1); } } } fn f<T>(_i: Vec<T>, _j: Vec<T> ) { } fn clone<T: Clone>(t: &T) -> T { t.clone() } fn main() {
let r2 = vec!(box r { i: i2 }); f(clone(&r1), clone(&r2)); //~^ ERROR the trait `core::clone::Clone` is not implemented for the type //~^^ ERROR the trait `core::clone::Clone` is not implemented for the type println!("{}", (r2, i1.get())); println!("{}", (r1, i2.get())); }
let i1 = &Cell::new(0); let i2 = &Cell::new(1); let r1 = vec!(box r { i: i1 });
random_line_split
unique-vec-res.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. #![feature(unsafe_destructor)] use std::cell::Cell; #[deriving(Show)] struct r<'a> { i: &'a Cell<int>, } #[unsafe_destructor] impl<'a> Drop for r<'a> { fn drop(&mut self) { unsafe { self.i.set(self.i.get() + 1); } } } fn
<T>(_i: Vec<T>, _j: Vec<T> ) { } fn clone<T: Clone>(t: &T) -> T { t.clone() } fn main() { let i1 = &Cell::new(0); let i2 = &Cell::new(1); let r1 = vec!(box r { i: i1 }); let r2 = vec!(box r { i: i2 }); f(clone(&r1), clone(&r2)); //~^ ERROR the trait `core::clone::Clone` is not implemented for the type //~^^ ERROR the trait `core::clone::Clone` is not implemented for the type println!("{}", (r2, i1.get())); println!("{}", (r1, i2.get())); }
f
identifier_name
quickchecks.rs
extern crate editdistancewf as wf; extern crate quickcheck; use quickcheck::quickcheck; #[test] fn at_least_size_difference_property()
#[test] fn at_most_length_of_longer_property() { fn at_most_size_of_longer(a: String, b: String) -> bool { let upper_bound = *[a.chars().count(), b.chars().count()] .iter() .max() .unwrap() as usize; wf::distance(a.chars(), b.chars()) <= upper_bound } quickcheck(at_most_size_of_longer as fn(a: String, b: String) -> bool); } #[test] fn zero_iff_a_equals_b_property() { fn zero_iff_a_equals_b(a: String, b: String) -> bool { let d = wf::distance(a.chars(), b.chars()); if a == b { d == 0 } else { d > 0 } } quickcheck(zero_iff_a_equals_b as fn(a: String, b: String) -> bool); } #[test] fn triangle_inequality_property() { fn triangle_inequality(a: String, b: String, c: String) -> bool { wf::distance(a.chars(), b.chars()) <= wf::distance(a.chars(), c.chars()) + wf::distance(b.chars(), c.chars()) } quickcheck(triangle_inequality as fn(a: String, b: String, c: String) -> bool); }
{ fn at_least_size_difference(a: String, b: String) -> bool { let size_a = a.chars().count() as isize; let size_b = b.chars().count() as isize; let diff = (size_a - size_b).abs() as usize; wf::distance(a.chars(), b.chars()) >= diff } quickcheck(at_least_size_difference as fn(a: String, b: String) -> bool); }
identifier_body
quickchecks.rs
extern crate editdistancewf as wf; extern crate quickcheck; use quickcheck::quickcheck; #[test] fn at_least_size_difference_property() { fn at_least_size_difference(a: String, b: String) -> bool { let size_a = a.chars().count() as isize; let size_b = b.chars().count() as isize; let diff = (size_a - size_b).abs() as usize; wf::distance(a.chars(), b.chars()) >= diff } quickcheck(at_least_size_difference as fn(a: String, b: String) -> bool); } #[test] fn at_most_length_of_longer_property() { fn at_most_size_of_longer(a: String, b: String) -> bool { let upper_bound = *[a.chars().count(), b.chars().count()] .iter() .max() .unwrap() as usize; wf::distance(a.chars(), b.chars()) <= upper_bound } quickcheck(at_most_size_of_longer as fn(a: String, b: String) -> bool); } #[test] fn zero_iff_a_equals_b_property() { fn zero_iff_a_equals_b(a: String, b: String) -> bool { let d = wf::distance(a.chars(), b.chars()); if a == b
else { d > 0 } } quickcheck(zero_iff_a_equals_b as fn(a: String, b: String) -> bool); } #[test] fn triangle_inequality_property() { fn triangle_inequality(a: String, b: String, c: String) -> bool { wf::distance(a.chars(), b.chars()) <= wf::distance(a.chars(), c.chars()) + wf::distance(b.chars(), c.chars()) } quickcheck(triangle_inequality as fn(a: String, b: String, c: String) -> bool); }
{ d == 0 }
conditional_block
quickchecks.rs
extern crate editdistancewf as wf; extern crate quickcheck; use quickcheck::quickcheck; #[test] fn
() { fn at_least_size_difference(a: String, b: String) -> bool { let size_a = a.chars().count() as isize; let size_b = b.chars().count() as isize; let diff = (size_a - size_b).abs() as usize; wf::distance(a.chars(), b.chars()) >= diff } quickcheck(at_least_size_difference as fn(a: String, b: String) -> bool); } #[test] fn at_most_length_of_longer_property() { fn at_most_size_of_longer(a: String, b: String) -> bool { let upper_bound = *[a.chars().count(), b.chars().count()] .iter() .max() .unwrap() as usize; wf::distance(a.chars(), b.chars()) <= upper_bound } quickcheck(at_most_size_of_longer as fn(a: String, b: String) -> bool); } #[test] fn zero_iff_a_equals_b_property() { fn zero_iff_a_equals_b(a: String, b: String) -> bool { let d = wf::distance(a.chars(), b.chars()); if a == b { d == 0 } else { d > 0 } } quickcheck(zero_iff_a_equals_b as fn(a: String, b: String) -> bool); } #[test] fn triangle_inequality_property() { fn triangle_inequality(a: String, b: String, c: String) -> bool { wf::distance(a.chars(), b.chars()) <= wf::distance(a.chars(), c.chars()) + wf::distance(b.chars(), c.chars()) } quickcheck(triangle_inequality as fn(a: String, b: String, c: String) -> bool); }
at_least_size_difference_property
identifier_name
quickchecks.rs
extern crate editdistancewf as wf; extern crate quickcheck; use quickcheck::quickcheck; #[test] fn at_least_size_difference_property() { fn at_least_size_difference(a: String, b: String) -> bool { let size_a = a.chars().count() as isize; let size_b = b.chars().count() as isize; let diff = (size_a - size_b).abs() as usize; wf::distance(a.chars(), b.chars()) >= diff } quickcheck(at_least_size_difference as fn(a: String, b: String) -> bool); } #[test] fn at_most_length_of_longer_property() { fn at_most_size_of_longer(a: String, b: String) -> bool { let upper_bound = *[a.chars().count(), b.chars().count()] .iter() .max() .unwrap() as usize; wf::distance(a.chars(), b.chars()) <= upper_bound } quickcheck(at_most_size_of_longer as fn(a: String, b: String) -> bool); } #[test] fn zero_iff_a_equals_b_property() { fn zero_iff_a_equals_b(a: String, b: String) -> bool { let d = wf::distance(a.chars(), b.chars()); if a == b { d == 0 } else { d > 0 } } quickcheck(zero_iff_a_equals_b as fn(a: String, b: String) -> bool); } #[test] fn triangle_inequality_property() {
wf::distance(a.chars(), c.chars()) + wf::distance(b.chars(), c.chars()) } quickcheck(triangle_inequality as fn(a: String, b: String, c: String) -> bool); }
fn triangle_inequality(a: String, b: String, c: String) -> bool { wf::distance(a.chars(), b.chars()) <=
random_line_split
day14.rs
extern crate crypto; use std::collections::HashMap; use crypto::md5::Md5; use crypto::digest::Digest; struct HashCache<'a> { base: String, hashes: HashMap<String, String>, hasher: &'a Fn(&str) -> String, } impl<'a> HashCache<'a> { fn new(base: &str, f: &'a Fn(&str) -> String) -> Self { HashCache{ base: base.to_owned(), hashes: HashMap::new(), hasher: f, } } fn get(&mut self, index: usize) -> String { let input = format!("{}{}", self.base, index); if self.hashes.get(&input).is_none() { let key = (self.hasher)(&input); self.hashes.insert(input.clone(), key); } self.hashes[&input].clone() } } fn has_triple(key: &str) -> Option<String> { let v : Vec<_> = key.chars().collect(); let mut windows = v.windows(3); while let Some(x) = windows.next() { let (a, b, c) = (x[0], x[1], x[2]); if a == b && b == c { return Some(format!("{}{}{}{}{}", a, a, a, a, a)) } } None } fn find_keys(salt: &str, num_keys: usize, hasher: &Fn(&str) -> String) -> Vec<(usize, String)> { let mut ret = Vec::new(); let mut index = 0; let mut hc = HashCache::new(salt, hasher); while ret.len() < num_keys { let key = hc.get(index); if let Some(t) = has_triple(&key) { for i in 1..1000 { if hc.get(index + i).contains(&t) { ret.push((index, key)); break } } } index += 1; } ret } fn h1(salt: &str) -> String { let mut hasher = Md5::new(); hasher.input(salt.as_bytes()); hasher.result_str() } fn h2016(salt: &str) -> String { let mut hasher = Md5::new(); let mut key = h1(salt); for _ in 0..2016 { hasher.input(key.as_bytes()); key = hasher.result_str(); hasher.reset(); } key } fn
() { let keys = find_keys("jlmsuwbz", 64, &h1); println!("1: {}", keys.last().unwrap().0); let keys = find_keys("jlmsuwbz", 64, &h2016); println!("2: {}", keys.last().unwrap().0); }
main
identifier_name
day14.rs
extern crate crypto; use std::collections::HashMap; use crypto::md5::Md5; use crypto::digest::Digest; struct HashCache<'a> { base: String, hashes: HashMap<String, String>, hasher: &'a Fn(&str) -> String, } impl<'a> HashCache<'a> { fn new(base: &str, f: &'a Fn(&str) -> String) -> Self { HashCache{ base: base.to_owned(), hashes: HashMap::new(), hasher: f, } } fn get(&mut self, index: usize) -> String { let input = format!("{}{}", self.base, index); if self.hashes.get(&input).is_none() { let key = (self.hasher)(&input); self.hashes.insert(input.clone(), key); } self.hashes[&input].clone() } } fn has_triple(key: &str) -> Option<String> { let v : Vec<_> = key.chars().collect(); let mut windows = v.windows(3); while let Some(x) = windows.next() { let (a, b, c) = (x[0], x[1], x[2]); if a == b && b == c { return Some(format!("{}{}{}{}{}", a, a, a, a, a)) } } None } fn find_keys(salt: &str, num_keys: usize, hasher: &Fn(&str) -> String) -> Vec<(usize, String)> { let mut ret = Vec::new(); let mut index = 0; let mut hc = HashCache::new(salt, hasher);
if let Some(t) = has_triple(&key) { for i in 1..1000 { if hc.get(index + i).contains(&t) { ret.push((index, key)); break } } } index += 1; } ret } fn h1(salt: &str) -> String { let mut hasher = Md5::new(); hasher.input(salt.as_bytes()); hasher.result_str() } fn h2016(salt: &str) -> String { let mut hasher = Md5::new(); let mut key = h1(salt); for _ in 0..2016 { hasher.input(key.as_bytes()); key = hasher.result_str(); hasher.reset(); } key } fn main() { let keys = find_keys("jlmsuwbz", 64, &h1); println!("1: {}", keys.last().unwrap().0); let keys = find_keys("jlmsuwbz", 64, &h2016); println!("2: {}", keys.last().unwrap().0); }
while ret.len() < num_keys { let key = hc.get(index);
random_line_split
day14.rs
extern crate crypto; use std::collections::HashMap; use crypto::md5::Md5; use crypto::digest::Digest; struct HashCache<'a> { base: String, hashes: HashMap<String, String>, hasher: &'a Fn(&str) -> String, } impl<'a> HashCache<'a> { fn new(base: &str, f: &'a Fn(&str) -> String) -> Self { HashCache{ base: base.to_owned(), hashes: HashMap::new(), hasher: f, } } fn get(&mut self, index: usize) -> String { let input = format!("{}{}", self.base, index); if self.hashes.get(&input).is_none() { let key = (self.hasher)(&input); self.hashes.insert(input.clone(), key); } self.hashes[&input].clone() } } fn has_triple(key: &str) -> Option<String> { let v : Vec<_> = key.chars().collect(); let mut windows = v.windows(3); while let Some(x) = windows.next() { let (a, b, c) = (x[0], x[1], x[2]); if a == b && b == c { return Some(format!("{}{}{}{}{}", a, a, a, a, a)) } } None } fn find_keys(salt: &str, num_keys: usize, hasher: &Fn(&str) -> String) -> Vec<(usize, String)> { let mut ret = Vec::new(); let mut index = 0; let mut hc = HashCache::new(salt, hasher); while ret.len() < num_keys { let key = hc.get(index); if let Some(t) = has_triple(&key) { for i in 1..1000 { if hc.get(index + i).contains(&t)
} } index += 1; } ret } fn h1(salt: &str) -> String { let mut hasher = Md5::new(); hasher.input(salt.as_bytes()); hasher.result_str() } fn h2016(salt: &str) -> String { let mut hasher = Md5::new(); let mut key = h1(salt); for _ in 0..2016 { hasher.input(key.as_bytes()); key = hasher.result_str(); hasher.reset(); } key } fn main() { let keys = find_keys("jlmsuwbz", 64, &h1); println!("1: {}", keys.last().unwrap().0); let keys = find_keys("jlmsuwbz", 64, &h2016); println!("2: {}", keys.last().unwrap().0); }
{ ret.push((index, key)); break }
conditional_block
day14.rs
extern crate crypto; use std::collections::HashMap; use crypto::md5::Md5; use crypto::digest::Digest; struct HashCache<'a> { base: String, hashes: HashMap<String, String>, hasher: &'a Fn(&str) -> String, } impl<'a> HashCache<'a> { fn new(base: &str, f: &'a Fn(&str) -> String) -> Self { HashCache{ base: base.to_owned(), hashes: HashMap::new(), hasher: f, } } fn get(&mut self, index: usize) -> String { let input = format!("{}{}", self.base, index); if self.hashes.get(&input).is_none() { let key = (self.hasher)(&input); self.hashes.insert(input.clone(), key); } self.hashes[&input].clone() } } fn has_triple(key: &str) -> Option<String>
fn find_keys(salt: &str, num_keys: usize, hasher: &Fn(&str) -> String) -> Vec<(usize, String)> { let mut ret = Vec::new(); let mut index = 0; let mut hc = HashCache::new(salt, hasher); while ret.len() < num_keys { let key = hc.get(index); if let Some(t) = has_triple(&key) { for i in 1..1000 { if hc.get(index + i).contains(&t) { ret.push((index, key)); break } } } index += 1; } ret } fn h1(salt: &str) -> String { let mut hasher = Md5::new(); hasher.input(salt.as_bytes()); hasher.result_str() } fn h2016(salt: &str) -> String { let mut hasher = Md5::new(); let mut key = h1(salt); for _ in 0..2016 { hasher.input(key.as_bytes()); key = hasher.result_str(); hasher.reset(); } key } fn main() { let keys = find_keys("jlmsuwbz", 64, &h1); println!("1: {}", keys.last().unwrap().0); let keys = find_keys("jlmsuwbz", 64, &h2016); println!("2: {}", keys.last().unwrap().0); }
{ let v : Vec<_> = key.chars().collect(); let mut windows = v.windows(3); while let Some(x) = windows.next() { let (a, b, c) = (x[0], x[1], x[2]); if a == b && b == c { return Some(format!("{}{}{}{}{}", a, a, a, a, a)) } } None }
identifier_body
inefficient_to_string.rs
use clippy_utils::diagnostics::span_lint_and_then; use clippy_utils::source::snippet_with_applicability; use clippy_utils::ty::{is_type_diagnostic_item, walk_ptrs_ty_depth}; use clippy_utils::{match_def_path, paths}; use if_chain::if_chain; use rustc_errors::Applicability; use rustc_hir as hir; use rustc_lint::LateContext; use rustc_middle::ty::{self, Ty}; use rustc_span::symbol::{sym, Symbol}; use super::INEFFICIENT_TO_STRING; /// Checks for the `INEFFICIENT_TO_STRING` lint pub fn check<'tcx>(cx: &LateContext<'tcx>, expr: &hir::Expr<'_>, method_name: Symbol, args: &[hir::Expr<'_>]) { if_chain! { if args.len() == 1 && method_name == sym!(to_string); if let Some(to_string_meth_did) = cx.typeck_results().type_dependent_def_id(expr.hir_id); if match_def_path(cx, to_string_meth_did, &paths::TO_STRING_METHOD); if let Some(substs) = cx.typeck_results().node_substs_opt(expr.hir_id); let arg_ty = cx.typeck_results().expr_ty_adjusted(&args[0]); let self_ty = substs.type_at(0); let (deref_self_ty, deref_count) = walk_ptrs_ty_depth(self_ty); if deref_count >= 1; if specializes_tostring(cx, deref_self_ty); then { span_lint_and_then( cx, INEFFICIENT_TO_STRING, expr.span, &format!("calling `to_string` on `{}`", arg_ty), |diag| { diag.help(&format!( "`{}` implements `ToString` through a slower blanket impl, but `{}` has a fast specialization of `ToString`", self_ty, deref_self_ty )); let mut applicability = Applicability::MachineApplicable; let arg_snippet = snippet_with_applicability(cx, args[0].span, "..", &mut applicability); diag.span_suggestion( expr.span, "try dereferencing the receiver", format!("({}{}).to_string()", "*".repeat(deref_count), arg_snippet), applicability, ); }, ); } } }
/// Returns whether `ty` specializes `ToString`. /// Currently, these are `str`, `String`, and `Cow<'_, str>`. fn specializes_tostring(cx: &LateContext<'_>, ty: Ty<'_>) -> bool { if let ty::Str = ty.kind() { return true; } if is_type_diagnostic_item(cx, ty, sym::String) { return true; } if let ty::Adt(adt, substs) = ty.kind() { match_def_path(cx, adt.did, &paths::COW) && substs.type_at(1).is_str() } else { false } }
random_line_split
inefficient_to_string.rs
use clippy_utils::diagnostics::span_lint_and_then; use clippy_utils::source::snippet_with_applicability; use clippy_utils::ty::{is_type_diagnostic_item, walk_ptrs_ty_depth}; use clippy_utils::{match_def_path, paths}; use if_chain::if_chain; use rustc_errors::Applicability; use rustc_hir as hir; use rustc_lint::LateContext; use rustc_middle::ty::{self, Ty}; use rustc_span::symbol::{sym, Symbol}; use super::INEFFICIENT_TO_STRING; /// Checks for the `INEFFICIENT_TO_STRING` lint pub fn
<'tcx>(cx: &LateContext<'tcx>, expr: &hir::Expr<'_>, method_name: Symbol, args: &[hir::Expr<'_>]) { if_chain! { if args.len() == 1 && method_name == sym!(to_string); if let Some(to_string_meth_did) = cx.typeck_results().type_dependent_def_id(expr.hir_id); if match_def_path(cx, to_string_meth_did, &paths::TO_STRING_METHOD); if let Some(substs) = cx.typeck_results().node_substs_opt(expr.hir_id); let arg_ty = cx.typeck_results().expr_ty_adjusted(&args[0]); let self_ty = substs.type_at(0); let (deref_self_ty, deref_count) = walk_ptrs_ty_depth(self_ty); if deref_count >= 1; if specializes_tostring(cx, deref_self_ty); then { span_lint_and_then( cx, INEFFICIENT_TO_STRING, expr.span, &format!("calling `to_string` on `{}`", arg_ty), |diag| { diag.help(&format!( "`{}` implements `ToString` through a slower blanket impl, but `{}` has a fast specialization of `ToString`", self_ty, deref_self_ty )); let mut applicability = Applicability::MachineApplicable; let arg_snippet = snippet_with_applicability(cx, args[0].span, "..", &mut applicability); diag.span_suggestion( expr.span, "try dereferencing the receiver", format!("({}{}).to_string()", "*".repeat(deref_count), arg_snippet), applicability, ); }, ); } } } /// Returns whether `ty` specializes `ToString`. /// Currently, these are `str`, `String`, and `Cow<'_, str>`. fn specializes_tostring(cx: &LateContext<'_>, ty: Ty<'_>) -> bool { if let ty::Str = ty.kind() { return true; } if is_type_diagnostic_item(cx, ty, sym::String) { return true; } if let ty::Adt(adt, substs) = ty.kind() { match_def_path(cx, adt.did, &paths::COW) && substs.type_at(1).is_str() } else { false } }
check
identifier_name
inefficient_to_string.rs
use clippy_utils::diagnostics::span_lint_and_then; use clippy_utils::source::snippet_with_applicability; use clippy_utils::ty::{is_type_diagnostic_item, walk_ptrs_ty_depth}; use clippy_utils::{match_def_path, paths}; use if_chain::if_chain; use rustc_errors::Applicability; use rustc_hir as hir; use rustc_lint::LateContext; use rustc_middle::ty::{self, Ty}; use rustc_span::symbol::{sym, Symbol}; use super::INEFFICIENT_TO_STRING; /// Checks for the `INEFFICIENT_TO_STRING` lint pub fn check<'tcx>(cx: &LateContext<'tcx>, expr: &hir::Expr<'_>, method_name: Symbol, args: &[hir::Expr<'_>]) { if_chain! { if args.len() == 1 && method_name == sym!(to_string); if let Some(to_string_meth_did) = cx.typeck_results().type_dependent_def_id(expr.hir_id); if match_def_path(cx, to_string_meth_did, &paths::TO_STRING_METHOD); if let Some(substs) = cx.typeck_results().node_substs_opt(expr.hir_id); let arg_ty = cx.typeck_results().expr_ty_adjusted(&args[0]); let self_ty = substs.type_at(0); let (deref_self_ty, deref_count) = walk_ptrs_ty_depth(self_ty); if deref_count >= 1; if specializes_tostring(cx, deref_self_ty); then { span_lint_and_then( cx, INEFFICIENT_TO_STRING, expr.span, &format!("calling `to_string` on `{}`", arg_ty), |diag| { diag.help(&format!( "`{}` implements `ToString` through a slower blanket impl, but `{}` has a fast specialization of `ToString`", self_ty, deref_self_ty )); let mut applicability = Applicability::MachineApplicable; let arg_snippet = snippet_with_applicability(cx, args[0].span, "..", &mut applicability); diag.span_suggestion( expr.span, "try dereferencing the receiver", format!("({}{}).to_string()", "*".repeat(deref_count), arg_snippet), applicability, ); }, ); } } } /// Returns whether `ty` specializes `ToString`. /// Currently, these are `str`, `String`, and `Cow<'_, str>`. fn specializes_tostring(cx: &LateContext<'_>, ty: Ty<'_>) -> bool { if let ty::Str = ty.kind() { return true; } if is_type_diagnostic_item(cx, ty, sym::String) { return true; } if let ty::Adt(adt, substs) = ty.kind()
else { false } }
{ match_def_path(cx, adt.did, &paths::COW) && substs.type_at(1).is_str() }
conditional_block
inefficient_to_string.rs
use clippy_utils::diagnostics::span_lint_and_then; use clippy_utils::source::snippet_with_applicability; use clippy_utils::ty::{is_type_diagnostic_item, walk_ptrs_ty_depth}; use clippy_utils::{match_def_path, paths}; use if_chain::if_chain; use rustc_errors::Applicability; use rustc_hir as hir; use rustc_lint::LateContext; use rustc_middle::ty::{self, Ty}; use rustc_span::symbol::{sym, Symbol}; use super::INEFFICIENT_TO_STRING; /// Checks for the `INEFFICIENT_TO_STRING` lint pub fn check<'tcx>(cx: &LateContext<'tcx>, expr: &hir::Expr<'_>, method_name: Symbol, args: &[hir::Expr<'_>])
self_ty, deref_self_ty )); let mut applicability = Applicability::MachineApplicable; let arg_snippet = snippet_with_applicability(cx, args[0].span, "..", &mut applicability); diag.span_suggestion( expr.span, "try dereferencing the receiver", format!("({}{}).to_string()", "*".repeat(deref_count), arg_snippet), applicability, ); }, ); } } } /// Returns whether `ty` specializes `ToString`. /// Currently, these are `str`, `String`, and `Cow<'_, str>`. fn specializes_tostring(cx: &LateContext<'_>, ty: Ty<'_>) -> bool { if let ty::Str = ty.kind() { return true; } if is_type_diagnostic_item(cx, ty, sym::String) { return true; } if let ty::Adt(adt, substs) = ty.kind() { match_def_path(cx, adt.did, &paths::COW) && substs.type_at(1).is_str() } else { false } }
{ if_chain! { if args.len() == 1 && method_name == sym!(to_string); if let Some(to_string_meth_did) = cx.typeck_results().type_dependent_def_id(expr.hir_id); if match_def_path(cx, to_string_meth_did, &paths::TO_STRING_METHOD); if let Some(substs) = cx.typeck_results().node_substs_opt(expr.hir_id); let arg_ty = cx.typeck_results().expr_ty_adjusted(&args[0]); let self_ty = substs.type_at(0); let (deref_self_ty, deref_count) = walk_ptrs_ty_depth(self_ty); if deref_count >= 1; if specializes_tostring(cx, deref_self_ty); then { span_lint_and_then( cx, INEFFICIENT_TO_STRING, expr.span, &format!("calling `to_string` on `{}`", arg_ty), |diag| { diag.help(&format!( "`{}` implements `ToString` through a slower blanket impl, but `{}` has a fast specialization of `ToString`",
identifier_body
sqrt.rs
use {Style, Sign, Float}; impl Float { pub fn sqrt(mut self) -> Float { self.debug_assert_valid(); let prec = self.prec; match self.style { Style::NaN => Float::nan(prec), Style::Infinity => { match self.sign { Sign::Pos => Float::inf(prec, Sign::Pos),
if self.sign == Sign::Neg { return Float::nan(prec); } // use this instead of % 2 to get the right sign // (should be 0 or 1, even if exp is negative) let c = self.exp & 1; let exp = (self.exp - c) / 2; // we compute sqrt(m1 * 2**c * 2**(p + 1)) to ensure // we get the full significand, and the rounding bit, // and can use the remainder to check for sticky bits. let shift = prec as usize + 1 + c as usize; self.signif <<= shift; let (mut sqrt, rem) = self.signif.sqrt_rem().unwrap(); let bits = sqrt.bit_length(); assert!(bits >= prec + 1); let unshift = bits - prec; let ulp_bit = sqrt.bit(unshift); let half_ulp_bit = sqrt.bit(unshift - 1); let has_trailing_ones = rem!= 0 || sqrt.trailing_zeros() < unshift - 1; sqrt >>= unshift as usize; let mut ret = Float { prec: prec, sign: Sign::Pos, exp: exp, signif: sqrt, style: Style::Normal, }; if half_ulp_bit && (ulp_bit || has_trailing_ones) { ret.add_ulp(); } ret } } } }
Sign::Neg => Float::nan(prec), } } Style::Zero => Float::zero_(prec, self.sign), Style::Normal => {
random_line_split
sqrt.rs
use {Style, Sign, Float}; impl Float { pub fn sqrt(mut self) -> Float
let c = self.exp & 1; let exp = (self.exp - c) / 2; // we compute sqrt(m1 * 2**c * 2**(p + 1)) to ensure // we get the full significand, and the rounding bit, // and can use the remainder to check for sticky bits. let shift = prec as usize + 1 + c as usize; self.signif <<= shift; let (mut sqrt, rem) = self.signif.sqrt_rem().unwrap(); let bits = sqrt.bit_length(); assert!(bits >= prec + 1); let unshift = bits - prec; let ulp_bit = sqrt.bit(unshift); let half_ulp_bit = sqrt.bit(unshift - 1); let has_trailing_ones = rem!= 0 || sqrt.trailing_zeros() < unshift - 1; sqrt >>= unshift as usize; let mut ret = Float { prec: prec, sign: Sign::Pos, exp: exp, signif: sqrt, style: Style::Normal, }; if half_ulp_bit && (ulp_bit || has_trailing_ones) { ret.add_ulp(); } ret } } } }
{ self.debug_assert_valid(); let prec = self.prec; match self.style { Style::NaN => Float::nan(prec), Style::Infinity => { match self.sign { Sign::Pos => Float::inf(prec, Sign::Pos), Sign::Neg => Float::nan(prec), } } Style::Zero => Float::zero_(prec, self.sign), Style::Normal => { if self.sign == Sign::Neg { return Float::nan(prec); } // use this instead of % 2 to get the right sign // (should be 0 or 1, even if exp is negative)
identifier_body
sqrt.rs
use {Style, Sign, Float}; impl Float { pub fn
(mut self) -> Float { self.debug_assert_valid(); let prec = self.prec; match self.style { Style::NaN => Float::nan(prec), Style::Infinity => { match self.sign { Sign::Pos => Float::inf(prec, Sign::Pos), Sign::Neg => Float::nan(prec), } } Style::Zero => Float::zero_(prec, self.sign), Style::Normal => { if self.sign == Sign::Neg { return Float::nan(prec); } // use this instead of % 2 to get the right sign // (should be 0 or 1, even if exp is negative) let c = self.exp & 1; let exp = (self.exp - c) / 2; // we compute sqrt(m1 * 2**c * 2**(p + 1)) to ensure // we get the full significand, and the rounding bit, // and can use the remainder to check for sticky bits. let shift = prec as usize + 1 + c as usize; self.signif <<= shift; let (mut sqrt, rem) = self.signif.sqrt_rem().unwrap(); let bits = sqrt.bit_length(); assert!(bits >= prec + 1); let unshift = bits - prec; let ulp_bit = sqrt.bit(unshift); let half_ulp_bit = sqrt.bit(unshift - 1); let has_trailing_ones = rem!= 0 || sqrt.trailing_zeros() < unshift - 1; sqrt >>= unshift as usize; let mut ret = Float { prec: prec, sign: Sign::Pos, exp: exp, signif: sqrt, style: Style::Normal, }; if half_ulp_bit && (ulp_bit || has_trailing_ones) { ret.add_ulp(); } ret } } } }
sqrt
identifier_name
newlambdas.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.
fn ff() -> @fn(int) -> int { return |x| x + 1; } pub fn main() { assert_eq!(f(10, |a| a), 10); g(||()); assert_eq!(do f(10) |a| { a }, 10); do g() { } let _x: @fn() -> int = || 10; let _y: @fn(int) -> int = |a| a; assert_eq!(ff()(10), 11); }
// Tests for the new |args| expr lambda syntax fn f(i: int, f: &fn(int) -> int) -> int { f(i) } fn g(g: &fn()) { }
random_line_split
newlambdas.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. // Tests for the new |args| expr lambda syntax fn f(i: int, f: &fn(int) -> int) -> int { f(i) } fn
(g: &fn()) { } fn ff() -> @fn(int) -> int { return |x| x + 1; } pub fn main() { assert_eq!(f(10, |a| a), 10); g(||()); assert_eq!(do f(10) |a| { a }, 10); do g() { } let _x: @fn() -> int = || 10; let _y: @fn(int) -> int = |a| a; assert_eq!(ff()(10), 11); }
g
identifier_name
newlambdas.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. // Tests for the new |args| expr lambda syntax fn f(i: int, f: &fn(int) -> int) -> int { f(i) } fn g(g: &fn())
fn ff() -> @fn(int) -> int { return |x| x + 1; } pub fn main() { assert_eq!(f(10, |a| a), 10); g(||()); assert_eq!(do f(10) |a| { a }, 10); do g() { } let _x: @fn() -> int = || 10; let _y: @fn(int) -> int = |a| a; assert_eq!(ff()(10), 11); }
{ }
identifier_body
p051.rs
//! [Problem 51](https://projecteuler.net/problem=51) solver. #![warn(bad_style, unused, unused_extern_crates, unused_import_braces, unused_qualifications, unused_results)] #[macro_use(problem)] extern crate common; extern crate integer; extern crate prime; use integer::Integer; use prime::PrimeSet; fn compute(num_value: usize) -> u64 { let radix = 10; let ps = PrimeSet::new(); for p in &ps { let ds = p.into_digits(radix as u64); let hs = p.into_digit_histogram(); for (d_src, &cnt) in hs.iter().enumerate() { // Skip digits that are appeared less than twice. if cnt <= 1 { continue } let mut num_prime = 1; for d_dst in (d_src + 1.. radix) { if radix - d_dst < num_value - num_prime { break } let it = ds.clone().map(|d| if d == (d_src as u64) { d_dst as u64 } else { d }); if ps.contains(Integer::from_digits(it, radix as u64)) { num_prime += 1; } } if num_prime >= num_value { return p } } } unreachable!() } fn solve() -> String
problem!("121313", solve); #[cfg(test)] mod tests { #[test] fn seven() { assert_eq!(56003, super::compute(7)) } }
{ compute(8).to_string() }
identifier_body
p051.rs
//! [Problem 51](https://projecteuler.net/problem=51) solver. #![warn(bad_style, unused, unused_extern_crates, unused_import_braces, unused_qualifications, unused_results)] #[macro_use(problem)] extern crate common; extern crate integer; extern crate prime; use integer::Integer; use prime::PrimeSet; fn compute(num_value: usize) -> u64 { let radix = 10; let ps = PrimeSet::new(); for p in &ps { let ds = p.into_digits(radix as u64); let hs = p.into_digit_histogram(); for (d_src, &cnt) in hs.iter().enumerate() { // Skip digits that are appeared less than twice. if cnt <= 1 { continue } let mut num_prime = 1; for d_dst in (d_src + 1.. radix) { if radix - d_dst < num_value - num_prime { break } let it = ds.clone().map(|d| if d == (d_src as u64) { d_dst as u64 } else { d }); if ps.contains(Integer::from_digits(it, radix as u64)) { num_prime += 1; } } if num_prime >= num_value { return p } } } unreachable!() } fn solve() -> String { compute(8).to_string() } problem!("121313", solve); #[cfg(test)] mod tests { #[test] fn
() { assert_eq!(56003, super::compute(7)) } }
seven
identifier_name
p051.rs
//! [Problem 51](https://projecteuler.net/problem=51) solver. #![warn(bad_style, unused, unused_extern_crates, unused_import_braces, unused_qualifications, unused_results)] #[macro_use(problem)] extern crate common; extern crate integer; extern crate prime; use integer::Integer; use prime::PrimeSet; fn compute(num_value: usize) -> u64 { let radix = 10; let ps = PrimeSet::new(); for p in &ps { let ds = p.into_digits(radix as u64); let hs = p.into_digit_histogram(); for (d_src, &cnt) in hs.iter().enumerate() { // Skip digits that are appeared less than twice. if cnt <= 1 { continue } let mut num_prime = 1; for d_dst in (d_src + 1.. radix) { if radix - d_dst < num_value - num_prime { break } let it = ds.clone().map(|d| if d == (d_src as u64) { d_dst as u64 } else { d }); if ps.contains(Integer::from_digits(it, radix as u64)) { num_prime += 1; }
} } } unreachable!() } fn solve() -> String { compute(8).to_string() } problem!("121313", solve); #[cfg(test)] mod tests { #[test] fn seven() { assert_eq!(56003, super::compute(7)) } }
} if num_prime >= num_value { return p
random_line_split
p051.rs
//! [Problem 51](https://projecteuler.net/problem=51) solver. #![warn(bad_style, unused, unused_extern_crates, unused_import_braces, unused_qualifications, unused_results)] #[macro_use(problem)] extern crate common; extern crate integer; extern crate prime; use integer::Integer; use prime::PrimeSet; fn compute(num_value: usize) -> u64 { let radix = 10; let ps = PrimeSet::new(); for p in &ps { let ds = p.into_digits(radix as u64); let hs = p.into_digit_histogram(); for (d_src, &cnt) in hs.iter().enumerate() { // Skip digits that are appeared less than twice. if cnt <= 1 { continue } let mut num_prime = 1; for d_dst in (d_src + 1.. radix) { if radix - d_dst < num_value - num_prime { break } let it = ds.clone().map(|d| if d == (d_src as u64) { d_dst as u64 } else { d }); if ps.contains(Integer::from_digits(it, radix as u64))
} if num_prime >= num_value { return p } } } unreachable!() } fn solve() -> String { compute(8).to_string() } problem!("121313", solve); #[cfg(test)] mod tests { #[test] fn seven() { assert_eq!(56003, super::compute(7)) } }
{ num_prime += 1; }
conditional_block
font.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/. */ /// Implementation of Quartz (CoreGraphics) fonts. extern crate core_foundation; extern crate core_graphics; extern crate core_text; use app_units::Au; use core_foundation::base::CFIndex; use core_foundation::data::CFData; use core_foundation::string::UniChar; use core_graphics::font::CGGlyph; use core_graphics::geometry::CGRect; use core_text::font::CTFont; use core_text::font_descriptor::{SymbolicTraitAccessors, TraitAccessors}; use core_text::font_descriptor::{kCTFontDefaultOrientation}; use font::FontTableTag; use font::FractionalPixel; use font::{FontHandleMethods, FontMetrics, FontTableMethods}; use platform::font_template::FontTemplateData; use platform::macos::font_context::FontContextHandle; use std::ptr; use std::sync::Arc; use style::computed_values::{font_stretch, font_weight}; use text::glyph::GlyphId; pub struct FontTable { data: CFData, } // assumes 72 points per inch, and 96 px per inch fn px_to_pt(px: f64) -> f64 { px / 96. * 72. } // assumes 72 points per inch, and 96 px per inch fn pt_to_px(pt: f64) -> f64 { pt / 72. * 96. } fn au_from_pt(pt: f64) -> Au { Au::from_f64_px(pt_to_px(pt)) } impl FontTable { pub fn wrap(data: CFData) -> FontTable { FontTable { data: data } } } impl FontTableMethods for FontTable { fn with_buffer<F>(&self, blk: F) where F: FnOnce(*const u8, usize) { blk(self.data.bytes().as_ptr(), self.data.len() as usize); } } #[derive(Debug)] pub struct FontHandle { pub font_data: Arc<FontTemplateData>, pub ctfont: CTFont, } impl FontHandleMethods for FontHandle { fn new_from_template(_fctx: &FontContextHandle, template: Arc<FontTemplateData>, pt_size: Option<Au>) -> Result<FontHandle, ()> { let size = match pt_size { Some(s) => s.to_f64_px(), None => 0.0 }; match template.ctfont(size) { Some(ref ctfont) => { Ok(FontHandle { font_data: template.clone(), ctfont: ctfont.clone_with_font_size(size), }) } None => { Err(()) } } } fn template(&self) -> Arc<FontTemplateData> { self.font_data.clone() } fn family_name(&self) -> String { self.ctfont.family_name() } fn face_name(&self) -> String { self.ctfont.face_name() } fn is_italic(&self) -> bool { self.ctfont.symbolic_traits().is_italic() } fn boldness(&self) -> font_weight::T { let normalized = self.ctfont.all_traits().normalized_weight(); // [-1.0, 1.0] let normalized = (normalized + 1.0) / 2.0 * 9.0; // [0.0, 9.0] match normalized { v if v < 1.0 => font_weight::T::Weight100, v if v < 2.0 => font_weight::T::Weight200, v if v < 3.0 => font_weight::T::Weight300, v if v < 4.0 => font_weight::T::Weight400, v if v < 5.0 => font_weight::T::Weight500, v if v < 6.0 => font_weight::T::Weight600, v if v < 7.0 => font_weight::T::Weight700, v if v < 8.0 => font_weight::T::Weight800, _ => font_weight::T::Weight900, } } fn stretchiness(&self) -> font_stretch::T { let normalized = self.ctfont.all_traits().normalized_width(); // [-1.0, 1.0] let normalized = (normalized + 1.0) / 2.0 * 9.0; // [0.0, 9.0] match normalized { v if v < 1.0 => font_stretch::T::ultra_condensed, v if v < 2.0 => font_stretch::T::extra_condensed, v if v < 3.0 => font_stretch::T::condensed, v if v < 4.0 => font_stretch::T::semi_condensed, v if v < 5.0 => font_stretch::T::normal, v if v < 6.0 => font_stretch::T::semi_expanded, v if v < 7.0 => font_stretch::T::expanded, v if v < 8.0 => font_stretch::T::extra_expanded, _ => font_stretch::T::ultra_expanded, } } fn glyph_index(&self, codepoint: char) -> Option<GlyphId> { let characters: [UniChar; 1] = [codepoint as UniChar]; let mut glyphs: [CGGlyph; 1] = [0 as CGGlyph]; let count: CFIndex = 1; let result = self.ctfont.get_glyphs_for_characters(&characters[0], &mut glyphs[0], count); if!result { // No glyph for this character return None; } assert!(glyphs[0]!= 0); // FIXME: error handling return Some(glyphs[0] as GlyphId); } fn glyph_h_kerning(&self, _first_glyph: GlyphId, _second_glyph: GlyphId) -> FractionalPixel { // TODO: Implement on mac 0.0 } fn
(&self, glyph: GlyphId) -> Option<FractionalPixel> { let glyphs = [glyph as CGGlyph]; let advance = self.ctfont.get_advances_for_glyphs(kCTFontDefaultOrientation, &glyphs[0], ptr::null_mut(), 1); Some(advance as FractionalPixel) } fn metrics(&self) -> FontMetrics { let bounding_rect: CGRect = self.ctfont.bounding_box(); let ascent = self.ctfont.ascent() as f64; let descent = self.ctfont.descent() as f64; let em_size = Au::from_f64_px(self.ctfont.pt_size() as f64); let leading = self.ctfont.leading() as f64; let scale = px_to_pt(self.ctfont.pt_size() as f64) / (ascent + descent); let line_gap = (ascent + descent + leading + 0.5).floor(); let max_advance_width = au_from_pt(bounding_rect.size.width as f64); let average_advance = self.glyph_index('0') .and_then(|idx| self.glyph_h_advance(idx)) .map(Au::from_f64_px) .unwrap_or(max_advance_width); let metrics = FontMetrics { underline_size: au_from_pt(self.ctfont.underline_thickness() as f64), // TODO(Issue #201): underline metrics are not reliable. Have to pull out of font table // directly. // // see also: https://bugs.webkit.org/show_bug.cgi?id=16768 // see also: https://bugreports.qt-project.org/browse/QTBUG-13364 underline_offset: au_from_pt(self.ctfont.underline_position() as f64), strikeout_size: Au(0), // FIXME(Issue #942) strikeout_offset: Au(0), // FIXME(Issue #942) leading: au_from_pt(leading), x_height: au_from_pt(self.ctfont.x_height() as f64), em_size: em_size, ascent: au_from_pt(ascent * scale), descent: au_from_pt(descent * scale), max_advance: max_advance_width, average_advance: average_advance, line_gap: Au::from_f64_px(line_gap), }; debug!("Font metrics (@{} pt): {:?}", self.ctfont.pt_size() as f64, metrics); metrics } fn table_for_tag(&self, tag: FontTableTag) -> Option<Box<FontTable>> { let result: Option<CFData> = self.ctfont.get_font_table(tag); result.and_then(|data| { Some(box FontTable::wrap(data)) }) } }
glyph_h_advance
identifier_name
font.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/. */ /// Implementation of Quartz (CoreGraphics) fonts. extern crate core_foundation; extern crate core_graphics; extern crate core_text; use app_units::Au; use core_foundation::base::CFIndex; use core_foundation::data::CFData; use core_foundation::string::UniChar; use core_graphics::font::CGGlyph; use core_graphics::geometry::CGRect; use core_text::font::CTFont; use core_text::font_descriptor::{SymbolicTraitAccessors, TraitAccessors}; use core_text::font_descriptor::{kCTFontDefaultOrientation}; use font::FontTableTag; use font::FractionalPixel; use font::{FontHandleMethods, FontMetrics, FontTableMethods}; use platform::font_template::FontTemplateData; use platform::macos::font_context::FontContextHandle; use std::ptr; use std::sync::Arc; use style::computed_values::{font_stretch, font_weight}; use text::glyph::GlyphId; pub struct FontTable { data: CFData, } // assumes 72 points per inch, and 96 px per inch fn px_to_pt(px: f64) -> f64 { px / 96. * 72. } // assumes 72 points per inch, and 96 px per inch fn pt_to_px(pt: f64) -> f64 { pt / 72. * 96. } fn au_from_pt(pt: f64) -> Au { Au::from_f64_px(pt_to_px(pt)) } impl FontTable { pub fn wrap(data: CFData) -> FontTable { FontTable { data: data } } } impl FontTableMethods for FontTable { fn with_buffer<F>(&self, blk: F) where F: FnOnce(*const u8, usize) { blk(self.data.bytes().as_ptr(), self.data.len() as usize); } } #[derive(Debug)] pub struct FontHandle { pub font_data: Arc<FontTemplateData>, pub ctfont: CTFont, } impl FontHandleMethods for FontHandle { fn new_from_template(_fctx: &FontContextHandle, template: Arc<FontTemplateData>, pt_size: Option<Au>) -> Result<FontHandle, ()> { let size = match pt_size { Some(s) => s.to_f64_px(), None => 0.0 }; match template.ctfont(size) { Some(ref ctfont) => { Ok(FontHandle { font_data: template.clone(), ctfont: ctfont.clone_with_font_size(size), }) } None => { Err(()) } } } fn template(&self) -> Arc<FontTemplateData> { self.font_data.clone() } fn family_name(&self) -> String { self.ctfont.family_name() } fn face_name(&self) -> String { self.ctfont.face_name() } fn is_italic(&self) -> bool { self.ctfont.symbolic_traits().is_italic() } fn boldness(&self) -> font_weight::T { let normalized = self.ctfont.all_traits().normalized_weight(); // [-1.0, 1.0] let normalized = (normalized + 1.0) / 2.0 * 9.0; // [0.0, 9.0] match normalized { v if v < 1.0 => font_weight::T::Weight100, v if v < 2.0 => font_weight::T::Weight200, v if v < 3.0 => font_weight::T::Weight300, v if v < 4.0 => font_weight::T::Weight400, v if v < 5.0 => font_weight::T::Weight500, v if v < 6.0 => font_weight::T::Weight600, v if v < 7.0 => font_weight::T::Weight700,
fn stretchiness(&self) -> font_stretch::T { let normalized = self.ctfont.all_traits().normalized_width(); // [-1.0, 1.0] let normalized = (normalized + 1.0) / 2.0 * 9.0; // [0.0, 9.0] match normalized { v if v < 1.0 => font_stretch::T::ultra_condensed, v if v < 2.0 => font_stretch::T::extra_condensed, v if v < 3.0 => font_stretch::T::condensed, v if v < 4.0 => font_stretch::T::semi_condensed, v if v < 5.0 => font_stretch::T::normal, v if v < 6.0 => font_stretch::T::semi_expanded, v if v < 7.0 => font_stretch::T::expanded, v if v < 8.0 => font_stretch::T::extra_expanded, _ => font_stretch::T::ultra_expanded, } } fn glyph_index(&self, codepoint: char) -> Option<GlyphId> { let characters: [UniChar; 1] = [codepoint as UniChar]; let mut glyphs: [CGGlyph; 1] = [0 as CGGlyph]; let count: CFIndex = 1; let result = self.ctfont.get_glyphs_for_characters(&characters[0], &mut glyphs[0], count); if!result { // No glyph for this character return None; } assert!(glyphs[0]!= 0); // FIXME: error handling return Some(glyphs[0] as GlyphId); } fn glyph_h_kerning(&self, _first_glyph: GlyphId, _second_glyph: GlyphId) -> FractionalPixel { // TODO: Implement on mac 0.0 } fn glyph_h_advance(&self, glyph: GlyphId) -> Option<FractionalPixel> { let glyphs = [glyph as CGGlyph]; let advance = self.ctfont.get_advances_for_glyphs(kCTFontDefaultOrientation, &glyphs[0], ptr::null_mut(), 1); Some(advance as FractionalPixel) } fn metrics(&self) -> FontMetrics { let bounding_rect: CGRect = self.ctfont.bounding_box(); let ascent = self.ctfont.ascent() as f64; let descent = self.ctfont.descent() as f64; let em_size = Au::from_f64_px(self.ctfont.pt_size() as f64); let leading = self.ctfont.leading() as f64; let scale = px_to_pt(self.ctfont.pt_size() as f64) / (ascent + descent); let line_gap = (ascent + descent + leading + 0.5).floor(); let max_advance_width = au_from_pt(bounding_rect.size.width as f64); let average_advance = self.glyph_index('0') .and_then(|idx| self.glyph_h_advance(idx)) .map(Au::from_f64_px) .unwrap_or(max_advance_width); let metrics = FontMetrics { underline_size: au_from_pt(self.ctfont.underline_thickness() as f64), // TODO(Issue #201): underline metrics are not reliable. Have to pull out of font table // directly. // // see also: https://bugs.webkit.org/show_bug.cgi?id=16768 // see also: https://bugreports.qt-project.org/browse/QTBUG-13364 underline_offset: au_from_pt(self.ctfont.underline_position() as f64), strikeout_size: Au(0), // FIXME(Issue #942) strikeout_offset: Au(0), // FIXME(Issue #942) leading: au_from_pt(leading), x_height: au_from_pt(self.ctfont.x_height() as f64), em_size: em_size, ascent: au_from_pt(ascent * scale), descent: au_from_pt(descent * scale), max_advance: max_advance_width, average_advance: average_advance, line_gap: Au::from_f64_px(line_gap), }; debug!("Font metrics (@{} pt): {:?}", self.ctfont.pt_size() as f64, metrics); metrics } fn table_for_tag(&self, tag: FontTableTag) -> Option<Box<FontTable>> { let result: Option<CFData> = self.ctfont.get_font_table(tag); result.and_then(|data| { Some(box FontTable::wrap(data)) }) } }
v if v < 8.0 => font_weight::T::Weight800, _ => font_weight::T::Weight900, } }
random_line_split
font.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/. */ /// Implementation of Quartz (CoreGraphics) fonts. extern crate core_foundation; extern crate core_graphics; extern crate core_text; use app_units::Au; use core_foundation::base::CFIndex; use core_foundation::data::CFData; use core_foundation::string::UniChar; use core_graphics::font::CGGlyph; use core_graphics::geometry::CGRect; use core_text::font::CTFont; use core_text::font_descriptor::{SymbolicTraitAccessors, TraitAccessors}; use core_text::font_descriptor::{kCTFontDefaultOrientation}; use font::FontTableTag; use font::FractionalPixel; use font::{FontHandleMethods, FontMetrics, FontTableMethods}; use platform::font_template::FontTemplateData; use platform::macos::font_context::FontContextHandle; use std::ptr; use std::sync::Arc; use style::computed_values::{font_stretch, font_weight}; use text::glyph::GlyphId; pub struct FontTable { data: CFData, } // assumes 72 points per inch, and 96 px per inch fn px_to_pt(px: f64) -> f64 { px / 96. * 72. } // assumes 72 points per inch, and 96 px per inch fn pt_to_px(pt: f64) -> f64 { pt / 72. * 96. } fn au_from_pt(pt: f64) -> Au { Au::from_f64_px(pt_to_px(pt)) } impl FontTable { pub fn wrap(data: CFData) -> FontTable { FontTable { data: data } } } impl FontTableMethods for FontTable { fn with_buffer<F>(&self, blk: F) where F: FnOnce(*const u8, usize)
} #[derive(Debug)] pub struct FontHandle { pub font_data: Arc<FontTemplateData>, pub ctfont: CTFont, } impl FontHandleMethods for FontHandle { fn new_from_template(_fctx: &FontContextHandle, template: Arc<FontTemplateData>, pt_size: Option<Au>) -> Result<FontHandle, ()> { let size = match pt_size { Some(s) => s.to_f64_px(), None => 0.0 }; match template.ctfont(size) { Some(ref ctfont) => { Ok(FontHandle { font_data: template.clone(), ctfont: ctfont.clone_with_font_size(size), }) } None => { Err(()) } } } fn template(&self) -> Arc<FontTemplateData> { self.font_data.clone() } fn family_name(&self) -> String { self.ctfont.family_name() } fn face_name(&self) -> String { self.ctfont.face_name() } fn is_italic(&self) -> bool { self.ctfont.symbolic_traits().is_italic() } fn boldness(&self) -> font_weight::T { let normalized = self.ctfont.all_traits().normalized_weight(); // [-1.0, 1.0] let normalized = (normalized + 1.0) / 2.0 * 9.0; // [0.0, 9.0] match normalized { v if v < 1.0 => font_weight::T::Weight100, v if v < 2.0 => font_weight::T::Weight200, v if v < 3.0 => font_weight::T::Weight300, v if v < 4.0 => font_weight::T::Weight400, v if v < 5.0 => font_weight::T::Weight500, v if v < 6.0 => font_weight::T::Weight600, v if v < 7.0 => font_weight::T::Weight700, v if v < 8.0 => font_weight::T::Weight800, _ => font_weight::T::Weight900, } } fn stretchiness(&self) -> font_stretch::T { let normalized = self.ctfont.all_traits().normalized_width(); // [-1.0, 1.0] let normalized = (normalized + 1.0) / 2.0 * 9.0; // [0.0, 9.0] match normalized { v if v < 1.0 => font_stretch::T::ultra_condensed, v if v < 2.0 => font_stretch::T::extra_condensed, v if v < 3.0 => font_stretch::T::condensed, v if v < 4.0 => font_stretch::T::semi_condensed, v if v < 5.0 => font_stretch::T::normal, v if v < 6.0 => font_stretch::T::semi_expanded, v if v < 7.0 => font_stretch::T::expanded, v if v < 8.0 => font_stretch::T::extra_expanded, _ => font_stretch::T::ultra_expanded, } } fn glyph_index(&self, codepoint: char) -> Option<GlyphId> { let characters: [UniChar; 1] = [codepoint as UniChar]; let mut glyphs: [CGGlyph; 1] = [0 as CGGlyph]; let count: CFIndex = 1; let result = self.ctfont.get_glyphs_for_characters(&characters[0], &mut glyphs[0], count); if!result { // No glyph for this character return None; } assert!(glyphs[0]!= 0); // FIXME: error handling return Some(glyphs[0] as GlyphId); } fn glyph_h_kerning(&self, _first_glyph: GlyphId, _second_glyph: GlyphId) -> FractionalPixel { // TODO: Implement on mac 0.0 } fn glyph_h_advance(&self, glyph: GlyphId) -> Option<FractionalPixel> { let glyphs = [glyph as CGGlyph]; let advance = self.ctfont.get_advances_for_glyphs(kCTFontDefaultOrientation, &glyphs[0], ptr::null_mut(), 1); Some(advance as FractionalPixel) } fn metrics(&self) -> FontMetrics { let bounding_rect: CGRect = self.ctfont.bounding_box(); let ascent = self.ctfont.ascent() as f64; let descent = self.ctfont.descent() as f64; let em_size = Au::from_f64_px(self.ctfont.pt_size() as f64); let leading = self.ctfont.leading() as f64; let scale = px_to_pt(self.ctfont.pt_size() as f64) / (ascent + descent); let line_gap = (ascent + descent + leading + 0.5).floor(); let max_advance_width = au_from_pt(bounding_rect.size.width as f64); let average_advance = self.glyph_index('0') .and_then(|idx| self.glyph_h_advance(idx)) .map(Au::from_f64_px) .unwrap_or(max_advance_width); let metrics = FontMetrics { underline_size: au_from_pt(self.ctfont.underline_thickness() as f64), // TODO(Issue #201): underline metrics are not reliable. Have to pull out of font table // directly. // // see also: https://bugs.webkit.org/show_bug.cgi?id=16768 // see also: https://bugreports.qt-project.org/browse/QTBUG-13364 underline_offset: au_from_pt(self.ctfont.underline_position() as f64), strikeout_size: Au(0), // FIXME(Issue #942) strikeout_offset: Au(0), // FIXME(Issue #942) leading: au_from_pt(leading), x_height: au_from_pt(self.ctfont.x_height() as f64), em_size: em_size, ascent: au_from_pt(ascent * scale), descent: au_from_pt(descent * scale), max_advance: max_advance_width, average_advance: average_advance, line_gap: Au::from_f64_px(line_gap), }; debug!("Font metrics (@{} pt): {:?}", self.ctfont.pt_size() as f64, metrics); metrics } fn table_for_tag(&self, tag: FontTableTag) -> Option<Box<FontTable>> { let result: Option<CFData> = self.ctfont.get_font_table(tag); result.and_then(|data| { Some(box FontTable::wrap(data)) }) } }
{ blk(self.data.bytes().as_ptr(), self.data.len() as usize); }
identifier_body
htmlbrelement.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ use dom::bindings::codegen::Bindings::HTMLBRElementBinding; use dom::bindings::root::DomRoot; use dom::document::Document; use dom::htmlelement::HTMLElement; use dom::node::Node; use dom_struct::dom_struct; use html5ever::{LocalName, Prefix}; #[dom_struct] pub struct HTMLBRElement { htmlelement: HTMLElement,
impl HTMLBRElement { fn new_inherited(local_name: LocalName, prefix: Option<Prefix>, document: &Document) -> HTMLBRElement { HTMLBRElement { htmlelement: HTMLElement::new_inherited(local_name, prefix, document) } } #[allow(unrooted_must_root)] pub fn new(local_name: LocalName, prefix: Option<Prefix>, document: &Document) -> DomRoot<HTMLBRElement> { Node::reflect_node(Box::new(HTMLBRElement::new_inherited(local_name, prefix, document)), document, HTMLBRElementBinding::Wrap) } }
}
random_line_split
htmlbrelement.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ use dom::bindings::codegen::Bindings::HTMLBRElementBinding; use dom::bindings::root::DomRoot; use dom::document::Document; use dom::htmlelement::HTMLElement; use dom::node::Node; use dom_struct::dom_struct; use html5ever::{LocalName, Prefix}; #[dom_struct] pub struct HTMLBRElement { htmlelement: HTMLElement, } impl HTMLBRElement { fn new_inherited(local_name: LocalName, prefix: Option<Prefix>, document: &Document) -> HTMLBRElement { HTMLBRElement { htmlelement: HTMLElement::new_inherited(local_name, prefix, document) } } #[allow(unrooted_must_root)] pub fn
(local_name: LocalName, prefix: Option<Prefix>, document: &Document) -> DomRoot<HTMLBRElement> { Node::reflect_node(Box::new(HTMLBRElement::new_inherited(local_name, prefix, document)), document, HTMLBRElementBinding::Wrap) } }
new
identifier_name
issue-3743.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. struct Vec2 { x: f64, y: f64 } // methods we want to export as methods as well as operators impl Vec2 { #[inline(always)] fn vmul(self, other: f64) -> Vec2 { Vec2 { x: self.x * other, y: self.y * other } } }
// Vec2's implementation of Mul "from the other side" using the above trait impl<Res, Rhs: RhsOfVec2Mul<Res>> Mul<Rhs,Res> for Vec2 { fn mul(&self, rhs: &Rhs) -> Res { rhs.mul_vec2_by(self) } } // Implementation of 'f64 as right-hand-side of Vec2::Mul' impl RhsOfVec2Mul<Vec2> for f64 { fn mul_vec2_by(&self, lhs: &Vec2) -> Vec2 { lhs.vmul(*self) } } // Usage with failing inference pub fn main() { let a = Vec2 { x: 3.0f64, y: 4.0f64 }; // the following compiles and works properly let v1: Vec2 = a * 3.0f64; println!("{} {}", v1.x, v1.y); // the following compiles but v2 will not be Vec2 yet and // using it later will cause an error that the type of v2 // must be known let v2 = a * 3.0f64; println!("{} {}", v2.x, v2.y); // error regarding v2's type }
// Right-hand-side operator visitor pattern trait RhsOfVec2Mul<Result> { fn mul_vec2_by(&self, lhs: &Vec2) -> Result; }
random_line_split
issue-3743.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. struct Vec2 { x: f64, y: f64 } // methods we want to export as methods as well as operators impl Vec2 { #[inline(always)] fn vmul(self, other: f64) -> Vec2 { Vec2 { x: self.x * other, y: self.y * other } } } // Right-hand-side operator visitor pattern trait RhsOfVec2Mul<Result> { fn mul_vec2_by(&self, lhs: &Vec2) -> Result; } // Vec2's implementation of Mul "from the other side" using the above trait impl<Res, Rhs: RhsOfVec2Mul<Res>> Mul<Rhs,Res> for Vec2 { fn mul(&self, rhs: &Rhs) -> Res { rhs.mul_vec2_by(self) } } // Implementation of 'f64 as right-hand-side of Vec2::Mul' impl RhsOfVec2Mul<Vec2> for f64 { fn mul_vec2_by(&self, lhs: &Vec2) -> Vec2 { lhs.vmul(*self) } } // Usage with failing inference pub fn
() { let a = Vec2 { x: 3.0f64, y: 4.0f64 }; // the following compiles and works properly let v1: Vec2 = a * 3.0f64; println!("{} {}", v1.x, v1.y); // the following compiles but v2 will not be Vec2 yet and // using it later will cause an error that the type of v2 // must be known let v2 = a * 3.0f64; println!("{} {}", v2.x, v2.y); // error regarding v2's type }
main
identifier_name
borrowck-preserve-box-in-uniq.rs
// xfail-pretty // 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. // exec-env:RUST_POISON_ON_FREE=1 use std::ptr; fn borrow(x: &int, f: |x: &int|) { let before = *x; f(x); let after = *x; assert_eq!(before, after); } struct F { f: ~int } pub fn main()
{ let mut x = ~@F{f: ~3}; borrow(x.f, |b_x| { assert_eq!(*b_x, 3); assert_eq!(ptr::to_unsafe_ptr(&(*x.f)), ptr::to_unsafe_ptr(&(*b_x))); *x = @F{f: ~4}; info!("ptr::to_unsafe_ptr(*b_x) = {:x}", ptr::to_unsafe_ptr(&(*b_x)) as uint); assert_eq!(*b_x, 3); assert!(ptr::to_unsafe_ptr(&(*x.f)) != ptr::to_unsafe_ptr(&(*b_x))); }) }
identifier_body
borrowck-preserve-box-in-uniq.rs
// xfail-pretty // 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. // exec-env:RUST_POISON_ON_FREE=1 use std::ptr; fn borrow(x: &int, f: |x: &int|) { let before = *x; f(x); let after = *x; assert_eq!(before, after); } struct F { f: ~int } pub fn main() { let mut x = ~@F{f: ~3}; borrow(x.f, |b_x| { assert_eq!(*b_x, 3); assert_eq!(ptr::to_unsafe_ptr(&(*x.f)), ptr::to_unsafe_ptr(&(*b_x))); *x = @F{f: ~4};
ptr::to_unsafe_ptr(&(*b_x)) as uint); assert_eq!(*b_x, 3); assert!(ptr::to_unsafe_ptr(&(*x.f))!= ptr::to_unsafe_ptr(&(*b_x))); }) }
info!("ptr::to_unsafe_ptr(*b_x) = {:x}",
random_line_split
borrowck-preserve-box-in-uniq.rs
// xfail-pretty // 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. // exec-env:RUST_POISON_ON_FREE=1 use std::ptr; fn borrow(x: &int, f: |x: &int|) { let before = *x; f(x); let after = *x; assert_eq!(before, after); } struct
{ f: ~int } pub fn main() { let mut x = ~@F{f: ~3}; borrow(x.f, |b_x| { assert_eq!(*b_x, 3); assert_eq!(ptr::to_unsafe_ptr(&(*x.f)), ptr::to_unsafe_ptr(&(*b_x))); *x = @F{f: ~4}; info!("ptr::to_unsafe_ptr(*b_x) = {:x}", ptr::to_unsafe_ptr(&(*b_x)) as uint); assert_eq!(*b_x, 3); assert!(ptr::to_unsafe_ptr(&(*x.f))!= ptr::to_unsafe_ptr(&(*b_x))); }) }
F
identifier_name
mod.rs
/* * Copyright (c) Facebook, Inc. and its affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ use common::FileKey; use fixture_tests::Fixture; use fnv::FnvHashMap; use graphql_ir::{build, Program}; use graphql_syntax::parse; use graphql_transforms::validate_server_only_directives; use test_schema::test_schema_with_extensions; pub fn transform_fixture(fixture: &Fixture) -> Result<String, String> { let parts: Vec<_> = fixture.content.split("%extensions%").collect(); if let [base, extensions] = parts.as_slice() { let file_key = FileKey::new(fixture.file_name); let ast = parse(base, file_key).unwrap(); let schema = test_schema_with_extensions(extensions); let mut sources = FnvHashMap::default(); sources.insert(FileKey::new(fixture.file_name), fixture.content); let ir = build(&schema, &ast.definitions).unwrap(); let program = Program::from_definitions(&schema, ir); let result = validate_server_only_directives(&program); match result { Ok(_) => Ok("OK".to_owned()), Err(errors) =>
} } else { panic!("Expected exactly one %extensions% section marker.") } }
{ let mut errs = errors .into_iter() .map(|err| err.print(&sources)) .collect::<Vec<_>>(); errs.sort(); Err(errs.join("\n\n")) }
conditional_block
mod.rs
/* * Copyright (c) Facebook, Inc. and its affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ use common::FileKey; use fixture_tests::Fixture; use fnv::FnvHashMap; use graphql_ir::{build, Program}; use graphql_syntax::parse; use graphql_transforms::validate_server_only_directives; use test_schema::test_schema_with_extensions; pub fn transform_fixture(fixture: &Fixture) -> Result<String, String>
.collect::<Vec<_>>(); errs.sort(); Err(errs.join("\n\n")) } } } else { panic!("Expected exactly one %extensions% section marker.") } }
{ let parts: Vec<_> = fixture.content.split("%extensions%").collect(); if let [base, extensions] = parts.as_slice() { let file_key = FileKey::new(fixture.file_name); let ast = parse(base, file_key).unwrap(); let schema = test_schema_with_extensions(extensions); let mut sources = FnvHashMap::default(); sources.insert(FileKey::new(fixture.file_name), fixture.content); let ir = build(&schema, &ast.definitions).unwrap(); let program = Program::from_definitions(&schema, ir); let result = validate_server_only_directives(&program); match result { Ok(_) => Ok("OK".to_owned()), Err(errors) => { let mut errs = errors .into_iter() .map(|err| err.print(&sources))
identifier_body
mod.rs
/* * Copyright (c) Facebook, Inc. and its affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ use common::FileKey; use fixture_tests::Fixture; use fnv::FnvHashMap; use graphql_ir::{build, Program}; use graphql_syntax::parse;
if let [base, extensions] = parts.as_slice() { let file_key = FileKey::new(fixture.file_name); let ast = parse(base, file_key).unwrap(); let schema = test_schema_with_extensions(extensions); let mut sources = FnvHashMap::default(); sources.insert(FileKey::new(fixture.file_name), fixture.content); let ir = build(&schema, &ast.definitions).unwrap(); let program = Program::from_definitions(&schema, ir); let result = validate_server_only_directives(&program); match result { Ok(_) => Ok("OK".to_owned()), Err(errors) => { let mut errs = errors .into_iter() .map(|err| err.print(&sources)) .collect::<Vec<_>>(); errs.sort(); Err(errs.join("\n\n")) } } } else { panic!("Expected exactly one %extensions% section marker.") } }
use graphql_transforms::validate_server_only_directives; use test_schema::test_schema_with_extensions; pub fn transform_fixture(fixture: &Fixture) -> Result<String, String> { let parts: Vec<_> = fixture.content.split("%extensions%").collect();
random_line_split
mod.rs
/* * Copyright (c) Facebook, Inc. and its affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ use common::FileKey; use fixture_tests::Fixture; use fnv::FnvHashMap; use graphql_ir::{build, Program}; use graphql_syntax::parse; use graphql_transforms::validate_server_only_directives; use test_schema::test_schema_with_extensions; pub fn
(fixture: &Fixture) -> Result<String, String> { let parts: Vec<_> = fixture.content.split("%extensions%").collect(); if let [base, extensions] = parts.as_slice() { let file_key = FileKey::new(fixture.file_name); let ast = parse(base, file_key).unwrap(); let schema = test_schema_with_extensions(extensions); let mut sources = FnvHashMap::default(); sources.insert(FileKey::new(fixture.file_name), fixture.content); let ir = build(&schema, &ast.definitions).unwrap(); let program = Program::from_definitions(&schema, ir); let result = validate_server_only_directives(&program); match result { Ok(_) => Ok("OK".to_owned()), Err(errors) => { let mut errs = errors .into_iter() .map(|err| err.print(&sources)) .collect::<Vec<_>>(); errs.sort(); Err(errs.join("\n\n")) } } } else { panic!("Expected exactly one %extensions% section marker.") } }
transform_fixture
identifier_name
cache.rs
// This module defines a common API for caching internal runtime state. // The `thread_local` crate provides an extremely optimized version of this. // However, if the perf-cache feature is disabled, then we drop the // thread_local dependency and instead use a pretty naive caching mechanism // with a mutex. // // Strictly speaking, the CachedGuard isn't necessary for the much more
pub use self::imp::{Cached, CachedGuard}; #[cfg(feature = "perf-cache")] mod imp { use thread_local::CachedThreadLocal; #[derive(Debug)] pub struct Cached<T: Send>(CachedThreadLocal<T>); #[derive(Debug)] pub struct CachedGuard<'a, T: 'a>(&'a T); impl<T: Send> Cached<T> { pub fn new() -> Cached<T> { Cached(CachedThreadLocal::new()) } pub fn get_or(&self, create: impl FnOnce() -> T) -> CachedGuard<T> { CachedGuard(self.0.get_or(|| create())) } } impl<'a, T: Send> CachedGuard<'a, T> { pub fn value(&self) -> &T { self.0 } } } #[cfg(not(feature = "perf-cache"))] mod imp { use std::marker::PhantomData; use std::panic::UnwindSafe; use std::sync::Mutex; #[derive(Debug)] pub struct Cached<T: Send> { stack: Mutex<Vec<T>>, /// When perf-cache is enabled, the thread_local crate is used, and /// its CachedThreadLocal impls Send, Sync and UnwindSafe, but NOT /// RefUnwindSafe. However, a Mutex impls RefUnwindSafe. So in order /// to keep the APIs consistent regardless of whether perf-cache is /// enabled, we force this type to NOT impl RefUnwindSafe too. /// /// Ideally, we should always impl RefUnwindSafe, but it seems a little /// tricky to do that right now. /// /// See also: https://github.com/rust-lang/regex/issues/576 _phantom: PhantomData<Box<dyn Send + Sync + UnwindSafe>>, } #[derive(Debug)] pub struct CachedGuard<'a, T: 'a + Send> { cache: &'a Cached<T>, value: Option<T>, } impl<T: Send> Cached<T> { pub fn new() -> Cached<T> { Cached { stack: Mutex::new(vec![]), _phantom: PhantomData } } pub fn get_or(&self, create: impl FnOnce() -> T) -> CachedGuard<T> { let mut stack = self.stack.lock().unwrap(); match stack.pop() { None => CachedGuard { cache: self, value: Some(create()) }, Some(value) => CachedGuard { cache: self, value: Some(value) }, } } fn put(&self, value: T) { let mut stack = self.stack.lock().unwrap(); stack.push(value); } } impl<'a, T: Send> CachedGuard<'a, T> { pub fn value(&self) -> &T { self.value.as_ref().unwrap() } } impl<'a, T: Send> Drop for CachedGuard<'a, T> { fn drop(&mut self) { if let Some(value) = self.value.take() { self.cache.put(value); } } } }
// flexible thread_local API, but implementing thread_local's API doesn't // seem possible in purely safe code.
random_line_split
cache.rs
// This module defines a common API for caching internal runtime state. // The `thread_local` crate provides an extremely optimized version of this. // However, if the perf-cache feature is disabled, then we drop the // thread_local dependency and instead use a pretty naive caching mechanism // with a mutex. // // Strictly speaking, the CachedGuard isn't necessary for the much more // flexible thread_local API, but implementing thread_local's API doesn't // seem possible in purely safe code. pub use self::imp::{Cached, CachedGuard}; #[cfg(feature = "perf-cache")] mod imp { use thread_local::CachedThreadLocal; #[derive(Debug)] pub struct Cached<T: Send>(CachedThreadLocal<T>); #[derive(Debug)] pub struct CachedGuard<'a, T: 'a>(&'a T); impl<T: Send> Cached<T> { pub fn new() -> Cached<T> { Cached(CachedThreadLocal::new()) } pub fn
(&self, create: impl FnOnce() -> T) -> CachedGuard<T> { CachedGuard(self.0.get_or(|| create())) } } impl<'a, T: Send> CachedGuard<'a, T> { pub fn value(&self) -> &T { self.0 } } } #[cfg(not(feature = "perf-cache"))] mod imp { use std::marker::PhantomData; use std::panic::UnwindSafe; use std::sync::Mutex; #[derive(Debug)] pub struct Cached<T: Send> { stack: Mutex<Vec<T>>, /// When perf-cache is enabled, the thread_local crate is used, and /// its CachedThreadLocal impls Send, Sync and UnwindSafe, but NOT /// RefUnwindSafe. However, a Mutex impls RefUnwindSafe. So in order /// to keep the APIs consistent regardless of whether perf-cache is /// enabled, we force this type to NOT impl RefUnwindSafe too. /// /// Ideally, we should always impl RefUnwindSafe, but it seems a little /// tricky to do that right now. /// /// See also: https://github.com/rust-lang/regex/issues/576 _phantom: PhantomData<Box<dyn Send + Sync + UnwindSafe>>, } #[derive(Debug)] pub struct CachedGuard<'a, T: 'a + Send> { cache: &'a Cached<T>, value: Option<T>, } impl<T: Send> Cached<T> { pub fn new() -> Cached<T> { Cached { stack: Mutex::new(vec![]), _phantom: PhantomData } } pub fn get_or(&self, create: impl FnOnce() -> T) -> CachedGuard<T> { let mut stack = self.stack.lock().unwrap(); match stack.pop() { None => CachedGuard { cache: self, value: Some(create()) }, Some(value) => CachedGuard { cache: self, value: Some(value) }, } } fn put(&self, value: T) { let mut stack = self.stack.lock().unwrap(); stack.push(value); } } impl<'a, T: Send> CachedGuard<'a, T> { pub fn value(&self) -> &T { self.value.as_ref().unwrap() } } impl<'a, T: Send> Drop for CachedGuard<'a, T> { fn drop(&mut self) { if let Some(value) = self.value.take() { self.cache.put(value); } } } }
get_or
identifier_name
cache.rs
// This module defines a common API for caching internal runtime state. // The `thread_local` crate provides an extremely optimized version of this. // However, if the perf-cache feature is disabled, then we drop the // thread_local dependency and instead use a pretty naive caching mechanism // with a mutex. // // Strictly speaking, the CachedGuard isn't necessary for the much more // flexible thread_local API, but implementing thread_local's API doesn't // seem possible in purely safe code. pub use self::imp::{Cached, CachedGuard}; #[cfg(feature = "perf-cache")] mod imp { use thread_local::CachedThreadLocal; #[derive(Debug)] pub struct Cached<T: Send>(CachedThreadLocal<T>); #[derive(Debug)] pub struct CachedGuard<'a, T: 'a>(&'a T); impl<T: Send> Cached<T> { pub fn new() -> Cached<T>
pub fn get_or(&self, create: impl FnOnce() -> T) -> CachedGuard<T> { CachedGuard(self.0.get_or(|| create())) } } impl<'a, T: Send> CachedGuard<'a, T> { pub fn value(&self) -> &T { self.0 } } } #[cfg(not(feature = "perf-cache"))] mod imp { use std::marker::PhantomData; use std::panic::UnwindSafe; use std::sync::Mutex; #[derive(Debug)] pub struct Cached<T: Send> { stack: Mutex<Vec<T>>, /// When perf-cache is enabled, the thread_local crate is used, and /// its CachedThreadLocal impls Send, Sync and UnwindSafe, but NOT /// RefUnwindSafe. However, a Mutex impls RefUnwindSafe. So in order /// to keep the APIs consistent regardless of whether perf-cache is /// enabled, we force this type to NOT impl RefUnwindSafe too. /// /// Ideally, we should always impl RefUnwindSafe, but it seems a little /// tricky to do that right now. /// /// See also: https://github.com/rust-lang/regex/issues/576 _phantom: PhantomData<Box<dyn Send + Sync + UnwindSafe>>, } #[derive(Debug)] pub struct CachedGuard<'a, T: 'a + Send> { cache: &'a Cached<T>, value: Option<T>, } impl<T: Send> Cached<T> { pub fn new() -> Cached<T> { Cached { stack: Mutex::new(vec![]), _phantom: PhantomData } } pub fn get_or(&self, create: impl FnOnce() -> T) -> CachedGuard<T> { let mut stack = self.stack.lock().unwrap(); match stack.pop() { None => CachedGuard { cache: self, value: Some(create()) }, Some(value) => CachedGuard { cache: self, value: Some(value) }, } } fn put(&self, value: T) { let mut stack = self.stack.lock().unwrap(); stack.push(value); } } impl<'a, T: Send> CachedGuard<'a, T> { pub fn value(&self) -> &T { self.value.as_ref().unwrap() } } impl<'a, T: Send> Drop for CachedGuard<'a, T> { fn drop(&mut self) { if let Some(value) = self.value.take() { self.cache.put(value); } } } }
{ Cached(CachedThreadLocal::new()) }
identifier_body
cache.rs
// This module defines a common API for caching internal runtime state. // The `thread_local` crate provides an extremely optimized version of this. // However, if the perf-cache feature is disabled, then we drop the // thread_local dependency and instead use a pretty naive caching mechanism // with a mutex. // // Strictly speaking, the CachedGuard isn't necessary for the much more // flexible thread_local API, but implementing thread_local's API doesn't // seem possible in purely safe code. pub use self::imp::{Cached, CachedGuard}; #[cfg(feature = "perf-cache")] mod imp { use thread_local::CachedThreadLocal; #[derive(Debug)] pub struct Cached<T: Send>(CachedThreadLocal<T>); #[derive(Debug)] pub struct CachedGuard<'a, T: 'a>(&'a T); impl<T: Send> Cached<T> { pub fn new() -> Cached<T> { Cached(CachedThreadLocal::new()) } pub fn get_or(&self, create: impl FnOnce() -> T) -> CachedGuard<T> { CachedGuard(self.0.get_or(|| create())) } } impl<'a, T: Send> CachedGuard<'a, T> { pub fn value(&self) -> &T { self.0 } } } #[cfg(not(feature = "perf-cache"))] mod imp { use std::marker::PhantomData; use std::panic::UnwindSafe; use std::sync::Mutex; #[derive(Debug)] pub struct Cached<T: Send> { stack: Mutex<Vec<T>>, /// When perf-cache is enabled, the thread_local crate is used, and /// its CachedThreadLocal impls Send, Sync and UnwindSafe, but NOT /// RefUnwindSafe. However, a Mutex impls RefUnwindSafe. So in order /// to keep the APIs consistent regardless of whether perf-cache is /// enabled, we force this type to NOT impl RefUnwindSafe too. /// /// Ideally, we should always impl RefUnwindSafe, but it seems a little /// tricky to do that right now. /// /// See also: https://github.com/rust-lang/regex/issues/576 _phantom: PhantomData<Box<dyn Send + Sync + UnwindSafe>>, } #[derive(Debug)] pub struct CachedGuard<'a, T: 'a + Send> { cache: &'a Cached<T>, value: Option<T>, } impl<T: Send> Cached<T> { pub fn new() -> Cached<T> { Cached { stack: Mutex::new(vec![]), _phantom: PhantomData } } pub fn get_or(&self, create: impl FnOnce() -> T) -> CachedGuard<T> { let mut stack = self.stack.lock().unwrap(); match stack.pop() { None => CachedGuard { cache: self, value: Some(create()) }, Some(value) => CachedGuard { cache: self, value: Some(value) }, } } fn put(&self, value: T) { let mut stack = self.stack.lock().unwrap(); stack.push(value); } } impl<'a, T: Send> CachedGuard<'a, T> { pub fn value(&self) -> &T { self.value.as_ref().unwrap() } } impl<'a, T: Send> Drop for CachedGuard<'a, T> { fn drop(&mut self) { if let Some(value) = self.value.take()
} } }
{ self.cache.put(value); }
conditional_block
font.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/. */ extern mod freetype; use font::{CSSFontWeight, FontHandleMethods, FontMetrics, FontTableMethods}; use font::{FontTableTag, FractionalPixel, SpecifiedFontStyle, UsedFontStyle, FontWeight100}; use font::{FontWeight200, FontWeight300, FontWeight400, FontWeight500, FontWeight600}; use font::{FontWeight700, FontWeight800, FontWeight900}; use servo_util::geometry::Au; use servo_util::geometry; use platform::font_context::FontContextHandle; use text::glyph::GlyphIndex; use text::util::{float_to_fixed, fixed_to_float}; use freetype::freetype::{FT_Get_Char_Index, FT_Get_Postscript_Name}; use freetype::freetype::{FT_Load_Glyph, FT_Set_Char_Size}; use freetype::freetype::{FT_New_Face, FT_Get_Sfnt_Table}; use freetype::freetype::{FT_New_Memory_Face, FT_Done_Face}; use freetype::freetype::{FTErrorMethods, FT_F26Dot6, FT_Face, FT_FaceRec}; use freetype::freetype::{FT_GlyphSlot, FT_Library, FT_Long, FT_ULong}; use freetype::freetype::{FT_STYLE_FLAG_ITALIC, FT_STYLE_FLAG_BOLD}; use freetype::freetype::{FT_SizeRec, FT_UInt, FT_Size_Metrics}; use freetype::freetype::{ft_sfnt_os2}; use freetype::tt_os2::TT_OS2; use std::cast; use std::ptr; use std::str; fn float_to_fixed_ft(f: float) -> i32 { float_to_fixed(6, f) } fn fixed_to_float_ft(f: i32) -> float { fixed_to_float(6, f) } pub struct FontTable { bogus: () } impl FontTableMethods for FontTable { fn with_buffer(&self, _blk: &fn(*u8, uint))
} enum FontSource { FontSourceMem(~[u8]), FontSourceFile(~str) } pub struct FontHandle { // The font binary. This must stay valid for the lifetime of the font, // if the font is created using FT_Memory_Face. source: FontSource, face: FT_Face, handle: FontContextHandle } #[unsafe_destructor] impl Drop for FontHandle { #[fixed_stack_segment] fn drop(&self) { assert!(self.face.is_not_null()); unsafe { if!FT_Done_Face(self.face).succeeded() { fail!(~"FT_Done_Face failed"); } } } } impl FontHandleMethods for FontHandle { fn new_from_buffer(fctx: &FontContextHandle, buf: ~[u8], style: &SpecifiedFontStyle) -> Result<FontHandle, ()> { let ft_ctx: FT_Library = fctx.ctx.ctx; if ft_ctx.is_null() { return Err(()); } let face_result = do buf.as_imm_buf |bytes: *u8, len: uint| { create_face_from_buffer(ft_ctx, bytes, len, style.pt_size) }; // TODO: this could be more simply written as result::chain // and moving buf into the struct ctor, but cant' move out of // captured binding. return match face_result { Ok(face) => { let handle = FontHandle { face: face, source: FontSourceMem(buf), handle: *fctx }; Ok(handle) } Err(()) => Err(()) }; #[fixed_stack_segment] fn create_face_from_buffer(lib: FT_Library, cbuf: *u8, cbuflen: uint, pt_size: float) -> Result<FT_Face, ()> { unsafe { let mut face: FT_Face = ptr::null(); let face_index = 0 as FT_Long; let result = FT_New_Memory_Face(lib, cbuf, cbuflen as FT_Long, face_index, ptr::to_mut_unsafe_ptr(&mut face)); if!result.succeeded() || face.is_null() { return Err(()); } if FontHandle::set_char_size(face, pt_size).is_ok() { Ok(face) } else { Err(()) } } } } // an identifier usable by FontContextHandle to recreate this FontHandle. fn face_identifier(&self) -> ~str { /* FT_Get_Postscript_Name seems like a better choice here, but it doesn't give usable results for fontconfig when deserializing. */ unsafe { str::raw::from_c_str((*self.face).family_name) } } fn family_name(&self) -> ~str { unsafe { str::raw::from_c_str((*self.face).family_name) } } #[fixed_stack_segment] fn face_name(&self) -> ~str { unsafe { str::raw::from_c_str(FT_Get_Postscript_Name(self.face)) } } fn is_italic(&self) -> bool { unsafe { (*self.face).style_flags & FT_STYLE_FLAG_ITALIC!= 0 } } #[fixed_stack_segment] fn boldness(&self) -> CSSFontWeight { let default_weight = FontWeight400; if unsafe { (*self.face).style_flags & FT_STYLE_FLAG_BOLD == 0 } { default_weight } else { unsafe { let os2 = FT_Get_Sfnt_Table(self.face, ft_sfnt_os2) as *TT_OS2; let valid = os2.is_not_null() && (*os2).version!= 0xffff; if valid { let weight =(*os2).usWeightClass; match weight { 1 | 100..199 => FontWeight100, 2 | 200..299 => FontWeight200, 3 | 300..399 => FontWeight300, 4 | 400..499 => FontWeight400, 5 | 500..599 => FontWeight500, 6 | 600..699 => FontWeight600, 7 | 700..799 => FontWeight700, 8 | 800..899 => FontWeight800, 9 | 900..999 => FontWeight900, _ => default_weight } } else { default_weight } } } } fn clone_with_style(&self, fctx: &FontContextHandle, style: &UsedFontStyle) -> Result<FontHandle, ()> { match self.source { FontSourceMem(ref buf) => { FontHandleMethods::new_from_buffer(fctx, buf.clone(), style) } FontSourceFile(ref file) => { FontHandle::new_from_file(fctx, (*file).clone(), style) } } } #[fixed_stack_segment] fn glyph_index(&self, codepoint: char) -> Option<GlyphIndex> { assert!(self.face.is_not_null()); unsafe { let idx = FT_Get_Char_Index(self.face, codepoint as FT_ULong); return if idx!= 0 as FT_UInt { Some(idx as GlyphIndex) } else { debug!("Invalid codepoint: %?", codepoint); None }; } } #[fixed_stack_segment] fn glyph_h_advance(&self, glyph: GlyphIndex) -> Option<FractionalPixel> { assert!(self.face.is_not_null()); unsafe { let res = FT_Load_Glyph(self.face, glyph as FT_UInt, 0); if res.succeeded() { let void_glyph = (*self.face).glyph; let slot: FT_GlyphSlot = cast::transmute(void_glyph); assert!(slot.is_not_null()); debug!("metrics: %?", (*slot).metrics); let advance = (*slot).metrics.horiAdvance; debug!("h_advance for %? is %?", glyph, advance); let advance = advance as i32; return Some(fixed_to_float_ft(advance) as FractionalPixel); } else { debug!("Unable to load glyph %?. reason: %?", glyph, res); return None; } } } #[fixed_stack_segment] fn get_metrics(&self) -> FontMetrics { /* TODO(Issue #76): complete me */ let face = self.get_face_rec(); let underline_size = self.font_units_to_au(face.underline_thickness as float); let underline_offset = self.font_units_to_au(face.underline_position as float); let em_size = self.font_units_to_au(face.units_per_EM as float); let ascent = self.font_units_to_au(face.ascender as float); let descent = self.font_units_to_au(face.descender as float); let max_advance = self.font_units_to_au(face.max_advance_width as float); let mut strikeout_size = geometry::from_pt(0.0); let mut strikeout_offset = geometry::from_pt(0.0); let mut x_height = geometry::from_pt(0.0); unsafe { let os2 = FT_Get_Sfnt_Table(face, ft_sfnt_os2) as *TT_OS2; let valid = os2.is_not_null() && (*os2).version!= 0xffff; if valid { strikeout_size = self.font_units_to_au((*os2).yStrikeoutSize as float); strikeout_offset = self.font_units_to_au((*os2).yStrikeoutPosition as float); x_height = self.font_units_to_au((*os2).sxHeight as float); } } return FontMetrics { underline_size: underline_size, underline_offset: underline_offset, strikeout_size: strikeout_size, strikeout_offset: strikeout_offset, leading: geometry::from_pt(0.0), //FIXME x_height: x_height, em_size: em_size, ascent: ascent, descent: -descent, // linux font's seem to use the opposite sign from mac max_advance: max_advance } } fn get_table_for_tag(&self, _: FontTableTag) -> Option<FontTable> { None } } impl<'self> FontHandle { #[fixed_stack_segment] fn set_char_size(face: FT_Face, pt_size: float) -> Result<(), ()>{ let char_width = float_to_fixed_ft(pt_size) as FT_F26Dot6; let char_height = float_to_fixed_ft(pt_size) as FT_F26Dot6; let h_dpi = 72; let v_dpi = 72; unsafe { let result = FT_Set_Char_Size(face, char_width, char_height, h_dpi, v_dpi); if result.succeeded() { Ok(()) } else { Err(()) } } } #[fixed_stack_segment] pub fn new_from_file(fctx: &FontContextHandle, file: ~str, style: &SpecifiedFontStyle) -> Result<FontHandle, ()> { unsafe { let ft_ctx: FT_Library = fctx.ctx.ctx; if ft_ctx.is_null() { return Err(()); } let mut face: FT_Face = ptr::null(); let face_index = 0 as FT_Long; do file.to_c_str().with_ref |file_str| { FT_New_Face(ft_ctx, file_str, face_index, ptr::to_mut_unsafe_ptr(&mut face)); } if face.is_null() { return Err(()); } if FontHandle::set_char_size(face, style.pt_size).is_ok() { Ok(FontHandle { source: FontSourceFile(file), face: face, handle: *fctx }) } else { Err(()) } } } #[fixed_stack_segment] pub fn new_from_file_unstyled(fctx: &FontContextHandle, file: ~str) -> Result<FontHandle, ()> { unsafe { let ft_ctx: FT_Library = fctx.ctx.ctx; if ft_ctx.is_null() { return Err(()); } let mut face: FT_Face = ptr::null(); let face_index = 0 as FT_Long; do file.to_c_str().with_ref |file_str| { FT_New_Face(ft_ctx, file_str, face_index, ptr::to_mut_unsafe_ptr(&mut face)); } if face.is_null() { return Err(()); } Ok(FontHandle { source: FontSourceFile(file), face: face, handle: *fctx }) } } fn get_face_rec(&'self self) -> &'self FT_FaceRec { unsafe { &(*self.face) } } fn font_units_to_au(&self, value: float) -> Au { let face = self.get_face_rec(); // face.size is a *c_void in the bindings, presumably to avoid // recursive structural types let size: &FT_SizeRec = unsafe { cast::transmute(&(*face.size)) }; let metrics: &FT_Size_Metrics = &(*size).metrics; let em_size = face.units_per_EM as float; let x_scale = (metrics.x_ppem as float) / em_size as float; // If this isn't true then we're scaling one of the axes wrong assert!(metrics.x_ppem == metrics.y_ppem); return geometry::from_frac_px(value * x_scale); } }
{ fail!() }
identifier_body
font.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/. */ extern mod freetype; use font::{CSSFontWeight, FontHandleMethods, FontMetrics, FontTableMethods}; use font::{FontTableTag, FractionalPixel, SpecifiedFontStyle, UsedFontStyle, FontWeight100}; use font::{FontWeight200, FontWeight300, FontWeight400, FontWeight500, FontWeight600}; use font::{FontWeight700, FontWeight800, FontWeight900}; use servo_util::geometry::Au; use servo_util::geometry; use platform::font_context::FontContextHandle; use text::glyph::GlyphIndex; use text::util::{float_to_fixed, fixed_to_float}; use freetype::freetype::{FT_Get_Char_Index, FT_Get_Postscript_Name}; use freetype::freetype::{FT_Load_Glyph, FT_Set_Char_Size}; use freetype::freetype::{FT_New_Face, FT_Get_Sfnt_Table}; use freetype::freetype::{FT_New_Memory_Face, FT_Done_Face}; use freetype::freetype::{FTErrorMethods, FT_F26Dot6, FT_Face, FT_FaceRec}; use freetype::freetype::{FT_GlyphSlot, FT_Library, FT_Long, FT_ULong}; use freetype::freetype::{FT_STYLE_FLAG_ITALIC, FT_STYLE_FLAG_BOLD}; use freetype::freetype::{FT_SizeRec, FT_UInt, FT_Size_Metrics}; use freetype::freetype::{ft_sfnt_os2}; use freetype::tt_os2::TT_OS2; use std::cast; use std::ptr; use std::str; fn float_to_fixed_ft(f: float) -> i32 { float_to_fixed(6, f) } fn fixed_to_float_ft(f: i32) -> float { fixed_to_float(6, f) } pub struct FontTable { bogus: () } impl FontTableMethods for FontTable { fn with_buffer(&self, _blk: &fn(*u8, uint)) { fail!() } } enum FontSource { FontSourceMem(~[u8]), FontSourceFile(~str) } pub struct FontHandle { // The font binary. This must stay valid for the lifetime of the font, // if the font is created using FT_Memory_Face. source: FontSource, face: FT_Face, handle: FontContextHandle } #[unsafe_destructor] impl Drop for FontHandle { #[fixed_stack_segment] fn drop(&self) { assert!(self.face.is_not_null()); unsafe { if!FT_Done_Face(self.face).succeeded() { fail!(~"FT_Done_Face failed"); } } } } impl FontHandleMethods for FontHandle { fn new_from_buffer(fctx: &FontContextHandle, buf: ~[u8], style: &SpecifiedFontStyle) -> Result<FontHandle, ()> { let ft_ctx: FT_Library = fctx.ctx.ctx; if ft_ctx.is_null() { return Err(()); } let face_result = do buf.as_imm_buf |bytes: *u8, len: uint| { create_face_from_buffer(ft_ctx, bytes, len, style.pt_size) }; // TODO: this could be more simply written as result::chain // and moving buf into the struct ctor, but cant' move out of // captured binding. return match face_result { Ok(face) => { let handle = FontHandle { face: face, source: FontSourceMem(buf), handle: *fctx }; Ok(handle) } Err(()) => Err(()) }; #[fixed_stack_segment] fn create_face_from_buffer(lib: FT_Library, cbuf: *u8, cbuflen: uint, pt_size: float) -> Result<FT_Face, ()> { unsafe { let mut face: FT_Face = ptr::null(); let face_index = 0 as FT_Long; let result = FT_New_Memory_Face(lib, cbuf, cbuflen as FT_Long, face_index, ptr::to_mut_unsafe_ptr(&mut face)); if!result.succeeded() || face.is_null() { return Err(()); } if FontHandle::set_char_size(face, pt_size).is_ok() { Ok(face) } else { Err(()) } } } } // an identifier usable by FontContextHandle to recreate this FontHandle. fn face_identifier(&self) -> ~str { /* FT_Get_Postscript_Name seems like a better choice here, but it doesn't give usable results for fontconfig when deserializing. */ unsafe { str::raw::from_c_str((*self.face).family_name) } } fn family_name(&self) -> ~str { unsafe { str::raw::from_c_str((*self.face).family_name) } } #[fixed_stack_segment] fn face_name(&self) -> ~str { unsafe { str::raw::from_c_str(FT_Get_Postscript_Name(self.face)) } } fn is_italic(&self) -> bool { unsafe { (*self.face).style_flags & FT_STYLE_FLAG_ITALIC!= 0 } } #[fixed_stack_segment] fn boldness(&self) -> CSSFontWeight { let default_weight = FontWeight400; if unsafe { (*self.face).style_flags & FT_STYLE_FLAG_BOLD == 0 } { default_weight } else { unsafe { let os2 = FT_Get_Sfnt_Table(self.face, ft_sfnt_os2) as *TT_OS2; let valid = os2.is_not_null() && (*os2).version!= 0xffff; if valid { let weight =(*os2).usWeightClass; match weight { 1 | 100..199 => FontWeight100, 2 | 200..299 => FontWeight200, 3 | 300..399 => FontWeight300, 4 | 400..499 => FontWeight400, 5 | 500..599 => FontWeight500, 6 | 600..699 => FontWeight600, 7 | 700..799 => FontWeight700, 8 | 800..899 => FontWeight800, 9 | 900..999 => FontWeight900, _ => default_weight } } else { default_weight } } } } fn
(&self, fctx: &FontContextHandle, style: &UsedFontStyle) -> Result<FontHandle, ()> { match self.source { FontSourceMem(ref buf) => { FontHandleMethods::new_from_buffer(fctx, buf.clone(), style) } FontSourceFile(ref file) => { FontHandle::new_from_file(fctx, (*file).clone(), style) } } } #[fixed_stack_segment] fn glyph_index(&self, codepoint: char) -> Option<GlyphIndex> { assert!(self.face.is_not_null()); unsafe { let idx = FT_Get_Char_Index(self.face, codepoint as FT_ULong); return if idx!= 0 as FT_UInt { Some(idx as GlyphIndex) } else { debug!("Invalid codepoint: %?", codepoint); None }; } } #[fixed_stack_segment] fn glyph_h_advance(&self, glyph: GlyphIndex) -> Option<FractionalPixel> { assert!(self.face.is_not_null()); unsafe { let res = FT_Load_Glyph(self.face, glyph as FT_UInt, 0); if res.succeeded() { let void_glyph = (*self.face).glyph; let slot: FT_GlyphSlot = cast::transmute(void_glyph); assert!(slot.is_not_null()); debug!("metrics: %?", (*slot).metrics); let advance = (*slot).metrics.horiAdvance; debug!("h_advance for %? is %?", glyph, advance); let advance = advance as i32; return Some(fixed_to_float_ft(advance) as FractionalPixel); } else { debug!("Unable to load glyph %?. reason: %?", glyph, res); return None; } } } #[fixed_stack_segment] fn get_metrics(&self) -> FontMetrics { /* TODO(Issue #76): complete me */ let face = self.get_face_rec(); let underline_size = self.font_units_to_au(face.underline_thickness as float); let underline_offset = self.font_units_to_au(face.underline_position as float); let em_size = self.font_units_to_au(face.units_per_EM as float); let ascent = self.font_units_to_au(face.ascender as float); let descent = self.font_units_to_au(face.descender as float); let max_advance = self.font_units_to_au(face.max_advance_width as float); let mut strikeout_size = geometry::from_pt(0.0); let mut strikeout_offset = geometry::from_pt(0.0); let mut x_height = geometry::from_pt(0.0); unsafe { let os2 = FT_Get_Sfnt_Table(face, ft_sfnt_os2) as *TT_OS2; let valid = os2.is_not_null() && (*os2).version!= 0xffff; if valid { strikeout_size = self.font_units_to_au((*os2).yStrikeoutSize as float); strikeout_offset = self.font_units_to_au((*os2).yStrikeoutPosition as float); x_height = self.font_units_to_au((*os2).sxHeight as float); } } return FontMetrics { underline_size: underline_size, underline_offset: underline_offset, strikeout_size: strikeout_size, strikeout_offset: strikeout_offset, leading: geometry::from_pt(0.0), //FIXME x_height: x_height, em_size: em_size, ascent: ascent, descent: -descent, // linux font's seem to use the opposite sign from mac max_advance: max_advance } } fn get_table_for_tag(&self, _: FontTableTag) -> Option<FontTable> { None } } impl<'self> FontHandle { #[fixed_stack_segment] fn set_char_size(face: FT_Face, pt_size: float) -> Result<(), ()>{ let char_width = float_to_fixed_ft(pt_size) as FT_F26Dot6; let char_height = float_to_fixed_ft(pt_size) as FT_F26Dot6; let h_dpi = 72; let v_dpi = 72; unsafe { let result = FT_Set_Char_Size(face, char_width, char_height, h_dpi, v_dpi); if result.succeeded() { Ok(()) } else { Err(()) } } } #[fixed_stack_segment] pub fn new_from_file(fctx: &FontContextHandle, file: ~str, style: &SpecifiedFontStyle) -> Result<FontHandle, ()> { unsafe { let ft_ctx: FT_Library = fctx.ctx.ctx; if ft_ctx.is_null() { return Err(()); } let mut face: FT_Face = ptr::null(); let face_index = 0 as FT_Long; do file.to_c_str().with_ref |file_str| { FT_New_Face(ft_ctx, file_str, face_index, ptr::to_mut_unsafe_ptr(&mut face)); } if face.is_null() { return Err(()); } if FontHandle::set_char_size(face, style.pt_size).is_ok() { Ok(FontHandle { source: FontSourceFile(file), face: face, handle: *fctx }) } else { Err(()) } } } #[fixed_stack_segment] pub fn new_from_file_unstyled(fctx: &FontContextHandle, file: ~str) -> Result<FontHandle, ()> { unsafe { let ft_ctx: FT_Library = fctx.ctx.ctx; if ft_ctx.is_null() { return Err(()); } let mut face: FT_Face = ptr::null(); let face_index = 0 as FT_Long; do file.to_c_str().with_ref |file_str| { FT_New_Face(ft_ctx, file_str, face_index, ptr::to_mut_unsafe_ptr(&mut face)); } if face.is_null() { return Err(()); } Ok(FontHandle { source: FontSourceFile(file), face: face, handle: *fctx }) } } fn get_face_rec(&'self self) -> &'self FT_FaceRec { unsafe { &(*self.face) } } fn font_units_to_au(&self, value: float) -> Au { let face = self.get_face_rec(); // face.size is a *c_void in the bindings, presumably to avoid // recursive structural types let size: &FT_SizeRec = unsafe { cast::transmute(&(*face.size)) }; let metrics: &FT_Size_Metrics = &(*size).metrics; let em_size = face.units_per_EM as float; let x_scale = (metrics.x_ppem as float) / em_size as float; // If this isn't true then we're scaling one of the axes wrong assert!(metrics.x_ppem == metrics.y_ppem); return geometry::from_frac_px(value * x_scale); } }
clone_with_style
identifier_name
font.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/. */ extern mod freetype; use font::{CSSFontWeight, FontHandleMethods, FontMetrics, FontTableMethods}; use font::{FontTableTag, FractionalPixel, SpecifiedFontStyle, UsedFontStyle, FontWeight100}; use font::{FontWeight200, FontWeight300, FontWeight400, FontWeight500, FontWeight600}; use font::{FontWeight700, FontWeight800, FontWeight900}; use servo_util::geometry::Au; use servo_util::geometry; use platform::font_context::FontContextHandle; use text::glyph::GlyphIndex; use text::util::{float_to_fixed, fixed_to_float}; use freetype::freetype::{FT_Get_Char_Index, FT_Get_Postscript_Name}; use freetype::freetype::{FT_Load_Glyph, FT_Set_Char_Size}; use freetype::freetype::{FT_New_Face, FT_Get_Sfnt_Table}; use freetype::freetype::{FT_New_Memory_Face, FT_Done_Face}; use freetype::freetype::{FTErrorMethods, FT_F26Dot6, FT_Face, FT_FaceRec}; use freetype::freetype::{FT_GlyphSlot, FT_Library, FT_Long, FT_ULong}; use freetype::freetype::{FT_STYLE_FLAG_ITALIC, FT_STYLE_FLAG_BOLD}; use freetype::freetype::{FT_SizeRec, FT_UInt, FT_Size_Metrics}; use freetype::freetype::{ft_sfnt_os2}; use freetype::tt_os2::TT_OS2; use std::cast; use std::ptr; use std::str; fn float_to_fixed_ft(f: float) -> i32 { float_to_fixed(6, f) } fn fixed_to_float_ft(f: i32) -> float { fixed_to_float(6, f) } pub struct FontTable { bogus: () } impl FontTableMethods for FontTable { fn with_buffer(&self, _blk: &fn(*u8, uint)) { fail!() } } enum FontSource { FontSourceMem(~[u8]), FontSourceFile(~str) } pub struct FontHandle { // The font binary. This must stay valid for the lifetime of the font, // if the font is created using FT_Memory_Face. source: FontSource, face: FT_Face, handle: FontContextHandle } #[unsafe_destructor] impl Drop for FontHandle { #[fixed_stack_segment] fn drop(&self) { assert!(self.face.is_not_null()); unsafe { if!FT_Done_Face(self.face).succeeded() { fail!(~"FT_Done_Face failed"); } } } } impl FontHandleMethods for FontHandle { fn new_from_buffer(fctx: &FontContextHandle, buf: ~[u8], style: &SpecifiedFontStyle) -> Result<FontHandle, ()> { let ft_ctx: FT_Library = fctx.ctx.ctx; if ft_ctx.is_null() { return Err(()); } let face_result = do buf.as_imm_buf |bytes: *u8, len: uint| { create_face_from_buffer(ft_ctx, bytes, len, style.pt_size) }; // TODO: this could be more simply written as result::chain // and moving buf into the struct ctor, but cant' move out of // captured binding. return match face_result { Ok(face) => { let handle = FontHandle { face: face, source: FontSourceMem(buf), handle: *fctx }; Ok(handle) } Err(()) => Err(()) }; #[fixed_stack_segment] fn create_face_from_buffer(lib: FT_Library, cbuf: *u8, cbuflen: uint, pt_size: float) -> Result<FT_Face, ()> { unsafe { let mut face: FT_Face = ptr::null(); let face_index = 0 as FT_Long; let result = FT_New_Memory_Face(lib, cbuf, cbuflen as FT_Long, face_index, ptr::to_mut_unsafe_ptr(&mut face)); if!result.succeeded() || face.is_null() { return Err(()); } if FontHandle::set_char_size(face, pt_size).is_ok() { Ok(face) } else { Err(()) } } } } // an identifier usable by FontContextHandle to recreate this FontHandle. fn face_identifier(&self) -> ~str { /* FT_Get_Postscript_Name seems like a better choice here, but it doesn't give usable results for fontconfig when deserializing. */ unsafe { str::raw::from_c_str((*self.face).family_name) } } fn family_name(&self) -> ~str { unsafe { str::raw::from_c_str((*self.face).family_name) } } #[fixed_stack_segment] fn face_name(&self) -> ~str { unsafe { str::raw::from_c_str(FT_Get_Postscript_Name(self.face)) } } fn is_italic(&self) -> bool { unsafe { (*self.face).style_flags & FT_STYLE_FLAG_ITALIC!= 0 } } #[fixed_stack_segment] fn boldness(&self) -> CSSFontWeight { let default_weight = FontWeight400; if unsafe { (*self.face).style_flags & FT_STYLE_FLAG_BOLD == 0 } { default_weight } else { unsafe { let os2 = FT_Get_Sfnt_Table(self.face, ft_sfnt_os2) as *TT_OS2; let valid = os2.is_not_null() && (*os2).version!= 0xffff; if valid { let weight =(*os2).usWeightClass; match weight { 1 | 100..199 => FontWeight100, 2 | 200..299 => FontWeight200, 3 | 300..399 => FontWeight300, 4 | 400..499 => FontWeight400, 5 | 500..599 => FontWeight500, 6 | 600..699 => FontWeight600, 7 | 700..799 => FontWeight700, 8 | 800..899 => FontWeight800, 9 | 900..999 => FontWeight900, _ => default_weight } } else { default_weight } } } } fn clone_with_style(&self, fctx: &FontContextHandle, style: &UsedFontStyle) -> Result<FontHandle, ()> { match self.source { FontSourceMem(ref buf) => { FontHandleMethods::new_from_buffer(fctx, buf.clone(), style) } FontSourceFile(ref file) => { FontHandle::new_from_file(fctx, (*file).clone(), style) } } } #[fixed_stack_segment] fn glyph_index(&self, codepoint: char) -> Option<GlyphIndex> { assert!(self.face.is_not_null()); unsafe { let idx = FT_Get_Char_Index(self.face, codepoint as FT_ULong); return if idx!= 0 as FT_UInt { Some(idx as GlyphIndex) } else { debug!("Invalid codepoint: %?", codepoint); None }; } } #[fixed_stack_segment] fn glyph_h_advance(&self, glyph: GlyphIndex) -> Option<FractionalPixel> { assert!(self.face.is_not_null()); unsafe { let res = FT_Load_Glyph(self.face, glyph as FT_UInt, 0); if res.succeeded() { let void_glyph = (*self.face).glyph; let slot: FT_GlyphSlot = cast::transmute(void_glyph); assert!(slot.is_not_null()); debug!("metrics: %?", (*slot).metrics); let advance = (*slot).metrics.horiAdvance; debug!("h_advance for %? is %?", glyph, advance); let advance = advance as i32; return Some(fixed_to_float_ft(advance) as FractionalPixel); } else { debug!("Unable to load glyph %?. reason: %?", glyph, res); return None; } } } #[fixed_stack_segment] fn get_metrics(&self) -> FontMetrics { /* TODO(Issue #76): complete me */ let face = self.get_face_rec(); let underline_size = self.font_units_to_au(face.underline_thickness as float); let underline_offset = self.font_units_to_au(face.underline_position as float); let em_size = self.font_units_to_au(face.units_per_EM as float); let ascent = self.font_units_to_au(face.ascender as float); let descent = self.font_units_to_au(face.descender as float); let max_advance = self.font_units_to_au(face.max_advance_width as float); let mut strikeout_size = geometry::from_pt(0.0); let mut strikeout_offset = geometry::from_pt(0.0); let mut x_height = geometry::from_pt(0.0); unsafe { let os2 = FT_Get_Sfnt_Table(face, ft_sfnt_os2) as *TT_OS2; let valid = os2.is_not_null() && (*os2).version!= 0xffff; if valid {
} } return FontMetrics { underline_size: underline_size, underline_offset: underline_offset, strikeout_size: strikeout_size, strikeout_offset: strikeout_offset, leading: geometry::from_pt(0.0), //FIXME x_height: x_height, em_size: em_size, ascent: ascent, descent: -descent, // linux font's seem to use the opposite sign from mac max_advance: max_advance } } fn get_table_for_tag(&self, _: FontTableTag) -> Option<FontTable> { None } } impl<'self> FontHandle { #[fixed_stack_segment] fn set_char_size(face: FT_Face, pt_size: float) -> Result<(), ()>{ let char_width = float_to_fixed_ft(pt_size) as FT_F26Dot6; let char_height = float_to_fixed_ft(pt_size) as FT_F26Dot6; let h_dpi = 72; let v_dpi = 72; unsafe { let result = FT_Set_Char_Size(face, char_width, char_height, h_dpi, v_dpi); if result.succeeded() { Ok(()) } else { Err(()) } } } #[fixed_stack_segment] pub fn new_from_file(fctx: &FontContextHandle, file: ~str, style: &SpecifiedFontStyle) -> Result<FontHandle, ()> { unsafe { let ft_ctx: FT_Library = fctx.ctx.ctx; if ft_ctx.is_null() { return Err(()); } let mut face: FT_Face = ptr::null(); let face_index = 0 as FT_Long; do file.to_c_str().with_ref |file_str| { FT_New_Face(ft_ctx, file_str, face_index, ptr::to_mut_unsafe_ptr(&mut face)); } if face.is_null() { return Err(()); } if FontHandle::set_char_size(face, style.pt_size).is_ok() { Ok(FontHandle { source: FontSourceFile(file), face: face, handle: *fctx }) } else { Err(()) } } } #[fixed_stack_segment] pub fn new_from_file_unstyled(fctx: &FontContextHandle, file: ~str) -> Result<FontHandle, ()> { unsafe { let ft_ctx: FT_Library = fctx.ctx.ctx; if ft_ctx.is_null() { return Err(()); } let mut face: FT_Face = ptr::null(); let face_index = 0 as FT_Long; do file.to_c_str().with_ref |file_str| { FT_New_Face(ft_ctx, file_str, face_index, ptr::to_mut_unsafe_ptr(&mut face)); } if face.is_null() { return Err(()); } Ok(FontHandle { source: FontSourceFile(file), face: face, handle: *fctx }) } } fn get_face_rec(&'self self) -> &'self FT_FaceRec { unsafe { &(*self.face) } } fn font_units_to_au(&self, value: float) -> Au { let face = self.get_face_rec(); // face.size is a *c_void in the bindings, presumably to avoid // recursive structural types let size: &FT_SizeRec = unsafe { cast::transmute(&(*face.size)) }; let metrics: &FT_Size_Metrics = &(*size).metrics; let em_size = face.units_per_EM as float; let x_scale = (metrics.x_ppem as float) / em_size as float; // If this isn't true then we're scaling one of the axes wrong assert!(metrics.x_ppem == metrics.y_ppem); return geometry::from_frac_px(value * x_scale); } }
strikeout_size = self.font_units_to_au((*os2).yStrikeoutSize as float); strikeout_offset = self.font_units_to_au((*os2).yStrikeoutPosition as float); x_height = self.font_units_to_au((*os2).sxHeight as float);
random_line_split
font.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/. */ extern mod freetype; use font::{CSSFontWeight, FontHandleMethods, FontMetrics, FontTableMethods}; use font::{FontTableTag, FractionalPixel, SpecifiedFontStyle, UsedFontStyle, FontWeight100}; use font::{FontWeight200, FontWeight300, FontWeight400, FontWeight500, FontWeight600}; use font::{FontWeight700, FontWeight800, FontWeight900}; use servo_util::geometry::Au; use servo_util::geometry; use platform::font_context::FontContextHandle; use text::glyph::GlyphIndex; use text::util::{float_to_fixed, fixed_to_float}; use freetype::freetype::{FT_Get_Char_Index, FT_Get_Postscript_Name}; use freetype::freetype::{FT_Load_Glyph, FT_Set_Char_Size}; use freetype::freetype::{FT_New_Face, FT_Get_Sfnt_Table}; use freetype::freetype::{FT_New_Memory_Face, FT_Done_Face}; use freetype::freetype::{FTErrorMethods, FT_F26Dot6, FT_Face, FT_FaceRec}; use freetype::freetype::{FT_GlyphSlot, FT_Library, FT_Long, FT_ULong}; use freetype::freetype::{FT_STYLE_FLAG_ITALIC, FT_STYLE_FLAG_BOLD}; use freetype::freetype::{FT_SizeRec, FT_UInt, FT_Size_Metrics}; use freetype::freetype::{ft_sfnt_os2}; use freetype::tt_os2::TT_OS2; use std::cast; use std::ptr; use std::str; fn float_to_fixed_ft(f: float) -> i32 { float_to_fixed(6, f) } fn fixed_to_float_ft(f: i32) -> float { fixed_to_float(6, f) } pub struct FontTable { bogus: () } impl FontTableMethods for FontTable { fn with_buffer(&self, _blk: &fn(*u8, uint)) { fail!() } } enum FontSource { FontSourceMem(~[u8]), FontSourceFile(~str) } pub struct FontHandle { // The font binary. This must stay valid for the lifetime of the font, // if the font is created using FT_Memory_Face. source: FontSource, face: FT_Face, handle: FontContextHandle } #[unsafe_destructor] impl Drop for FontHandle { #[fixed_stack_segment] fn drop(&self) { assert!(self.face.is_not_null()); unsafe { if!FT_Done_Face(self.face).succeeded() { fail!(~"FT_Done_Face failed"); } } } } impl FontHandleMethods for FontHandle { fn new_from_buffer(fctx: &FontContextHandle, buf: ~[u8], style: &SpecifiedFontStyle) -> Result<FontHandle, ()> { let ft_ctx: FT_Library = fctx.ctx.ctx; if ft_ctx.is_null() { return Err(()); } let face_result = do buf.as_imm_buf |bytes: *u8, len: uint| { create_face_from_buffer(ft_ctx, bytes, len, style.pt_size) }; // TODO: this could be more simply written as result::chain // and moving buf into the struct ctor, but cant' move out of // captured binding. return match face_result { Ok(face) => { let handle = FontHandle { face: face, source: FontSourceMem(buf), handle: *fctx }; Ok(handle) } Err(()) => Err(()) }; #[fixed_stack_segment] fn create_face_from_buffer(lib: FT_Library, cbuf: *u8, cbuflen: uint, pt_size: float) -> Result<FT_Face, ()> { unsafe { let mut face: FT_Face = ptr::null(); let face_index = 0 as FT_Long; let result = FT_New_Memory_Face(lib, cbuf, cbuflen as FT_Long, face_index, ptr::to_mut_unsafe_ptr(&mut face)); if!result.succeeded() || face.is_null() { return Err(()); } if FontHandle::set_char_size(face, pt_size).is_ok() { Ok(face) } else { Err(()) } } } } // an identifier usable by FontContextHandle to recreate this FontHandle. fn face_identifier(&self) -> ~str { /* FT_Get_Postscript_Name seems like a better choice here, but it doesn't give usable results for fontconfig when deserializing. */ unsafe { str::raw::from_c_str((*self.face).family_name) } } fn family_name(&self) -> ~str { unsafe { str::raw::from_c_str((*self.face).family_name) } } #[fixed_stack_segment] fn face_name(&self) -> ~str { unsafe { str::raw::from_c_str(FT_Get_Postscript_Name(self.face)) } } fn is_italic(&self) -> bool { unsafe { (*self.face).style_flags & FT_STYLE_FLAG_ITALIC!= 0 } } #[fixed_stack_segment] fn boldness(&self) -> CSSFontWeight { let default_weight = FontWeight400; if unsafe { (*self.face).style_flags & FT_STYLE_FLAG_BOLD == 0 } { default_weight } else { unsafe { let os2 = FT_Get_Sfnt_Table(self.face, ft_sfnt_os2) as *TT_OS2; let valid = os2.is_not_null() && (*os2).version!= 0xffff; if valid { let weight =(*os2).usWeightClass; match weight { 1 | 100..199 => FontWeight100, 2 | 200..299 => FontWeight200, 3 | 300..399 => FontWeight300, 4 | 400..499 => FontWeight400, 5 | 500..599 => FontWeight500, 6 | 600..699 => FontWeight600, 7 | 700..799 => FontWeight700, 8 | 800..899 => FontWeight800, 9 | 900..999 => FontWeight900, _ => default_weight } } else
} } } fn clone_with_style(&self, fctx: &FontContextHandle, style: &UsedFontStyle) -> Result<FontHandle, ()> { match self.source { FontSourceMem(ref buf) => { FontHandleMethods::new_from_buffer(fctx, buf.clone(), style) } FontSourceFile(ref file) => { FontHandle::new_from_file(fctx, (*file).clone(), style) } } } #[fixed_stack_segment] fn glyph_index(&self, codepoint: char) -> Option<GlyphIndex> { assert!(self.face.is_not_null()); unsafe { let idx = FT_Get_Char_Index(self.face, codepoint as FT_ULong); return if idx!= 0 as FT_UInt { Some(idx as GlyphIndex) } else { debug!("Invalid codepoint: %?", codepoint); None }; } } #[fixed_stack_segment] fn glyph_h_advance(&self, glyph: GlyphIndex) -> Option<FractionalPixel> { assert!(self.face.is_not_null()); unsafe { let res = FT_Load_Glyph(self.face, glyph as FT_UInt, 0); if res.succeeded() { let void_glyph = (*self.face).glyph; let slot: FT_GlyphSlot = cast::transmute(void_glyph); assert!(slot.is_not_null()); debug!("metrics: %?", (*slot).metrics); let advance = (*slot).metrics.horiAdvance; debug!("h_advance for %? is %?", glyph, advance); let advance = advance as i32; return Some(fixed_to_float_ft(advance) as FractionalPixel); } else { debug!("Unable to load glyph %?. reason: %?", glyph, res); return None; } } } #[fixed_stack_segment] fn get_metrics(&self) -> FontMetrics { /* TODO(Issue #76): complete me */ let face = self.get_face_rec(); let underline_size = self.font_units_to_au(face.underline_thickness as float); let underline_offset = self.font_units_to_au(face.underline_position as float); let em_size = self.font_units_to_au(face.units_per_EM as float); let ascent = self.font_units_to_au(face.ascender as float); let descent = self.font_units_to_au(face.descender as float); let max_advance = self.font_units_to_au(face.max_advance_width as float); let mut strikeout_size = geometry::from_pt(0.0); let mut strikeout_offset = geometry::from_pt(0.0); let mut x_height = geometry::from_pt(0.0); unsafe { let os2 = FT_Get_Sfnt_Table(face, ft_sfnt_os2) as *TT_OS2; let valid = os2.is_not_null() && (*os2).version!= 0xffff; if valid { strikeout_size = self.font_units_to_au((*os2).yStrikeoutSize as float); strikeout_offset = self.font_units_to_au((*os2).yStrikeoutPosition as float); x_height = self.font_units_to_au((*os2).sxHeight as float); } } return FontMetrics { underline_size: underline_size, underline_offset: underline_offset, strikeout_size: strikeout_size, strikeout_offset: strikeout_offset, leading: geometry::from_pt(0.0), //FIXME x_height: x_height, em_size: em_size, ascent: ascent, descent: -descent, // linux font's seem to use the opposite sign from mac max_advance: max_advance } } fn get_table_for_tag(&self, _: FontTableTag) -> Option<FontTable> { None } } impl<'self> FontHandle { #[fixed_stack_segment] fn set_char_size(face: FT_Face, pt_size: float) -> Result<(), ()>{ let char_width = float_to_fixed_ft(pt_size) as FT_F26Dot6; let char_height = float_to_fixed_ft(pt_size) as FT_F26Dot6; let h_dpi = 72; let v_dpi = 72; unsafe { let result = FT_Set_Char_Size(face, char_width, char_height, h_dpi, v_dpi); if result.succeeded() { Ok(()) } else { Err(()) } } } #[fixed_stack_segment] pub fn new_from_file(fctx: &FontContextHandle, file: ~str, style: &SpecifiedFontStyle) -> Result<FontHandle, ()> { unsafe { let ft_ctx: FT_Library = fctx.ctx.ctx; if ft_ctx.is_null() { return Err(()); } let mut face: FT_Face = ptr::null(); let face_index = 0 as FT_Long; do file.to_c_str().with_ref |file_str| { FT_New_Face(ft_ctx, file_str, face_index, ptr::to_mut_unsafe_ptr(&mut face)); } if face.is_null() { return Err(()); } if FontHandle::set_char_size(face, style.pt_size).is_ok() { Ok(FontHandle { source: FontSourceFile(file), face: face, handle: *fctx }) } else { Err(()) } } } #[fixed_stack_segment] pub fn new_from_file_unstyled(fctx: &FontContextHandle, file: ~str) -> Result<FontHandle, ()> { unsafe { let ft_ctx: FT_Library = fctx.ctx.ctx; if ft_ctx.is_null() { return Err(()); } let mut face: FT_Face = ptr::null(); let face_index = 0 as FT_Long; do file.to_c_str().with_ref |file_str| { FT_New_Face(ft_ctx, file_str, face_index, ptr::to_mut_unsafe_ptr(&mut face)); } if face.is_null() { return Err(()); } Ok(FontHandle { source: FontSourceFile(file), face: face, handle: *fctx }) } } fn get_face_rec(&'self self) -> &'self FT_FaceRec { unsafe { &(*self.face) } } fn font_units_to_au(&self, value: float) -> Au { let face = self.get_face_rec(); // face.size is a *c_void in the bindings, presumably to avoid // recursive structural types let size: &FT_SizeRec = unsafe { cast::transmute(&(*face.size)) }; let metrics: &FT_Size_Metrics = &(*size).metrics; let em_size = face.units_per_EM as float; let x_scale = (metrics.x_ppem as float) / em_size as float; // If this isn't true then we're scaling one of the axes wrong assert!(metrics.x_ppem == metrics.y_ppem); return geometry::from_frac_px(value * x_scale); } }
{ default_weight }
conditional_block
move_cell.rs
//! A cell type that can move values into and out of a shared reference. //! //! Behaves like `RefCell<Option<T>>` but optimized for use-cases where temporary or permanent //! ownership is required. use std::cell::UnsafeCell; use std::mem; /// A cell type that can move values into and out of a shared reference. pub struct MoveCell<T>(UnsafeCell<Option<T>>); impl<T> MoveCell<T> { /// Create a new `MoveCell` with no contained value. pub fn new() -> MoveCell<T> { MoveCell(UnsafeCell::new(None)) } /// Create a new `MoveCell` with the given value. pub fn with(val: T) -> MoveCell<T> { MoveCell(UnsafeCell::new(Some(val))) } /// Create a new `MoveCell<T>` around the given `Option<T>`. pub fn from(opt: Option<T>) -> MoveCell<T> { MoveCell(UnsafeCell::new(opt)) } unsafe fn as_mut(&self) -> &mut Option<T> { &mut *self.0.get() } unsafe fn as_ref(&self) -> &Option<T> { & *self.0.get() } /// Place a value into this `MoveCell`, returning the previous value, if present. pub fn put(&self, val: T) -> Option<T> { mem::replace(unsafe { self.as_mut() }, Some(val)) } /// Take the value out of this `MoveCell`, leaving nothing in its place. pub fn take(&self) -> Option<T> { unsafe { self.as_mut().take() } } /// Take the value out of this `MoveCell`, leaving a clone in its place. pub fn clone_inner(&self) -> Option<T> where T: Clone { let inner = self.take(); inner.clone().map(|inner| self.put(inner)); inner } /// Check if this `MoveCell` contains a value or not. pub fn has_value(&self) -> bool { unsafe { self.as_ref().is_some() } } } impl<T> Default for MoveCell<T> { fn default() -> Self
}
{ MoveCell::new() }
identifier_body
move_cell.rs
//! A cell type that can move values into and out of a shared reference. //! //! Behaves like `RefCell<Option<T>>` but optimized for use-cases where temporary or permanent //! ownership is required. use std::cell::UnsafeCell; use std::mem; /// A cell type that can move values into and out of a shared reference. pub struct MoveCell<T>(UnsafeCell<Option<T>>); impl<T> MoveCell<T> { /// Create a new `MoveCell` with no contained value. pub fn new() -> MoveCell<T> { MoveCell(UnsafeCell::new(None)) } /// Create a new `MoveCell` with the given value. pub fn with(val: T) -> MoveCell<T> { MoveCell(UnsafeCell::new(Some(val))) } /// Create a new `MoveCell<T>` around the given `Option<T>`. pub fn from(opt: Option<T>) -> MoveCell<T> { MoveCell(UnsafeCell::new(opt)) } unsafe fn as_mut(&self) -> &mut Option<T> { &mut *self.0.get() } unsafe fn
(&self) -> &Option<T> { & *self.0.get() } /// Place a value into this `MoveCell`, returning the previous value, if present. pub fn put(&self, val: T) -> Option<T> { mem::replace(unsafe { self.as_mut() }, Some(val)) } /// Take the value out of this `MoveCell`, leaving nothing in its place. pub fn take(&self) -> Option<T> { unsafe { self.as_mut().take() } } /// Take the value out of this `MoveCell`, leaving a clone in its place. pub fn clone_inner(&self) -> Option<T> where T: Clone { let inner = self.take(); inner.clone().map(|inner| self.put(inner)); inner } /// Check if this `MoveCell` contains a value or not. pub fn has_value(&self) -> bool { unsafe { self.as_ref().is_some() } } } impl<T> Default for MoveCell<T> { fn default() -> Self { MoveCell::new() } }
as_ref
identifier_name
move_cell.rs
//! A cell type that can move values into and out of a shared reference. //! //! Behaves like `RefCell<Option<T>>` but optimized for use-cases where temporary or permanent //! ownership is required. use std::cell::UnsafeCell; use std::mem; /// A cell type that can move values into and out of a shared reference. pub struct MoveCell<T>(UnsafeCell<Option<T>>); impl<T> MoveCell<T> { /// Create a new `MoveCell` with no contained value. pub fn new() -> MoveCell<T> { MoveCell(UnsafeCell::new(None)) } /// Create a new `MoveCell` with the given value. pub fn with(val: T) -> MoveCell<T> { MoveCell(UnsafeCell::new(Some(val))) } /// Create a new `MoveCell<T>` around the given `Option<T>`. pub fn from(opt: Option<T>) -> MoveCell<T> { MoveCell(UnsafeCell::new(opt)) } unsafe fn as_mut(&self) -> &mut Option<T> {
} unsafe fn as_ref(&self) -> &Option<T> { & *self.0.get() } /// Place a value into this `MoveCell`, returning the previous value, if present. pub fn put(&self, val: T) -> Option<T> { mem::replace(unsafe { self.as_mut() }, Some(val)) } /// Take the value out of this `MoveCell`, leaving nothing in its place. pub fn take(&self) -> Option<T> { unsafe { self.as_mut().take() } } /// Take the value out of this `MoveCell`, leaving a clone in its place. pub fn clone_inner(&self) -> Option<T> where T: Clone { let inner = self.take(); inner.clone().map(|inner| self.put(inner)); inner } /// Check if this `MoveCell` contains a value or not. pub fn has_value(&self) -> bool { unsafe { self.as_ref().is_some() } } } impl<T> Default for MoveCell<T> { fn default() -> Self { MoveCell::new() } }
&mut *self.0.get()
random_line_split
util.rs
use std::fmt; use std::io::{IoErrorKind, IoResult}; #[derive(Copy)] pub struct FormatBytes(pub u64); impl FormatBytes { #[inline] fn to_kb(self) -> f64 { (self.0 as f64) / 1.0e3 } #[inline] fn to_mb(self) -> f64 { (self.0 as f64) / 1.0e6 } #[inline] fn to_gb(self) -> f64 { (self.0 as f64) / 1.0e9 } } impl fmt::String for FormatBytes { fn fmt(&self, fmt: &mut fmt::Formatter) -> Result<(), fmt::Error> { match self.0 { 0... 999 => fmt.write_fmt(format_args!("{} B", self.0)), 1_000... 999_999 => fmt.write_fmt(format_args!("{:.02} KB", self.to_kb())), 1_000_000... 999_999_999 => fmt.write_fmt(format_args!("{:.02} MB", self.to_mb())), _ => fmt.write_fmt(format_args!("{:.02} GB", self.to_gb())), } } } pub fn ignore_timeout<T>(result: IoResult<T>) -> IoResult<Option<T>> { match result { Ok(ok) => Ok(Some(ok)), Err(ref err) if err.kind == IoErrorKind::TimedOut => Ok(None), Err(err) => Err(err), } } pub fn precise_time_ms() -> u64 { use time; time::precise_time_ns() / 1_000_000 } pub struct FormatTime(pub u64, pub u8, pub u8); impl FormatTime { pub fn from_s(s: u64) -> FormatTime { let seconds = (s % 60) as u8; let tot_min = s / 60;
FormatTime(hours, minutes, seconds) } } impl fmt::String for FormatTime { fn fmt(&self, f: &mut fmt::Formatter) -> Result<(), fmt::Error> { f.write_fmt(format_args!("{}:{:02}:{:02}", self.0, self.1, self.2)) } }
let minutes = (tot_min % 60) as u8; let hours = tot_min / 60;
random_line_split
util.rs
use std::fmt; use std::io::{IoErrorKind, IoResult}; #[derive(Copy)] pub struct FormatBytes(pub u64); impl FormatBytes { #[inline] fn to_kb(self) -> f64 { (self.0 as f64) / 1.0e3 } #[inline] fn to_mb(self) -> f64 { (self.0 as f64) / 1.0e6 } #[inline] fn to_gb(self) -> f64 { (self.0 as f64) / 1.0e9 } } impl fmt::String for FormatBytes { fn fmt(&self, fmt: &mut fmt::Formatter) -> Result<(), fmt::Error> { match self.0 { 0... 999 => fmt.write_fmt(format_args!("{} B", self.0)), 1_000... 999_999 => fmt.write_fmt(format_args!("{:.02} KB", self.to_kb())), 1_000_000... 999_999_999 => fmt.write_fmt(format_args!("{:.02} MB", self.to_mb())), _ => fmt.write_fmt(format_args!("{:.02} GB", self.to_gb())), } } } pub fn ignore_timeout<T>(result: IoResult<T>) -> IoResult<Option<T>> { match result { Ok(ok) => Ok(Some(ok)), Err(ref err) if err.kind == IoErrorKind::TimedOut => Ok(None), Err(err) => Err(err), } } pub fn precise_time_ms() -> u64 { use time; time::precise_time_ns() / 1_000_000 } pub struct
(pub u64, pub u8, pub u8); impl FormatTime { pub fn from_s(s: u64) -> FormatTime { let seconds = (s % 60) as u8; let tot_min = s / 60; let minutes = (tot_min % 60) as u8; let hours = tot_min / 60; FormatTime(hours, minutes, seconds) } } impl fmt::String for FormatTime { fn fmt(&self, f: &mut fmt::Formatter) -> Result<(), fmt::Error> { f.write_fmt(format_args!("{}:{:02}:{:02}", self.0, self.1, self.2)) } }
FormatTime
identifier_name
perm.rs
use centrifuge::{Store, Message}; pub struct PermStore<'a> { sequence: usize, position: usize, data: &'a mut [u8] } #[derive(Debug)] pub struct PermMsg<'a> { sequence: usize, data: &'a [u8], } impl <'a> PermStore<'a> { pub fn new(data: &'a mut [u8]) -> Self { PermStore { sequence: 0, position: 0, data: data } } #[inline] fn get_slice(&mut self, from: usize, len: usize) -> &'a mut [u8] { use std::slice::from_raw_parts_mut; let ptr = self.data.as_mut_ptr(); unsafe { from_raw_parts_mut(ptr.offset(from as isize), len) } } #[inline] fn get_slice_from_to(&mut self, from: usize, to: usize) -> &'a mut [u8]
#[inline] fn get_remaining_slice(&mut self) -> &'a mut [u8] { let start = self.position; let end = self.data.len(); self.get_slice_from_to(start, end) } } impl <'a> Message for PermMsg<'a> { fn get_sequence(&self) -> usize { self.sequence } fn get_data(&self) -> &[u8] { self.data } } impl <'a> Store<'a> for PermStore<'a> { type Msg = PermMsg<'a>; fn write<W>(&mut self, writer: W) -> PermMsg<'a> where W: FnOnce(&mut [u8]) -> usize { let start = self.position; self.position += writer(&mut self.get_remaining_slice()); self.sequence += 1; let seq = self.sequence; let pos = self.position; PermMsg { sequence: seq, data: self.get_slice_from_to(start, pos) } } } #[cfg(test)] pub mod test { use centrifuge::*; #[test] pub fn test_perm() { use centrifuge::perm::*; let mut sequence_nums = Vec::<usize>::new(); let mut log = vec![0; 16]; { let mut store = PermStore::new(&mut log); let mut centrifuge = Centrifuge::new(&mut store, |msg| { println!("Message received: {:?}", msg); sequence_nums.push(msg.get_sequence()); }); let data = b"hello"; centrifuge.receive_msg( &data[..] ); let data = b"bye"; centrifuge.receive_msg( &data[..] ); } assert_eq!(&vec![1, 2], &sequence_nums); assert_eq!(&b"hellobye"[..], &log[0..8]); } }
{ self.get_slice(from, to - from) }
identifier_body
perm.rs
use centrifuge::{Store, Message}; pub struct PermStore<'a> { sequence: usize, position: usize, data: &'a mut [u8] } #[derive(Debug)] pub struct PermMsg<'a> { sequence: usize, data: &'a [u8], } impl <'a> PermStore<'a> { pub fn new(data: &'a mut [u8]) -> Self { PermStore { sequence: 0, position: 0, data: data } } #[inline] fn get_slice(&mut self, from: usize, len: usize) -> &'a mut [u8] { use std::slice::from_raw_parts_mut; let ptr = self.data.as_mut_ptr(); unsafe { from_raw_parts_mut(ptr.offset(from as isize), len) } } #[inline] fn get_slice_from_to(&mut self, from: usize, to: usize) -> &'a mut [u8] { self.get_slice(from, to - from) } #[inline] fn get_remaining_slice(&mut self) -> &'a mut [u8] { let start = self.position; let end = self.data.len(); self.get_slice_from_to(start, end) } } impl <'a> Message for PermMsg<'a> { fn get_sequence(&self) -> usize { self.sequence } fn get_data(&self) -> &[u8] { self.data } } impl <'a> Store<'a> for PermStore<'a> { type Msg = PermMsg<'a>; fn write<W>(&mut self, writer: W) -> PermMsg<'a> where W: FnOnce(&mut [u8]) -> usize { let start = self.position; self.position += writer(&mut self.get_remaining_slice());
let pos = self.position; PermMsg { sequence: seq, data: self.get_slice_from_to(start, pos) } } } #[cfg(test)] pub mod test { use centrifuge::*; #[test] pub fn test_perm() { use centrifuge::perm::*; let mut sequence_nums = Vec::<usize>::new(); let mut log = vec![0; 16]; { let mut store = PermStore::new(&mut log); let mut centrifuge = Centrifuge::new(&mut store, |msg| { println!("Message received: {:?}", msg); sequence_nums.push(msg.get_sequence()); }); let data = b"hello"; centrifuge.receive_msg( &data[..] ); let data = b"bye"; centrifuge.receive_msg( &data[..] ); } assert_eq!(&vec![1, 2], &sequence_nums); assert_eq!(&b"hellobye"[..], &log[0..8]); } }
self.sequence += 1; let seq = self.sequence;
random_line_split
perm.rs
use centrifuge::{Store, Message}; pub struct PermStore<'a> { sequence: usize, position: usize, data: &'a mut [u8] } #[derive(Debug)] pub struct PermMsg<'a> { sequence: usize, data: &'a [u8], } impl <'a> PermStore<'a> { pub fn
(data: &'a mut [u8]) -> Self { PermStore { sequence: 0, position: 0, data: data } } #[inline] fn get_slice(&mut self, from: usize, len: usize) -> &'a mut [u8] { use std::slice::from_raw_parts_mut; let ptr = self.data.as_mut_ptr(); unsafe { from_raw_parts_mut(ptr.offset(from as isize), len) } } #[inline] fn get_slice_from_to(&mut self, from: usize, to: usize) -> &'a mut [u8] { self.get_slice(from, to - from) } #[inline] fn get_remaining_slice(&mut self) -> &'a mut [u8] { let start = self.position; let end = self.data.len(); self.get_slice_from_to(start, end) } } impl <'a> Message for PermMsg<'a> { fn get_sequence(&self) -> usize { self.sequence } fn get_data(&self) -> &[u8] { self.data } } impl <'a> Store<'a> for PermStore<'a> { type Msg = PermMsg<'a>; fn write<W>(&mut self, writer: W) -> PermMsg<'a> where W: FnOnce(&mut [u8]) -> usize { let start = self.position; self.position += writer(&mut self.get_remaining_slice()); self.sequence += 1; let seq = self.sequence; let pos = self.position; PermMsg { sequence: seq, data: self.get_slice_from_to(start, pos) } } } #[cfg(test)] pub mod test { use centrifuge::*; #[test] pub fn test_perm() { use centrifuge::perm::*; let mut sequence_nums = Vec::<usize>::new(); let mut log = vec![0; 16]; { let mut store = PermStore::new(&mut log); let mut centrifuge = Centrifuge::new(&mut store, |msg| { println!("Message received: {:?}", msg); sequence_nums.push(msg.get_sequence()); }); let data = b"hello"; centrifuge.receive_msg( &data[..] ); let data = b"bye"; centrifuge.receive_msg( &data[..] ); } assert_eq!(&vec![1, 2], &sequence_nums); assert_eq!(&b"hellobye"[..], &log[0..8]); } }
new
identifier_name
shootout-fasta-redux.rs
// The Computer Language Benchmarks Game // http://benchmarksgame.alioth.debian.org/ // // contributed by the Rust Project Developers // Copyright (c) 2013-2014 The Rust Project Developers // // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // // - Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // // - Redistributions in binary form must reproduce the above copyright // notice, this list of conditions and the following disclaimer in // the documentation and/or other materials provided with the // distribution. // // - Neither the name of "The Computer Language Benchmarks Game" nor // the name of "The Computer Language Shootout Benchmarks" nor the // names of its contributors may be used to endorse or promote // products derived from this software without specific prior // written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS // FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE // COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, // INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES // (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR // SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) // HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, // STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED // OF THE POSSIBILITY OF SUCH DAMAGE. #![feature(slicing_syntax)] use std::cmp::min; use std::io::{stdout, IoResult}; use std::os; use std::slice::bytes::copy_memory; const LINE_LEN: uint = 60; const LOOKUP_SIZE: uint = 4 * 1024; const LOOKUP_SCALE: f32 = (LOOKUP_SIZE - 1) as f32; // Random number generator constants const IM: u32 = 139968; const IA: u32 = 3877; const IC: u32 = 29573; const ALU: &'static str = "GGCCGGGCGCGGTGGCTCACGCCTGTAATCCCAGCACTTTG\ GGAGGCCGAGGCGGGCGGATCACCTGAGGTCAGGAGTTCGA\ GACCAGCCTGGCCAACATGGTGAAACCCCGTCTCTACTAAA\ AATACAAAAATTAGCCGGGCGTGGTGGCGCGCGCCTGTAAT\ CCCAGCTACTCGGGAGGCTGAGGCAGGAGAATCGCTTGAAC\ CCGGGAGGCGGAGGTTGCAGTGAGCCGAGATCGCGCCACTG\ CACTCCAGCCTGGGCGACAGAGCGAGACTCCGTCTCAAAAA"; const NULL_AMINO_ACID: AminoAcid = AminoAcid { c:'' as u8, p: 0.0 }; static IUB: [AminoAcid,..15] = [ AminoAcid { c: 'a' as u8, p: 0.27 }, AminoAcid { c: 'c' as u8, p: 0.12 }, AminoAcid { c: 'g' as u8, p: 0.12 }, AminoAcid { c: 't' as u8, p: 0.27 }, AminoAcid { c: 'B' as u8, p: 0.02 }, AminoAcid { c: 'D' as u8, p: 0.02 }, AminoAcid { c: 'H' as u8, p: 0.02 }, AminoAcid { c: 'K' as u8, p: 0.02 }, AminoAcid { c: 'M' as u8, p: 0.02 }, AminoAcid { c: 'N' as u8, p: 0.02 }, AminoAcid { c: 'R' as u8, p: 0.02 }, AminoAcid { c: 'S' as u8, p: 0.02 }, AminoAcid { c: 'V' as u8, p: 0.02 }, AminoAcid { c: 'W' as u8, p: 0.02 }, AminoAcid { c: 'Y' as u8, p: 0.02 }, ]; static HOMO_SAPIENS: [AminoAcid,..4] = [ AminoAcid { c: 'a' as u8, p: 0.3029549426680 }, AminoAcid { c: 'c' as u8, p: 0.1979883004921 }, AminoAcid { c: 'g' as u8, p: 0.1975473066391 }, AminoAcid { c: 't' as u8, p: 0.3015094502008 }, ]; // FIXME: Use map(). fn sum_and_scale(a: &'static [AminoAcid]) -> Vec<AminoAcid> { let mut result = Vec::new(); let mut p = 0f32; for a_i in a.iter() { let mut a_i = *a_i; p += a_i.p; a_i.p = p * LOOKUP_SCALE; result.push(a_i); } let result_len = result.len(); result[result_len - 1].p = LOOKUP_SCALE; result } struct AminoAcid { c: u8, p: f32, } struct RepeatFasta<'a, W:'a> {
impl<'a, W: Writer> RepeatFasta<'a, W> { fn new(alu: &'static str, w: &'a mut W) -> RepeatFasta<'a, W> { RepeatFasta { alu: alu, out: w } } fn make(&mut self, n: uint) -> IoResult<()> { let alu_len = self.alu.len(); let mut buf = Vec::from_elem(alu_len + LINE_LEN, 0u8); let alu: &[u8] = self.alu.as_bytes(); copy_memory(buf.as_mut_slice(), alu); let buf_len = buf.len(); copy_memory(buf[mut alu_len..buf_len], alu[..LINE_LEN]); let mut pos = 0; let mut bytes; let mut n = n; while n > 0 { bytes = min(LINE_LEN, n); try!(self.out.write(buf.slice(pos, pos + bytes))); try!(self.out.write_u8('\n' as u8)); pos += bytes; if pos > alu_len { pos -= alu_len; } n -= bytes; } Ok(()) } } fn make_lookup(a: &[AminoAcid]) -> [AminoAcid,..LOOKUP_SIZE] { let mut lookup = [ NULL_AMINO_ACID,..LOOKUP_SIZE ]; let mut j = 0; for (i, slot) in lookup.iter_mut().enumerate() { while a[j].p < (i as f32) { j += 1; } *slot = a[j]; } lookup } struct RandomFasta<'a, W:'a> { seed: u32, lookup: [AminoAcid,..LOOKUP_SIZE], out: &'a mut W, } impl<'a, W: Writer> RandomFasta<'a, W> { fn new(w: &'a mut W, a: &[AminoAcid]) -> RandomFasta<'a, W> { RandomFasta { seed: 42, out: w, lookup: make_lookup(a), } } fn rng(&mut self, max: f32) -> f32 { self.seed = (self.seed * IA + IC) % IM; max * (self.seed as f32) / (IM as f32) } fn nextc(&mut self) -> u8 { let r = self.rng(1.0); for a in self.lookup.iter() { if a.p >= r { return a.c; } } 0 } fn make(&mut self, n: uint) -> IoResult<()> { let lines = n / LINE_LEN; let chars_left = n % LINE_LEN; let mut buf = [0,..LINE_LEN + 1]; for _ in range(0, lines) { for i in range(0u, LINE_LEN) { buf[i] = self.nextc(); } buf[LINE_LEN] = '\n' as u8; try!(self.out.write(buf)); } for i in range(0u, chars_left) { buf[i] = self.nextc(); } self.out.write(buf[..chars_left]) } } fn main() { let args = os::args(); let args = args.as_slice(); let n = if args.len() > 1 { from_str::<uint>(args[1].as_slice()).unwrap() } else { 5 }; let mut out = stdout(); out.write_line(">ONE Homo sapiens alu").unwrap(); { let mut repeat = RepeatFasta::new(ALU, &mut out); repeat.make(n * 2).unwrap(); } out.write_line(">TWO IUB ambiguity codes").unwrap(); let iub = sum_and_scale(IUB); let mut random = RandomFasta::new(&mut out, iub.as_slice()); random.make(n * 3).unwrap(); random.out.write_line(">THREE Homo sapiens frequency").unwrap(); let homo_sapiens = sum_and_scale(HOMO_SAPIENS); random.lookup = make_lookup(homo_sapiens.as_slice()); random.make(n * 5).unwrap(); random.out.write_str("\n").unwrap(); }
alu: &'static str, out: &'a mut W }
random_line_split
shootout-fasta-redux.rs
// The Computer Language Benchmarks Game // http://benchmarksgame.alioth.debian.org/ // // contributed by the Rust Project Developers // Copyright (c) 2013-2014 The Rust Project Developers // // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // // - Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // // - Redistributions in binary form must reproduce the above copyright // notice, this list of conditions and the following disclaimer in // the documentation and/or other materials provided with the // distribution. // // - Neither the name of "The Computer Language Benchmarks Game" nor // the name of "The Computer Language Shootout Benchmarks" nor the // names of its contributors may be used to endorse or promote // products derived from this software without specific prior // written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS // FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE // COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, // INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES // (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR // SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) // HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, // STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED // OF THE POSSIBILITY OF SUCH DAMAGE. #![feature(slicing_syntax)] use std::cmp::min; use std::io::{stdout, IoResult}; use std::os; use std::slice::bytes::copy_memory; const LINE_LEN: uint = 60; const LOOKUP_SIZE: uint = 4 * 1024; const LOOKUP_SCALE: f32 = (LOOKUP_SIZE - 1) as f32; // Random number generator constants const IM: u32 = 139968; const IA: u32 = 3877; const IC: u32 = 29573; const ALU: &'static str = "GGCCGGGCGCGGTGGCTCACGCCTGTAATCCCAGCACTTTG\ GGAGGCCGAGGCGGGCGGATCACCTGAGGTCAGGAGTTCGA\ GACCAGCCTGGCCAACATGGTGAAACCCCGTCTCTACTAAA\ AATACAAAAATTAGCCGGGCGTGGTGGCGCGCGCCTGTAAT\ CCCAGCTACTCGGGAGGCTGAGGCAGGAGAATCGCTTGAAC\ CCGGGAGGCGGAGGTTGCAGTGAGCCGAGATCGCGCCACTG\ CACTCCAGCCTGGGCGACAGAGCGAGACTCCGTCTCAAAAA"; const NULL_AMINO_ACID: AminoAcid = AminoAcid { c:'' as u8, p: 0.0 }; static IUB: [AminoAcid,..15] = [ AminoAcid { c: 'a' as u8, p: 0.27 }, AminoAcid { c: 'c' as u8, p: 0.12 }, AminoAcid { c: 'g' as u8, p: 0.12 }, AminoAcid { c: 't' as u8, p: 0.27 }, AminoAcid { c: 'B' as u8, p: 0.02 }, AminoAcid { c: 'D' as u8, p: 0.02 }, AminoAcid { c: 'H' as u8, p: 0.02 }, AminoAcid { c: 'K' as u8, p: 0.02 }, AminoAcid { c: 'M' as u8, p: 0.02 }, AminoAcid { c: 'N' as u8, p: 0.02 }, AminoAcid { c: 'R' as u8, p: 0.02 }, AminoAcid { c: 'S' as u8, p: 0.02 }, AminoAcid { c: 'V' as u8, p: 0.02 }, AminoAcid { c: 'W' as u8, p: 0.02 }, AminoAcid { c: 'Y' as u8, p: 0.02 }, ]; static HOMO_SAPIENS: [AminoAcid,..4] = [ AminoAcid { c: 'a' as u8, p: 0.3029549426680 }, AminoAcid { c: 'c' as u8, p: 0.1979883004921 }, AminoAcid { c: 'g' as u8, p: 0.1975473066391 }, AminoAcid { c: 't' as u8, p: 0.3015094502008 }, ]; // FIXME: Use map(). fn sum_and_scale(a: &'static [AminoAcid]) -> Vec<AminoAcid> { let mut result = Vec::new(); let mut p = 0f32; for a_i in a.iter() { let mut a_i = *a_i; p += a_i.p; a_i.p = p * LOOKUP_SCALE; result.push(a_i); } let result_len = result.len(); result[result_len - 1].p = LOOKUP_SCALE; result } struct AminoAcid { c: u8, p: f32, } struct RepeatFasta<'a, W:'a> { alu: &'static str, out: &'a mut W } impl<'a, W: Writer> RepeatFasta<'a, W> { fn new(alu: &'static str, w: &'a mut W) -> RepeatFasta<'a, W> { RepeatFasta { alu: alu, out: w } } fn make(&mut self, n: uint) -> IoResult<()> { let alu_len = self.alu.len(); let mut buf = Vec::from_elem(alu_len + LINE_LEN, 0u8); let alu: &[u8] = self.alu.as_bytes(); copy_memory(buf.as_mut_slice(), alu); let buf_len = buf.len(); copy_memory(buf[mut alu_len..buf_len], alu[..LINE_LEN]); let mut pos = 0; let mut bytes; let mut n = n; while n > 0 { bytes = min(LINE_LEN, n); try!(self.out.write(buf.slice(pos, pos + bytes))); try!(self.out.write_u8('\n' as u8)); pos += bytes; if pos > alu_len { pos -= alu_len; } n -= bytes; } Ok(()) } } fn make_lookup(a: &[AminoAcid]) -> [AminoAcid,..LOOKUP_SIZE] { let mut lookup = [ NULL_AMINO_ACID,..LOOKUP_SIZE ]; let mut j = 0; for (i, slot) in lookup.iter_mut().enumerate() { while a[j].p < (i as f32) { j += 1; } *slot = a[j]; } lookup } struct RandomFasta<'a, W:'a> { seed: u32, lookup: [AminoAcid,..LOOKUP_SIZE], out: &'a mut W, } impl<'a, W: Writer> RandomFasta<'a, W> { fn new(w: &'a mut W, a: &[AminoAcid]) -> RandomFasta<'a, W> { RandomFasta { seed: 42, out: w, lookup: make_lookup(a), } } fn
(&mut self, max: f32) -> f32 { self.seed = (self.seed * IA + IC) % IM; max * (self.seed as f32) / (IM as f32) } fn nextc(&mut self) -> u8 { let r = self.rng(1.0); for a in self.lookup.iter() { if a.p >= r { return a.c; } } 0 } fn make(&mut self, n: uint) -> IoResult<()> { let lines = n / LINE_LEN; let chars_left = n % LINE_LEN; let mut buf = [0,..LINE_LEN + 1]; for _ in range(0, lines) { for i in range(0u, LINE_LEN) { buf[i] = self.nextc(); } buf[LINE_LEN] = '\n' as u8; try!(self.out.write(buf)); } for i in range(0u, chars_left) { buf[i] = self.nextc(); } self.out.write(buf[..chars_left]) } } fn main() { let args = os::args(); let args = args.as_slice(); let n = if args.len() > 1 { from_str::<uint>(args[1].as_slice()).unwrap() } else { 5 }; let mut out = stdout(); out.write_line(">ONE Homo sapiens alu").unwrap(); { let mut repeat = RepeatFasta::new(ALU, &mut out); repeat.make(n * 2).unwrap(); } out.write_line(">TWO IUB ambiguity codes").unwrap(); let iub = sum_and_scale(IUB); let mut random = RandomFasta::new(&mut out, iub.as_slice()); random.make(n * 3).unwrap(); random.out.write_line(">THREE Homo sapiens frequency").unwrap(); let homo_sapiens = sum_and_scale(HOMO_SAPIENS); random.lookup = make_lookup(homo_sapiens.as_slice()); random.make(n * 5).unwrap(); random.out.write_str("\n").unwrap(); }
rng
identifier_name
shootout-fasta-redux.rs
// The Computer Language Benchmarks Game // http://benchmarksgame.alioth.debian.org/ // // contributed by the Rust Project Developers // Copyright (c) 2013-2014 The Rust Project Developers // // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // // - Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // // - Redistributions in binary form must reproduce the above copyright // notice, this list of conditions and the following disclaimer in // the documentation and/or other materials provided with the // distribution. // // - Neither the name of "The Computer Language Benchmarks Game" nor // the name of "The Computer Language Shootout Benchmarks" nor the // names of its contributors may be used to endorse or promote // products derived from this software without specific prior // written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS // FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE // COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, // INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES // (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR // SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) // HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, // STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED // OF THE POSSIBILITY OF SUCH DAMAGE. #![feature(slicing_syntax)] use std::cmp::min; use std::io::{stdout, IoResult}; use std::os; use std::slice::bytes::copy_memory; const LINE_LEN: uint = 60; const LOOKUP_SIZE: uint = 4 * 1024; const LOOKUP_SCALE: f32 = (LOOKUP_SIZE - 1) as f32; // Random number generator constants const IM: u32 = 139968; const IA: u32 = 3877; const IC: u32 = 29573; const ALU: &'static str = "GGCCGGGCGCGGTGGCTCACGCCTGTAATCCCAGCACTTTG\ GGAGGCCGAGGCGGGCGGATCACCTGAGGTCAGGAGTTCGA\ GACCAGCCTGGCCAACATGGTGAAACCCCGTCTCTACTAAA\ AATACAAAAATTAGCCGGGCGTGGTGGCGCGCGCCTGTAAT\ CCCAGCTACTCGGGAGGCTGAGGCAGGAGAATCGCTTGAAC\ CCGGGAGGCGGAGGTTGCAGTGAGCCGAGATCGCGCCACTG\ CACTCCAGCCTGGGCGACAGAGCGAGACTCCGTCTCAAAAA"; const NULL_AMINO_ACID: AminoAcid = AminoAcid { c:'' as u8, p: 0.0 }; static IUB: [AminoAcid,..15] = [ AminoAcid { c: 'a' as u8, p: 0.27 }, AminoAcid { c: 'c' as u8, p: 0.12 }, AminoAcid { c: 'g' as u8, p: 0.12 }, AminoAcid { c: 't' as u8, p: 0.27 }, AminoAcid { c: 'B' as u8, p: 0.02 }, AminoAcid { c: 'D' as u8, p: 0.02 }, AminoAcid { c: 'H' as u8, p: 0.02 }, AminoAcid { c: 'K' as u8, p: 0.02 }, AminoAcid { c: 'M' as u8, p: 0.02 }, AminoAcid { c: 'N' as u8, p: 0.02 }, AminoAcid { c: 'R' as u8, p: 0.02 }, AminoAcid { c: 'S' as u8, p: 0.02 }, AminoAcid { c: 'V' as u8, p: 0.02 }, AminoAcid { c: 'W' as u8, p: 0.02 }, AminoAcid { c: 'Y' as u8, p: 0.02 }, ]; static HOMO_SAPIENS: [AminoAcid,..4] = [ AminoAcid { c: 'a' as u8, p: 0.3029549426680 }, AminoAcid { c: 'c' as u8, p: 0.1979883004921 }, AminoAcid { c: 'g' as u8, p: 0.1975473066391 }, AminoAcid { c: 't' as u8, p: 0.3015094502008 }, ]; // FIXME: Use map(). fn sum_and_scale(a: &'static [AminoAcid]) -> Vec<AminoAcid> { let mut result = Vec::new(); let mut p = 0f32; for a_i in a.iter() { let mut a_i = *a_i; p += a_i.p; a_i.p = p * LOOKUP_SCALE; result.push(a_i); } let result_len = result.len(); result[result_len - 1].p = LOOKUP_SCALE; result } struct AminoAcid { c: u8, p: f32, } struct RepeatFasta<'a, W:'a> { alu: &'static str, out: &'a mut W } impl<'a, W: Writer> RepeatFasta<'a, W> { fn new(alu: &'static str, w: &'a mut W) -> RepeatFasta<'a, W> { RepeatFasta { alu: alu, out: w } } fn make(&mut self, n: uint) -> IoResult<()> { let alu_len = self.alu.len(); let mut buf = Vec::from_elem(alu_len + LINE_LEN, 0u8); let alu: &[u8] = self.alu.as_bytes(); copy_memory(buf.as_mut_slice(), alu); let buf_len = buf.len(); copy_memory(buf[mut alu_len..buf_len], alu[..LINE_LEN]); let mut pos = 0; let mut bytes; let mut n = n; while n > 0 { bytes = min(LINE_LEN, n); try!(self.out.write(buf.slice(pos, pos + bytes))); try!(self.out.write_u8('\n' as u8)); pos += bytes; if pos > alu_len { pos -= alu_len; } n -= bytes; } Ok(()) } } fn make_lookup(a: &[AminoAcid]) -> [AminoAcid,..LOOKUP_SIZE] { let mut lookup = [ NULL_AMINO_ACID,..LOOKUP_SIZE ]; let mut j = 0; for (i, slot) in lookup.iter_mut().enumerate() { while a[j].p < (i as f32) { j += 1; } *slot = a[j]; } lookup } struct RandomFasta<'a, W:'a> { seed: u32, lookup: [AminoAcid,..LOOKUP_SIZE], out: &'a mut W, } impl<'a, W: Writer> RandomFasta<'a, W> { fn new(w: &'a mut W, a: &[AminoAcid]) -> RandomFasta<'a, W> { RandomFasta { seed: 42, out: w, lookup: make_lookup(a), } } fn rng(&mut self, max: f32) -> f32 { self.seed = (self.seed * IA + IC) % IM; max * (self.seed as f32) / (IM as f32) } fn nextc(&mut self) -> u8 { let r = self.rng(1.0); for a in self.lookup.iter() { if a.p >= r
} 0 } fn make(&mut self, n: uint) -> IoResult<()> { let lines = n / LINE_LEN; let chars_left = n % LINE_LEN; let mut buf = [0,..LINE_LEN + 1]; for _ in range(0, lines) { for i in range(0u, LINE_LEN) { buf[i] = self.nextc(); } buf[LINE_LEN] = '\n' as u8; try!(self.out.write(buf)); } for i in range(0u, chars_left) { buf[i] = self.nextc(); } self.out.write(buf[..chars_left]) } } fn main() { let args = os::args(); let args = args.as_slice(); let n = if args.len() > 1 { from_str::<uint>(args[1].as_slice()).unwrap() } else { 5 }; let mut out = stdout(); out.write_line(">ONE Homo sapiens alu").unwrap(); { let mut repeat = RepeatFasta::new(ALU, &mut out); repeat.make(n * 2).unwrap(); } out.write_line(">TWO IUB ambiguity codes").unwrap(); let iub = sum_and_scale(IUB); let mut random = RandomFasta::new(&mut out, iub.as_slice()); random.make(n * 3).unwrap(); random.out.write_line(">THREE Homo sapiens frequency").unwrap(); let homo_sapiens = sum_and_scale(HOMO_SAPIENS); random.lookup = make_lookup(homo_sapiens.as_slice()); random.make(n * 5).unwrap(); random.out.write_str("\n").unwrap(); }
{ return a.c; }
conditional_block
pipe_unix.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. use alloc::arc::Arc; use libc; use std::c_str::CString; use std::intrinsics; use std::io; use std::mem; use std::rt::rtio; use std::unstable::mutex; use super::{IoResult, retry}; use super::net; use super::util; use super::c; use super::file::fd_t; fn unix_socket(ty: libc::c_int) -> IoResult<fd_t> { match unsafe { libc::socket(libc::AF_UNIX, ty, 0) } { -1 => Err(super::last_error()), fd => Ok(fd) } } fn addr_to_sockaddr_un(addr: &CString) -> IoResult<(libc::sockaddr_storage, uint)> { // the sun_path length is limited to SUN_LEN (with null) assert!(mem::size_of::<libc::sockaddr_storage>() >= mem::size_of::<libc::sockaddr_un>()); let mut storage: libc::sockaddr_storage = unsafe { intrinsics::init() }; let s: &mut libc::sockaddr_un = unsafe { mem::transmute(&mut storage) }; let len = addr.len(); if len > s.sun_path.len() - 1 { return Err(io::IoError { kind: io::InvalidInput, desc: "path must be smaller than SUN_LEN", detail: None, }) } s.sun_family = libc::AF_UNIX as libc::sa_family_t; for (slot, value) in s.sun_path.mut_iter().zip(addr.iter()) { *slot = value; } // count the null terminator let len = mem::size_of::<libc::sa_family_t>() + len + 1; return Ok((storage, len)); } struct Inner { fd: fd_t, lock: mutex::NativeMutex, } impl Inner { fn new(fd: fd_t) -> Inner { Inner { fd: fd, lock: unsafe { mutex::NativeMutex::new() } } } } impl Drop for Inner { fn drop(&mut self) { unsafe { let _ = libc::close(self.fd); } } } fn connect(addr: &CString, ty: libc::c_int, timeout: Option<u64>) -> IoResult<Inner> { let (addr, len) = try!(addr_to_sockaddr_un(addr)); let inner = Inner::new(try!(unix_socket(ty))); let addrp = &addr as *_ as *libc::sockaddr; let len = len as libc::socklen_t; match timeout { None => { match retry(|| unsafe { libc::connect(inner.fd, addrp, len) }) { -1 => Err(super::last_error()), _ => Ok(inner) } } Some(timeout_ms) => { try!(util::connect_timeout(inner.fd, addrp, len, timeout_ms)); Ok(inner) } } } fn bind(addr: &CString, ty: libc::c_int) -> IoResult<Inner> { let (addr, len) = try!(addr_to_sockaddr_un(addr)); let inner = Inner::new(try!(unix_socket(ty))); let addrp = &addr as *libc::sockaddr_storage; match unsafe { libc::bind(inner.fd, addrp as *libc::sockaddr, len as libc::socklen_t) } { -1 => Err(super::last_error()), _ => Ok(inner) } } //////////////////////////////////////////////////////////////////////////////// // Unix Streams //////////////////////////////////////////////////////////////////////////////// pub struct UnixStream { inner: Arc<Inner>, read_deadline: u64, write_deadline: u64, } impl UnixStream { pub fn connect(addr: &CString, timeout: Option<u64>) -> IoResult<UnixStream> { connect(addr, libc::SOCK_STREAM, timeout).map(|inner| { UnixStream::new(Arc::new(inner)) }) } fn new(inner: Arc<Inner>) -> UnixStream { UnixStream { inner: inner, read_deadline: 0, write_deadline: 0, } } fn fd(&self) -> fd_t { self.inner.fd } #[cfg(target_os = "linux")] fn lock_nonblocking(&self) {} #[cfg(not(target_os = "linux"))] fn lock_nonblocking<'a>(&'a self) -> net::Guard<'a> { let ret = net::Guard { fd: self.fd(), guard: unsafe { self.inner.lock.lock() }, }; assert!(util::set_nonblocking(self.fd(), true).is_ok()); ret } } impl rtio::RtioPipe for UnixStream { fn read(&mut self, buf: &mut [u8]) -> IoResult<uint> { let fd = self.fd(); let dolock = || self.lock_nonblocking(); let doread = |nb| unsafe { let flags = if nb {c::MSG_DONTWAIT} else {0}; libc::recv(fd, buf.as_mut_ptr() as *mut libc::c_void, buf.len() as libc::size_t, flags) as libc::c_int }; net::read(fd, self.read_deadline, dolock, doread) } fn write(&mut self, buf: &[u8]) -> IoResult<()> { let fd = self.fd(); let dolock = || self.lock_nonblocking(); let dowrite = |nb: bool, buf: *u8, len: uint| unsafe { let flags = if nb {c::MSG_DONTWAIT} else {0}; libc::send(fd, buf as *mut libc::c_void, len as libc::size_t, flags) as i64 }; match net::write(fd, self.write_deadline, buf, true, dolock, dowrite) { Ok(_) => Ok(()), Err(e) => Err(e) } } fn clone(&self) -> Box<rtio::RtioPipe:Send> { box UnixStream::new(self.inner.clone()) as Box<rtio::RtioPipe:Send> } fn close_write(&mut self) -> IoResult<()> { super::mkerr_libc(unsafe { libc::shutdown(self.fd(), libc::SHUT_WR) }) } fn close_read(&mut self) -> IoResult<()> { super::mkerr_libc(unsafe { libc::shutdown(self.fd(), libc::SHUT_RD) }) } fn set_timeout(&mut self, timeout: Option<u64>) { let deadline = timeout.map(|a| ::io::timer::now() + a).unwrap_or(0); self.read_deadline = deadline; self.write_deadline = deadline; } fn set_read_timeout(&mut self, timeout: Option<u64>) { self.read_deadline = timeout.map(|a| ::io::timer::now() + a).unwrap_or(0); } fn set_write_timeout(&mut self, timeout: Option<u64>) { self.write_deadline = timeout.map(|a| ::io::timer::now() + a).unwrap_or(0); } } //////////////////////////////////////////////////////////////////////////////// // Unix Listener //////////////////////////////////////////////////////////////////////////////// pub struct UnixListener { inner: Inner, path: CString, } impl UnixListener { pub fn bind(addr: &CString) -> IoResult<UnixListener> { bind(addr, libc::SOCK_STREAM).map(|fd| { UnixListener { inner: fd, path: addr.clone() } }) } fn fd(&self) -> fd_t { self.inner.fd } pub fn native_listen(self, backlog: int) -> IoResult<UnixAcceptor> { match unsafe { libc::listen(self.fd(), backlog as libc::c_int) } { -1 => Err(super::last_error()), _ => Ok(UnixAcceptor { listener: self, deadline: 0 }) } } } impl rtio::RtioUnixListener for UnixListener { fn listen(~self) -> IoResult<Box<rtio::RtioUnixAcceptor:Send>> { self.native_listen(128).map(|a| { box a as Box<rtio::RtioUnixAcceptor:Send> }) } } pub struct UnixAcceptor { listener: UnixListener, deadline: u64, } impl UnixAcceptor { fn fd(&self) -> fd_t { self.listener.fd() } pub fn native_accept(&mut self) -> IoResult<UnixStream> { if self.deadline!= 0 { try!(util::await(self.fd(), Some(self.deadline), util::Readable)); } let mut storage: libc::sockaddr_storage = unsafe { intrinsics::init() }; let storagep = &mut storage as *mut libc::sockaddr_storage; let size = mem::size_of::<libc::sockaddr_storage>(); let mut size = size as libc::socklen_t; match retry(|| unsafe { libc::accept(self.fd(), storagep as *mut libc::sockaddr, &mut size as *mut libc::socklen_t) as libc::c_int }) { -1 => Err(super::last_error()), fd => Ok(UnixStream::new(Arc::new(Inner::new(fd)))) }
fn accept(&mut self) -> IoResult<Box<rtio::RtioPipe:Send>> { self.native_accept().map(|s| box s as Box<rtio::RtioPipe:Send>) } fn set_timeout(&mut self, timeout: Option<u64>) { self.deadline = timeout.map(|a| ::io::timer::now() + a).unwrap_or(0); } } impl Drop for UnixListener { fn drop(&mut self) { // Unlink the path to the socket to ensure that it doesn't linger. We're // careful to unlink the path before we close the file descriptor to // prevent races where we unlink someone else's path. unsafe { let _ = libc::unlink(self.path.with_ref(|p| p)); } } }
} } impl rtio::RtioUnixAcceptor for UnixAcceptor {
random_line_split
pipe_unix.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. use alloc::arc::Arc; use libc; use std::c_str::CString; use std::intrinsics; use std::io; use std::mem; use std::rt::rtio; use std::unstable::mutex; use super::{IoResult, retry}; use super::net; use super::util; use super::c; use super::file::fd_t; fn unix_socket(ty: libc::c_int) -> IoResult<fd_t> { match unsafe { libc::socket(libc::AF_UNIX, ty, 0) } { -1 => Err(super::last_error()), fd => Ok(fd) } } fn addr_to_sockaddr_un(addr: &CString) -> IoResult<(libc::sockaddr_storage, uint)> { // the sun_path length is limited to SUN_LEN (with null) assert!(mem::size_of::<libc::sockaddr_storage>() >= mem::size_of::<libc::sockaddr_un>()); let mut storage: libc::sockaddr_storage = unsafe { intrinsics::init() }; let s: &mut libc::sockaddr_un = unsafe { mem::transmute(&mut storage) }; let len = addr.len(); if len > s.sun_path.len() - 1 { return Err(io::IoError { kind: io::InvalidInput, desc: "path must be smaller than SUN_LEN", detail: None, }) } s.sun_family = libc::AF_UNIX as libc::sa_family_t; for (slot, value) in s.sun_path.mut_iter().zip(addr.iter()) { *slot = value; } // count the null terminator let len = mem::size_of::<libc::sa_family_t>() + len + 1; return Ok((storage, len)); } struct Inner { fd: fd_t, lock: mutex::NativeMutex, } impl Inner { fn new(fd: fd_t) -> Inner { Inner { fd: fd, lock: unsafe { mutex::NativeMutex::new() } } } } impl Drop for Inner { fn drop(&mut self) { unsafe { let _ = libc::close(self.fd); } } } fn connect(addr: &CString, ty: libc::c_int, timeout: Option<u64>) -> IoResult<Inner> { let (addr, len) = try!(addr_to_sockaddr_un(addr)); let inner = Inner::new(try!(unix_socket(ty))); let addrp = &addr as *_ as *libc::sockaddr; let len = len as libc::socklen_t; match timeout { None => { match retry(|| unsafe { libc::connect(inner.fd, addrp, len) }) { -1 => Err(super::last_error()), _ => Ok(inner) } } Some(timeout_ms) => { try!(util::connect_timeout(inner.fd, addrp, len, timeout_ms)); Ok(inner) } } } fn bind(addr: &CString, ty: libc::c_int) -> IoResult<Inner> { let (addr, len) = try!(addr_to_sockaddr_un(addr)); let inner = Inner::new(try!(unix_socket(ty))); let addrp = &addr as *libc::sockaddr_storage; match unsafe { libc::bind(inner.fd, addrp as *libc::sockaddr, len as libc::socklen_t) } { -1 => Err(super::last_error()), _ => Ok(inner) } } //////////////////////////////////////////////////////////////////////////////// // Unix Streams //////////////////////////////////////////////////////////////////////////////// pub struct UnixStream { inner: Arc<Inner>, read_deadline: u64, write_deadline: u64, } impl UnixStream { pub fn
(addr: &CString, timeout: Option<u64>) -> IoResult<UnixStream> { connect(addr, libc::SOCK_STREAM, timeout).map(|inner| { UnixStream::new(Arc::new(inner)) }) } fn new(inner: Arc<Inner>) -> UnixStream { UnixStream { inner: inner, read_deadline: 0, write_deadline: 0, } } fn fd(&self) -> fd_t { self.inner.fd } #[cfg(target_os = "linux")] fn lock_nonblocking(&self) {} #[cfg(not(target_os = "linux"))] fn lock_nonblocking<'a>(&'a self) -> net::Guard<'a> { let ret = net::Guard { fd: self.fd(), guard: unsafe { self.inner.lock.lock() }, }; assert!(util::set_nonblocking(self.fd(), true).is_ok()); ret } } impl rtio::RtioPipe for UnixStream { fn read(&mut self, buf: &mut [u8]) -> IoResult<uint> { let fd = self.fd(); let dolock = || self.lock_nonblocking(); let doread = |nb| unsafe { let flags = if nb {c::MSG_DONTWAIT} else {0}; libc::recv(fd, buf.as_mut_ptr() as *mut libc::c_void, buf.len() as libc::size_t, flags) as libc::c_int }; net::read(fd, self.read_deadline, dolock, doread) } fn write(&mut self, buf: &[u8]) -> IoResult<()> { let fd = self.fd(); let dolock = || self.lock_nonblocking(); let dowrite = |nb: bool, buf: *u8, len: uint| unsafe { let flags = if nb {c::MSG_DONTWAIT} else {0}; libc::send(fd, buf as *mut libc::c_void, len as libc::size_t, flags) as i64 }; match net::write(fd, self.write_deadline, buf, true, dolock, dowrite) { Ok(_) => Ok(()), Err(e) => Err(e) } } fn clone(&self) -> Box<rtio::RtioPipe:Send> { box UnixStream::new(self.inner.clone()) as Box<rtio::RtioPipe:Send> } fn close_write(&mut self) -> IoResult<()> { super::mkerr_libc(unsafe { libc::shutdown(self.fd(), libc::SHUT_WR) }) } fn close_read(&mut self) -> IoResult<()> { super::mkerr_libc(unsafe { libc::shutdown(self.fd(), libc::SHUT_RD) }) } fn set_timeout(&mut self, timeout: Option<u64>) { let deadline = timeout.map(|a| ::io::timer::now() + a).unwrap_or(0); self.read_deadline = deadline; self.write_deadline = deadline; } fn set_read_timeout(&mut self, timeout: Option<u64>) { self.read_deadline = timeout.map(|a| ::io::timer::now() + a).unwrap_or(0); } fn set_write_timeout(&mut self, timeout: Option<u64>) { self.write_deadline = timeout.map(|a| ::io::timer::now() + a).unwrap_or(0); } } //////////////////////////////////////////////////////////////////////////////// // Unix Listener //////////////////////////////////////////////////////////////////////////////// pub struct UnixListener { inner: Inner, path: CString, } impl UnixListener { pub fn bind(addr: &CString) -> IoResult<UnixListener> { bind(addr, libc::SOCK_STREAM).map(|fd| { UnixListener { inner: fd, path: addr.clone() } }) } fn fd(&self) -> fd_t { self.inner.fd } pub fn native_listen(self, backlog: int) -> IoResult<UnixAcceptor> { match unsafe { libc::listen(self.fd(), backlog as libc::c_int) } { -1 => Err(super::last_error()), _ => Ok(UnixAcceptor { listener: self, deadline: 0 }) } } } impl rtio::RtioUnixListener for UnixListener { fn listen(~self) -> IoResult<Box<rtio::RtioUnixAcceptor:Send>> { self.native_listen(128).map(|a| { box a as Box<rtio::RtioUnixAcceptor:Send> }) } } pub struct UnixAcceptor { listener: UnixListener, deadline: u64, } impl UnixAcceptor { fn fd(&self) -> fd_t { self.listener.fd() } pub fn native_accept(&mut self) -> IoResult<UnixStream> { if self.deadline!= 0 { try!(util::await(self.fd(), Some(self.deadline), util::Readable)); } let mut storage: libc::sockaddr_storage = unsafe { intrinsics::init() }; let storagep = &mut storage as *mut libc::sockaddr_storage; let size = mem::size_of::<libc::sockaddr_storage>(); let mut size = size as libc::socklen_t; match retry(|| unsafe { libc::accept(self.fd(), storagep as *mut libc::sockaddr, &mut size as *mut libc::socklen_t) as libc::c_int }) { -1 => Err(super::last_error()), fd => Ok(UnixStream::new(Arc::new(Inner::new(fd)))) } } } impl rtio::RtioUnixAcceptor for UnixAcceptor { fn accept(&mut self) -> IoResult<Box<rtio::RtioPipe:Send>> { self.native_accept().map(|s| box s as Box<rtio::RtioPipe:Send>) } fn set_timeout(&mut self, timeout: Option<u64>) { self.deadline = timeout.map(|a| ::io::timer::now() + a).unwrap_or(0); } } impl Drop for UnixListener { fn drop(&mut self) { // Unlink the path to the socket to ensure that it doesn't linger. We're // careful to unlink the path before we close the file descriptor to // prevent races where we unlink someone else's path. unsafe { let _ = libc::unlink(self.path.with_ref(|p| p)); } } }
connect
identifier_name
bytevec.rs
use std::fmt::Debug; use std::{fmt, ops}; /// Wrapper around `Vec<u8>` for efficient `AlgoIo` conversions when working with byte data /// /// Serde JSON serializes/deserializes `Vec<u8>` as an array of numbers. /// This type provides a more direct way of converting to/from `AlgoIo` without going through JSON. #[derive(Clone, Default, Eq, Hash, PartialEq, PartialOrd, Ord)] pub struct ByteVec { bytes: Vec<u8>, } impl ByteVec { /// Construct a new, empty `ByteVec`. pub fn new() -> Self { ByteVec::from(Vec::new()) } /// Construct a new, empty `ByteVec` with the specified capacity. pub fn with_capacity(cap: usize) -> Self { ByteVec::from(Vec::with_capacity(cap)) } /// Wrap existing bytes in a `ByteVec`. pub fn from<T: Into<Vec<u8>>>(bytes: T) -> Self { ByteVec { bytes: bytes.into(), } } } impl Debug for ByteVec { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { Debug::fmt(&self.bytes, f) } } impl From<ByteVec> for Vec<u8> { fn from(wrapper: ByteVec) -> Vec<u8> { wrapper.bytes } } impl From<Vec<u8>> for ByteVec { fn from(bytes: Vec<u8>) -> Self { ByteVec::from(bytes) } } impl AsRef<Vec<u8>> for ByteVec { fn as_ref(&self) -> &Vec<u8> { &self.bytes } } impl AsRef<[u8]> for ByteVec { fn as_ref(&self) -> &[u8] { &self.bytes } } impl AsMut<Vec<u8>> for ByteVec { fn as_mut(&mut self) -> &mut Vec<u8> { &mut self.bytes } } impl AsMut<[u8]> for ByteVec { fn as_mut(&mut self) -> &mut [u8] { &mut self.bytes } } impl ops::Deref for ByteVec { type Target = [u8]; fn
(&self) -> &[u8] { &self.bytes[..] } } impl ops::DerefMut for ByteVec { fn deref_mut(&mut self) -> &mut [u8] { &mut self.bytes[..] } }
deref
identifier_name
bytevec.rs
use std::fmt::Debug; use std::{fmt, ops}; /// Wrapper around `Vec<u8>` for efficient `AlgoIo` conversions when working with byte data /// /// Serde JSON serializes/deserializes `Vec<u8>` as an array of numbers. /// This type provides a more direct way of converting to/from `AlgoIo` without going through JSON. #[derive(Clone, Default, Eq, Hash, PartialEq, PartialOrd, Ord)] pub struct ByteVec { bytes: Vec<u8>, } impl ByteVec { /// Construct a new, empty `ByteVec`. pub fn new() -> Self { ByteVec::from(Vec::new()) } /// Construct a new, empty `ByteVec` with the specified capacity. pub fn with_capacity(cap: usize) -> Self { ByteVec::from(Vec::with_capacity(cap)) } /// Wrap existing bytes in a `ByteVec`.
} impl Debug for ByteVec { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { Debug::fmt(&self.bytes, f) } } impl From<ByteVec> for Vec<u8> { fn from(wrapper: ByteVec) -> Vec<u8> { wrapper.bytes } } impl From<Vec<u8>> for ByteVec { fn from(bytes: Vec<u8>) -> Self { ByteVec::from(bytes) } } impl AsRef<Vec<u8>> for ByteVec { fn as_ref(&self) -> &Vec<u8> { &self.bytes } } impl AsRef<[u8]> for ByteVec { fn as_ref(&self) -> &[u8] { &self.bytes } } impl AsMut<Vec<u8>> for ByteVec { fn as_mut(&mut self) -> &mut Vec<u8> { &mut self.bytes } } impl AsMut<[u8]> for ByteVec { fn as_mut(&mut self) -> &mut [u8] { &mut self.bytes } } impl ops::Deref for ByteVec { type Target = [u8]; fn deref(&self) -> &[u8] { &self.bytes[..] } } impl ops::DerefMut for ByteVec { fn deref_mut(&mut self) -> &mut [u8] { &mut self.bytes[..] } }
pub fn from<T: Into<Vec<u8>>>(bytes: T) -> Self { ByteVec { bytes: bytes.into(), } }
random_line_split
bytevec.rs
use std::fmt::Debug; use std::{fmt, ops}; /// Wrapper around `Vec<u8>` for efficient `AlgoIo` conversions when working with byte data /// /// Serde JSON serializes/deserializes `Vec<u8>` as an array of numbers. /// This type provides a more direct way of converting to/from `AlgoIo` without going through JSON. #[derive(Clone, Default, Eq, Hash, PartialEq, PartialOrd, Ord)] pub struct ByteVec { bytes: Vec<u8>, } impl ByteVec { /// Construct a new, empty `ByteVec`. pub fn new() -> Self { ByteVec::from(Vec::new()) } /// Construct a new, empty `ByteVec` with the specified capacity. pub fn with_capacity(cap: usize) -> Self { ByteVec::from(Vec::with_capacity(cap)) } /// Wrap existing bytes in a `ByteVec`. pub fn from<T: Into<Vec<u8>>>(bytes: T) -> Self { ByteVec { bytes: bytes.into(), } } } impl Debug for ByteVec { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { Debug::fmt(&self.bytes, f) } } impl From<ByteVec> for Vec<u8> { fn from(wrapper: ByteVec) -> Vec<u8> { wrapper.bytes } } impl From<Vec<u8>> for ByteVec { fn from(bytes: Vec<u8>) -> Self { ByteVec::from(bytes) } } impl AsRef<Vec<u8>> for ByteVec { fn as_ref(&self) -> &Vec<u8> { &self.bytes } } impl AsRef<[u8]> for ByteVec { fn as_ref(&self) -> &[u8]
} impl AsMut<Vec<u8>> for ByteVec { fn as_mut(&mut self) -> &mut Vec<u8> { &mut self.bytes } } impl AsMut<[u8]> for ByteVec { fn as_mut(&mut self) -> &mut [u8] { &mut self.bytes } } impl ops::Deref for ByteVec { type Target = [u8]; fn deref(&self) -> &[u8] { &self.bytes[..] } } impl ops::DerefMut for ByteVec { fn deref_mut(&mut self) -> &mut [u8] { &mut self.bytes[..] } }
{ &self.bytes }
identifier_body
main.rs
extern crate meltdown; extern crate url; extern crate gtk; use url::Url; use std::thread; use std::path::Path; use std::ffi::OsStr; use std::sync::mpsc::channel; use std::sync::mpsc::Sender; use gtk::prelude::*; use gtk::Builder; use gtk::MessageDialog; use meltdown::{manager, join_part_files, config}; pub enum UIMessage { Finished, Paused, Aborted } fn main() { if gtk::init().is_err() { println!("Failed to initialize GTK."); return; } let glade_src = include_str!("meltdown_ui.glade"); let builder = Builder::new(); builder.add_from_string(glade_src).unwrap(); let window: gtk::Window = builder.get_object("window").unwrap(); let open_button: gtk::ToolButton = builder.get_object("open_button").unwrap(); let text_view: gtk::TextView = builder.get_object("text_view").unwrap(); open_button.connect_clicked(move |_| { let text_buffer = text_view.get_buffer().unwrap(); let (left, right) = text_buffer.get_bounds(); let download_url = text_buffer.get_slice(&left, &right, false); let (tx, rx) = channel(); let handler = thread::spawn(move|| { init_manager(download_url.unwrap(), tx.clone()); }); }); window.connect_delete_event(|_, _| { gtk::main_quit(); Inhibit(false) }); window.show_all(); gtk::main(); } pub fn init_manager(url_vec: String, ui_sender: Sender<UIMessage>)
.max_connection(configurations.max_connection) .file(&file_name) .finish(); let complete_name = file_name.clone(); let (tx, rx) = channel(); let main_tx_clone = main_tx.clone(); let _ = thread::spawn(move || { match manager.start(rx) { manager::State::Completed(bytes) => { let ext = Path::new(&complete_name); let ext_str = ext.extension().unwrap_or(&OsStr::new("unknown")).to_str(); let mut prefix_nested = prefix.clone(); prefix_nested.push(complete_name.clone()); join_part_files(&complete_name, prefix_nested.to_str().unwrap(), ext_str.unwrap()); let _ = main_tx_clone.send(manager::State::Completed(bytes)); } manager::State::Aborted => { println!("A Network Error occured"); return; } _ => {} } }); } let mut complete_tasks = 0; loop { match main_rx.try_recv() { Ok(state) => { match state { manager::State::Completed(bytes) => { let _ = ui_sender.send(UIMessage::Finished); println!("Download Complete of {:?} bytes", bytes); } _ => {} } complete_tasks += 1; } Err(_) => {} } if complete_tasks == submitted_tasks { println!("All tasks complete"); break; } } }
{ let _ = config::setup_config_directories(); let configurations = config::read_config(); let url_vec = url_vec.split("\n").collect::<Vec<&str>>(); let submitted_tasks = url_vec.len(); let (main_tx, main_rx) = channel(); for url in url_vec { let prefix = config::default_cache_dir().unwrap(); let mut manager = manager::DownloadManager::new(); let download_url = match Url::parse(&url) { Ok(url) => url, Err(_) => { println!("{:?} is not a valid Url", url); continue } }; let url_path_vec = download_url.path_segments().unwrap().collect::<Vec<&str>>(); let file_name = url_path_vec[url_path_vec.len() - 1].to_owned(); manager.add_url(download_url.clone())
identifier_body
main.rs
extern crate meltdown; extern crate url; extern crate gtk; use url::Url; use std::thread; use std::path::Path; use std::ffi::OsStr; use std::sync::mpsc::channel; use std::sync::mpsc::Sender; use gtk::prelude::*; use gtk::Builder; use gtk::MessageDialog; use meltdown::{manager, join_part_files, config}; pub enum
{ Finished, Paused, Aborted } fn main() { if gtk::init().is_err() { println!("Failed to initialize GTK."); return; } let glade_src = include_str!("meltdown_ui.glade"); let builder = Builder::new(); builder.add_from_string(glade_src).unwrap(); let window: gtk::Window = builder.get_object("window").unwrap(); let open_button: gtk::ToolButton = builder.get_object("open_button").unwrap(); let text_view: gtk::TextView = builder.get_object("text_view").unwrap(); open_button.connect_clicked(move |_| { let text_buffer = text_view.get_buffer().unwrap(); let (left, right) = text_buffer.get_bounds(); let download_url = text_buffer.get_slice(&left, &right, false); let (tx, rx) = channel(); let handler = thread::spawn(move|| { init_manager(download_url.unwrap(), tx.clone()); }); }); window.connect_delete_event(|_, _| { gtk::main_quit(); Inhibit(false) }); window.show_all(); gtk::main(); } pub fn init_manager(url_vec: String, ui_sender: Sender<UIMessage>) { let _ = config::setup_config_directories(); let configurations = config::read_config(); let url_vec = url_vec.split("\n").collect::<Vec<&str>>(); let submitted_tasks = url_vec.len(); let (main_tx, main_rx) = channel(); for url in url_vec { let prefix = config::default_cache_dir().unwrap(); let mut manager = manager::DownloadManager::new(); let download_url = match Url::parse(&url) { Ok(url) => url, Err(_) => { println!("{:?} is not a valid Url", url); continue } }; let url_path_vec = download_url.path_segments().unwrap().collect::<Vec<&str>>(); let file_name = url_path_vec[url_path_vec.len() - 1].to_owned(); manager.add_url(download_url.clone()) .max_connection(configurations.max_connection) .file(&file_name) .finish(); let complete_name = file_name.clone(); let (tx, rx) = channel(); let main_tx_clone = main_tx.clone(); let _ = thread::spawn(move || { match manager.start(rx) { manager::State::Completed(bytes) => { let ext = Path::new(&complete_name); let ext_str = ext.extension().unwrap_or(&OsStr::new("unknown")).to_str(); let mut prefix_nested = prefix.clone(); prefix_nested.push(complete_name.clone()); join_part_files(&complete_name, prefix_nested.to_str().unwrap(), ext_str.unwrap()); let _ = main_tx_clone.send(manager::State::Completed(bytes)); } manager::State::Aborted => { println!("A Network Error occured"); return; } _ => {} } }); } let mut complete_tasks = 0; loop { match main_rx.try_recv() { Ok(state) => { match state { manager::State::Completed(bytes) => { let _ = ui_sender.send(UIMessage::Finished); println!("Download Complete of {:?} bytes", bytes); } _ => {} } complete_tasks += 1; } Err(_) => {} } if complete_tasks == submitted_tasks { println!("All tasks complete"); break; } } }
UIMessage
identifier_name
main.rs
extern crate meltdown; extern crate url; extern crate gtk; use url::Url; use std::thread; use std::path::Path; use std::ffi::OsStr; use std::sync::mpsc::channel; use std::sync::mpsc::Sender; use gtk::prelude::*; use gtk::Builder; use gtk::MessageDialog; use meltdown::{manager, join_part_files, config}; pub enum UIMessage {
Aborted } fn main() { if gtk::init().is_err() { println!("Failed to initialize GTK."); return; } let glade_src = include_str!("meltdown_ui.glade"); let builder = Builder::new(); builder.add_from_string(glade_src).unwrap(); let window: gtk::Window = builder.get_object("window").unwrap(); let open_button: gtk::ToolButton = builder.get_object("open_button").unwrap(); let text_view: gtk::TextView = builder.get_object("text_view").unwrap(); open_button.connect_clicked(move |_| { let text_buffer = text_view.get_buffer().unwrap(); let (left, right) = text_buffer.get_bounds(); let download_url = text_buffer.get_slice(&left, &right, false); let (tx, rx) = channel(); let handler = thread::spawn(move|| { init_manager(download_url.unwrap(), tx.clone()); }); }); window.connect_delete_event(|_, _| { gtk::main_quit(); Inhibit(false) }); window.show_all(); gtk::main(); } pub fn init_manager(url_vec: String, ui_sender: Sender<UIMessage>) { let _ = config::setup_config_directories(); let configurations = config::read_config(); let url_vec = url_vec.split("\n").collect::<Vec<&str>>(); let submitted_tasks = url_vec.len(); let (main_tx, main_rx) = channel(); for url in url_vec { let prefix = config::default_cache_dir().unwrap(); let mut manager = manager::DownloadManager::new(); let download_url = match Url::parse(&url) { Ok(url) => url, Err(_) => { println!("{:?} is not a valid Url", url); continue } }; let url_path_vec = download_url.path_segments().unwrap().collect::<Vec<&str>>(); let file_name = url_path_vec[url_path_vec.len() - 1].to_owned(); manager.add_url(download_url.clone()) .max_connection(configurations.max_connection) .file(&file_name) .finish(); let complete_name = file_name.clone(); let (tx, rx) = channel(); let main_tx_clone = main_tx.clone(); let _ = thread::spawn(move || { match manager.start(rx) { manager::State::Completed(bytes) => { let ext = Path::new(&complete_name); let ext_str = ext.extension().unwrap_or(&OsStr::new("unknown")).to_str(); let mut prefix_nested = prefix.clone(); prefix_nested.push(complete_name.clone()); join_part_files(&complete_name, prefix_nested.to_str().unwrap(), ext_str.unwrap()); let _ = main_tx_clone.send(manager::State::Completed(bytes)); } manager::State::Aborted => { println!("A Network Error occured"); return; } _ => {} } }); } let mut complete_tasks = 0; loop { match main_rx.try_recv() { Ok(state) => { match state { manager::State::Completed(bytes) => { let _ = ui_sender.send(UIMessage::Finished); println!("Download Complete of {:?} bytes", bytes); } _ => {} } complete_tasks += 1; } Err(_) => {} } if complete_tasks == submitted_tasks { println!("All tasks complete"); break; } } }
Finished, Paused,
random_line_split
main.rs
extern crate meltdown; extern crate url; extern crate gtk; use url::Url; use std::thread; use std::path::Path; use std::ffi::OsStr; use std::sync::mpsc::channel; use std::sync::mpsc::Sender; use gtk::prelude::*; use gtk::Builder; use gtk::MessageDialog; use meltdown::{manager, join_part_files, config}; pub enum UIMessage { Finished, Paused, Aborted } fn main() { if gtk::init().is_err() { println!("Failed to initialize GTK."); return; } let glade_src = include_str!("meltdown_ui.glade"); let builder = Builder::new(); builder.add_from_string(glade_src).unwrap(); let window: gtk::Window = builder.get_object("window").unwrap(); let open_button: gtk::ToolButton = builder.get_object("open_button").unwrap(); let text_view: gtk::TextView = builder.get_object("text_view").unwrap(); open_button.connect_clicked(move |_| { let text_buffer = text_view.get_buffer().unwrap(); let (left, right) = text_buffer.get_bounds(); let download_url = text_buffer.get_slice(&left, &right, false); let (tx, rx) = channel(); let handler = thread::spawn(move|| { init_manager(download_url.unwrap(), tx.clone()); }); }); window.connect_delete_event(|_, _| { gtk::main_quit(); Inhibit(false) }); window.show_all(); gtk::main(); } pub fn init_manager(url_vec: String, ui_sender: Sender<UIMessage>) { let _ = config::setup_config_directories(); let configurations = config::read_config(); let url_vec = url_vec.split("\n").collect::<Vec<&str>>(); let submitted_tasks = url_vec.len(); let (main_tx, main_rx) = channel(); for url in url_vec { let prefix = config::default_cache_dir().unwrap(); let mut manager = manager::DownloadManager::new(); let download_url = match Url::parse(&url) { Ok(url) => url, Err(_) =>
}; let url_path_vec = download_url.path_segments().unwrap().collect::<Vec<&str>>(); let file_name = url_path_vec[url_path_vec.len() - 1].to_owned(); manager.add_url(download_url.clone()) .max_connection(configurations.max_connection) .file(&file_name) .finish(); let complete_name = file_name.clone(); let (tx, rx) = channel(); let main_tx_clone = main_tx.clone(); let _ = thread::spawn(move || { match manager.start(rx) { manager::State::Completed(bytes) => { let ext = Path::new(&complete_name); let ext_str = ext.extension().unwrap_or(&OsStr::new("unknown")).to_str(); let mut prefix_nested = prefix.clone(); prefix_nested.push(complete_name.clone()); join_part_files(&complete_name, prefix_nested.to_str().unwrap(), ext_str.unwrap()); let _ = main_tx_clone.send(manager::State::Completed(bytes)); } manager::State::Aborted => { println!("A Network Error occured"); return; } _ => {} } }); } let mut complete_tasks = 0; loop { match main_rx.try_recv() { Ok(state) => { match state { manager::State::Completed(bytes) => { let _ = ui_sender.send(UIMessage::Finished); println!("Download Complete of {:?} bytes", bytes); } _ => {} } complete_tasks += 1; } Err(_) => {} } if complete_tasks == submitted_tasks { println!("All tasks complete"); break; } } }
{ println!("{:?} is not a valid Url", url); continue }
conditional_block
associated-types-eq-hr.rs
// Check testing of equality constraints in a higher-ranked context. pub trait TheTrait<T> { type A; fn get(&self, t: T) -> Self::A; } struct IntStruct { x: isize, } impl<'a> TheTrait<&'a isize> for IntStruct { type A = &'a isize; fn get(&self, t: &'a isize) -> &'a isize { t } } struct UintStruct { x: isize, } impl<'a> TheTrait<&'a isize> for UintStruct { type A = &'a usize; fn get(&self, t: &'a isize) -> &'a usize { panic!() } } struct Tuple {} impl<'a> TheTrait<(&'a isize, &'a isize)> for Tuple { type A = &'a isize; fn get(&self, t: (&'a isize, &'a isize)) -> &'a isize { t.0 } } fn foo<T>() where T: for<'x> TheTrait<&'x isize, A = &'x isize>, { // ok for IntStruct, but not UintStruct } fn bar<T>() where T: for<'x> TheTrait<&'x isize, A = &'x usize>, { // ok for UintStruct, but not IntStruct } fn tuple_one<T>() where T: for<'x, 'y> TheTrait<(&'x isize, &'y isize), A = &'x isize>,
fn tuple_two<T>() where T: for<'x, 'y> TheTrait<(&'x isize, &'y isize), A = &'y isize>, { // not ok for tuple, two lifetimes and we pick second } fn tuple_three<T>() where T: for<'x> TheTrait<(&'x isize, &'x isize), A = &'x isize>, { // ok for tuple } fn tuple_four<T>() where T: for<'x, 'y> TheTrait<(&'x isize, &'y isize)>, { // not ok for tuple, two lifetimes, and lifetime matching is invariant } pub fn call_foo() { foo::<IntStruct>(); foo::<UintStruct>(); //~ ERROR type mismatch } pub fn call_bar() { bar::<IntStruct>(); //~ ERROR type mismatch bar::<UintStruct>(); } pub fn call_tuple_one() { tuple_one::<Tuple>(); //~^ ERROR implementation of `TheTrait` is not general enough //~| ERROR implementation of `TheTrait` is not general enough } pub fn call_tuple_two() { tuple_two::<Tuple>(); //~^ ERROR implementation of `TheTrait` is not general enough //~| ERROR implementation of `TheTrait` is not general enough } pub fn call_tuple_three() { tuple_three::<Tuple>(); } pub fn call_tuple_four() { tuple_four::<Tuple>(); //~^ ERROR implementation of `TheTrait` is not general enough } fn main() {}
{ // not ok for tuple, two lifetimes and we pick first }
identifier_body